handler.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #pragma once
  2. #include <string>
  3. #include "common/i18n.h"
  4. #include "config/app_config.h"
  5. #include "db/mysql_service.h"
  6. #include "net/protocol.h"
  7. #include "net/session.h"
  8. #include "util/json.h"
  9. namespace im {
  10. class ImServer;
  11. // 单次请求上下文。由 Dispatcher 写入 IHandler,业务 handle() 不再传参。
  12. struct HandlerContext {
  13. SessionPtr session;
  14. Packet packet;
  15. ImServer* server = nullptr;
  16. MysqlService* mysql = nullptr;
  17. const AppConfig* config = nullptr;
  18. };
  19. // 业务 Handler 基类。按 Type 分发;子类在 handle() 内解析 Cmd。
  20. class IHandler {
  21. public:
  22. virtual ~IHandler() = default;
  23. void process(HandlerContext ctx);
  24. protected:
  25. virtual void handle() = 0;
  26. Cmd cmd() const;
  27. Type type() const;
  28. SessionPtr& session();
  29. ImServer& server();
  30. MysqlService* mysql();
  31. const AppConfig& config();
  32. const Packet& packet() const;
  33. // 读本次请求 JSON 字段;缺少返回空串 / fallback。
  34. // 非法 JSON 已在 process() 回错,不会进入 handle()。
  35. std::string json_str(const char* key);
  36. int64 json_i64(const char* key, int64 fallback = 0);
  37. bool json_has(const char* key);
  38. const ylib::json& json_body() const { return req_; }
  39. void reply_ok();
  40. void reply_ok(ylib::json body);
  41. ylib::json limits_json();
  42. ylib::json cdn_json();
  43. ylib::json update_json();
  44. // 按本连接 Session 语言翻译 Msg
  45. void reply_error(int code, i18n::Msg msg);
  46. // 原文回传(如三方短信错误)
  47. void reply_error(int code, const std::string& msg);
  48. i18n::Lang reply_lang() const;
  49. void push(ConnId connid, Type type, Cmd cmd, const ylib::json& body);
  50. bool require_login();
  51. HandlerContext ctx_;
  52. private:
  53. void send_reply(const ylib::json& body);
  54. ylib::json req_;
  55. };
  56. } // namespace im