You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.3 KiB
C++

#ifndef HTTP_SERVER_H
#define HTTP_SERVER_H
#include <string>
#include <map>
#include <vector>
#include <functional>
class HTTPServer {
public:
// 构造函数和析构函数
HTTPServer(int port = 8080);
~HTTPServer();
//消息
std::string PostMsg;
// 服务器控制方法
bool start();
void run();
void stop();
void SetPort(int port);
// 回调函数类型定义
using RequestHandler = std::function<void(int, const std::string&, const std::map<std::string, std::string>&, const std::string&)>;
// 设置自定义请求处理器
void setRequestHandler(const RequestHandler& handler);
// 静态工具方法
static std::string urlDecode(const std::string& encoded);
static std::map<std::string, std::string> parseQueryString(const std::string& query);
static std::map<std::string, std::string> parseHeaders(const std::string& headers);
static std::string getContentType(const std::map<std::string, std::string>& headers);
static int getContentLength(const std::map<std::string, std::string>& headers);
// 响应方法
static void sendResponse(int client_socket, const std::string& response,
const std::string& content_type = "text/html; charset=utf-8");
static void sendError(int client_socket, int code, const std::string& message);
static void sendJSONResponse(int client_socket, const std::string& json);
private:
// 私有方法
std::string readFullRequest(int client_socket, int timeout_ms = 5000);
bool isRequestComplete(const std::string& request);
void handleConnection(int client_socket, const std::string& client_ip);
void handleRequest(int client_socket, const std::string& request);
void handlePOST(int client_socket, const std::string& request,
const std::map<std::string, std::string>& headers);
void handleGET(int client_socket, const std::string& request_line);
void logRequest(const std::string& method, const std::string& client_ip,
const std::map<std::string, std::string>& headers);
// 私有成员变量
int server_fd;
int port;
RequestHandler custom_handler;
// 禁用复制和赋值
HTTPServer(const HTTPServer&) = delete;
HTTPServer& operator=(const HTTPServer&) = delete;
};
#endif // HTTP_SERVER_H