#pragma once #include #include "common/i18n.h" #include "config/app_config.h" #include "db/mysql_service.h" #include "net/protocol.h" #include "net/session.h" #include "util/json.h" namespace im { class ImServer; // 单次请求上下文。由 Dispatcher 写入 IHandler,业务 handle() 不再传参。 struct HandlerContext { SessionPtr session; Packet packet; ImServer* server = nullptr; MysqlService* mysql = nullptr; const AppConfig* config = nullptr; }; // 业务 Handler 基类。按 Type 分发;子类在 handle() 内解析 Cmd。 class IHandler { public: virtual ~IHandler() = default; void process(HandlerContext ctx); protected: virtual void handle() = 0; Cmd cmd() const; Type type() const; SessionPtr& session(); ImServer& server(); MysqlService* mysql(); const AppConfig& config(); const Packet& packet() const; // 读本次请求 JSON 字段;缺少返回空串 / fallback。 // 非法 JSON 已在 process() 回错,不会进入 handle()。 std::string json_str(const char* key); int64 json_i64(const char* key, int64 fallback = 0); bool json_has(const char* key); const ylib::json& json_body() const { return req_; } void reply_ok(); void reply_ok(ylib::json body); ylib::json limits_json(); ylib::json cdn_json(); ylib::json update_json(); // 按本连接 Session 语言翻译 Msg void reply_error(int code, i18n::Msg msg); // 原文回传(如三方短信错误) void reply_error(int code, const std::string& msg); i18n::Lang reply_lang() const; void push(ConnId connid, Type type, Cmd cmd, const ylib::json& body); bool require_login(); HandlerContext ctx_; private: void send_reply(const ylib::json& body); ylib::json req_; }; } // namespace im