forked from caozhiyi/CppNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpServer.cpp
68 lines (51 loc) · 1.73 KB
/
HttpServer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "HttpServer.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
#include "HttpContext.h"
using namespace cppnet;
base::CTimeTool CHttpServer::_time_tool;
CHttpServer::CHttpServer() {
}
CHttpServer::~CHttpServer() {
}
void CHttpServer::OnConnection(const cppnet::Handle& handle, uint32_t err) {
if (err == CEC_SUCCESS) {
std::unique_lock<std::mutex> lock(_mutex);
if (_context_map.find(handle) == _context_map.end()) {
_context_map[handle] = CHttpContext();
}
}
}
void CHttpServer::OnMessage(const cppnet::Handle& handle, base::CBuffer* data,
uint32_t, uint32_t err) {
if (err != CEC_SUCCESS) {
return;
}
_mutex.lock();
CHttpContext& context = _context_map[handle];
_mutex.unlock();
_time_tool.Now();
if (!context.ParseRequest(data, _time_tool.GetMsec())) {
cppnet::Write(handle, "HTTP/1.1 400 Bad Request\r\n\r\n", sizeof("HTTP/1.1 400 Bad Request\r\n\r\n"));
cppnet::Close(handle);
}
if (context.IsGotAll()) {
OnRequest(handle, context.GetRequest());
context.Reset();
}
}
void CHttpServer::OnMessageSend(const cppnet::Handle& , uint32_t , uint32_t ) {
// do nothing.
}
void CHttpServer::OnRequest(const cppnet::Handle& handle, const CHttpRequest& req) {
const std::string& connection = req.GetHeader("Connection");
bool close = connection == "close" ||
(req.GetVersion() == Http10 && connection != "Keep-Alive");
CHttpResponse response(close);
_http_call_back(req, response);
std::string res = response.GetSendBuffer();
cppnet::Write(handle, res.c_str(), res.length());
if (response.GetCloseConnection()) {
cppnet::Close(handle);
}
}