#pragma once
#include "mongoose.h"
#include
#include
#include
#include
#include
// å®ä¹httpè¿åcallback
typedef void OnRspCallback(mg_connection *c, std::string);
// å®ä¹http请æ±handler
using ReqHandler = std::function;
class HttpServer
{
public:
HttpServer() {}
~HttpServer() {}
void Init(const std::string &port, const std::string &rootdir = ".wwwroot"); // åå§å设置
bool Start(); // å¯å¨httpserver
bool Close(); // å
³é
void AddHandler(const std::string &url, ReqHandler req_handler); // 注åäºä»¶å¤ç彿°
void RemoveHandler(const std::string &url); // ç§»é¤æ¶é´å¤ç彿°
private:
// éæäºä»¶ååºå½æ°
static void OnHttpWebsocketEvent(mg_connection *connection, int event_type, void *event_data);
static void HandleHttpEvent(mg_connection *connection, http_message *http_req);
static void SendHttpRsp(mg_connection *connection, std::string rsp);
static int isWebsocket(const mg_connection *connection); // 夿æ¯å¦æ¯websoketç±»åè¿æ¥
static void HandleWebsocketMessage(mg_connection *connection, int event_type, websocket_message *ws_msg);
static void SendWebsocketMsg(mg_connection *connection, std::string msg); // åéæ¶æ¯å°æå®è¿æ¥
static void BroadcastWebsocketMsg(std::string msg); // ç»ææè¿æ¥å¹¿ææ¶æ¯
static std::unordered_set s_websocket_session_set; // ç¼åwebsocketè¿æ¥
std::string m_port; // 端å£
mg_mgr m_mgr; // è¿æ¥ç®¡çå¨
static mg_serve_http_opts mServerOptions;
static std::unordered_map<:string reqhandler> s_handler_map; // åè°å½æ°æ å°è¡¨
};