-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestHandler.cpp
128 lines (102 loc) · 2.57 KB
/
RequestHandler.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "RequestHandler.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
#include "HttpResponse.h"
#include "HttpRequest.h"
#include "DeviceData.h"
namespace http {
namespace server {
const std::string RequestHandler::BASE_FILENAME = "prefixes";
RequestHandler::RequestHandler() : prefixesBase_(new DeviceTrie())
{
initPrefixBase();
}
void RequestHandler::handleRequest(
const HttpRequest& request,
HttpResponse& response
)
{
std::string requestPath;
if (!urlDecode(request.uri, requestPath)) {
//std::cout << "decode uri error" << std::endl;
response = HttpResponse::defaultResponse(HttpResponse::bad_request);
return;
}
std::string userAgent = requestPath.substr(5);
TrieNode<Device> *result = prefixesBase_->find(userAgent);
if (result)
createResponse(response, *result);
else {
response = HttpResponse::defaultResponse(HttpResponse::not_found);
return;
}
response.status = HttpResponse::ok;
response.headers.resize(1);
response.headers[0].name = "Content-Type";
response.headers[0].value = "text/plain";
}
bool RequestHandler::urlDecode(const std::string& in, std::string& out)
{
out.clear();
out.reserve(in.size());
for (std::size_t i = 0; i < in.size(); ++i) {
if (in[i] == '%') {
if (i + 3 <= in.size()) {
int value;
std::istringstream is(in.substr(i + 1, 2));
if (is >> std::hex >> value) {
out += static_cast<char>(value);
i += 2;
} else {
return false;
}
} else {
return false;
}
} else if (in[i] == '+') {
out += ' ';
} else {
out += in[i];
}
}
return true;
}
void RequestHandler::initPrefixBase()
{
using namespace boost::spirit::classic;
std::string input;
DeviceDataParser parser(*prefixesBase_);
std::ifstream prefixesFile(BASE_FILENAME.c_str());
if (prefixesFile.is_open()) {
while (!prefixesFile.eof()) {
getline(prefixesFile, input);
parse_info<> info = parse(
input.c_str(),
parser,
nothing_p
);
if (!info.hit) {
std::cout << "E:" << input.c_str() << std::endl;
}
}
prefixesFile.close();
}
}
void RequestHandler::createResponse(HttpResponse& response, TrieNode<Device>& node)
{
char buf[128];
Device* d = const_cast<Device*>(node.getObject());
sprintf(
buf,
"model_id:%d;brand_id:%d;mobile_device:%d;",
d->modelId,
d->brandId,
d->mobileDevice
);
response.content.append(buf);
}
}
}