CreoOtkPluging/HttpServer_fixed.h
2025-07-16 17:16:59 +08:00

57 lines
1.5 KiB
C++

#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <map>
#include <functional>
#include "Config.h"
// HTTP请求结构
struct HttpRequest {
std::string method;
std::string path;
std::string query;
std::map<std::string, std::string> headers;
std::string body;
};
// HTTP响应结构
struct HttpResponse {
int status_code = 200;
std::map<std::string, std::string> headers;
std::string body;
HttpResponse() {
headers["Content-Type"] = "application/json";
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
headers["Access-Control-Allow-Headers"] = "Content-Type";
}
};
// HTTP服务器类
class HttpServer {
public:
HttpServer();
~HttpServer();
bool Start();
void Stop();
bool IsRunning() const { return running_; }
// 设置路由处理器
void SetRouteHandler(const std::string& path,
std::function<HttpResponse(const HttpRequest&)> handler);
private:
static DWORD WINAPI ServerThread(LPVOID lpParam);
void HandleClient(SOCKET client_socket);
HttpRequest ParseRequest(const std::string& raw_request);
void SendResponse(SOCKET client_socket, const HttpResponse& response);
SOCKET server_socket_;
volatile bool running_;
HANDLE thread_handle_;
std::map<std::string, std::function<HttpResponse(const HttpRequest&)>> route_handlers_;
};