1 Star 0 Fork 0

Aurora/Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
HttpServer.hpp 3.10 KB
一键复制 编辑 原始数据 按行查看 历史
Aurora 提交于 2025-07-13 00:44 +08:00 . 完整版httpserver
#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
using namespace TcpServerModule;
using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;
class HttpServer
{
public:
HttpServer(int port)
: _tsvr(std::make_unique<TcpServer>(port))
{
}
void Resgiter(std::string funcname, http_handler_t func)
{
_route[funcname] = func;
}
bool SafeCheck(const std::string &service)
{
auto iter = _route.find(service);
return iter != _route.end();
}
void Start()
{
_tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
{ return this->HandlerRequest(sockfd, client); });
_tsvr->Loop();
}
// 就是我们处理http的入口
bool HandlerRequest(SockPtr sockfd, InetAddr client)
{
LOG(LogLevel::DEBUG) << "HttPserver: get a new client: " << sockfd->Fd() << "addr info:" << client.Addr();
std::string http_request;
sockfd->Recv(&http_request);
HttpRequest req;
req.Deserialize(http_request);
HttpResponse resp;
// std::cout << "用户想要: " << req.Uri() << std::endl;
// req.GetContent();
// req.Print();
// 请求应该被分成两类:1.请求一般的静态资源 2.提交参数,携带参数,需要我们进行交互设置
if (req.IsHasArgs())
{
std::cout << "--------------IsHasArgs()" << std::endl;
// 2.提交参数,携带参数,需要我们进行交互设置
std::string service = req.Path();
if (SafeCheck(service))
_route[req.Path()](req, resp); // login
else
resp.Build(req);
}
else
{
std::cout << "--------------Non IsHasArgs()" << std::endl;
resp.Build(req);
}
std::string resp_str;
resp.Seserialize(&resp_str);
sockfd->Send(resp_str);
return true;
// std::cout << http_request; // 字节流的请求
// 读取请求,对请求进行分析处理 --> 文本处理!
// 1.读取请求的完整性 --- 暂时不做
// 2.完整http反序列化http responce序列化...
// demo 1:直接返回一个固定的内容
// std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine; // BlankLine 至少有状态行+空行
// // 直接返回一个html网页
// std::string body = " <!DOCTYPE html> <html lang=\"zh-CN\">\
// <head>\
// <meta charset=\"UTF-8\">\
// <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\
// <title>Hello World</title>\
// </head>\
// <body>\
// Hello World\
// </body>\
// </html> ";
// std::string httpresponse = status_line + body;
// sockfd->Send(httpresponse);
return true;
}
~HttpServer()
{
}
private:
std::unique_ptr<TcpServer> _tsvr;
std::unordered_map<std::string, http_handler_t> _route; // 功能路由
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/Axurea/linux.git
git@gitee.com:Axurea/linux.git
Axurea
linux
Linux
master

搜索帮助