-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.cpp
102 lines (93 loc) · 3.2 KB
/
helpers.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
#include "helpers.h"
#include "http_parser.h"
namespace {
const std::string empty_body("{}");
}
void NotFound(int http_method, http_response& res) {
static const std::string not_found_post("HTTP/1.1 404 Not Found\r\n"
"S: b\r\n"
"C: k\r\n"
"B: a\r\n"
"Content-Length: 0\r\n"
"\r\n");
static const std::string not_found_get("HTTP/1.1 404 Not Found\r\n"
"S: b\r\n"
"C: k\r\n"
"B: a\r\n"
"Content-Length: 0\r\n"
"\r\n");
if (http_method == HTTP_POST) {
res.iov[0].iov_base = (void*)not_found_post.c_str();
res.iov[0].iov_len = not_found_post.length();
} else {
res.iov[0].iov_base = (void*)not_found_get.c_str();
res.iov[0].iov_len = not_found_get.length();
}
res.iov_size = 1;
}
void BadRequest(int http_method, http_response& res) {
static const std::string bad_data_post("HTTP/1.1 400 Bad Request\r\n"
"S: b\r\n"
"C: k\r\n"
"B: a\r\n"
"Content-Length: 0\r\n"
"\r\n");
static const std::string bad_data_get("HTTP/1.1 400 Bad Request\r\n"
"S: b\r\n"
"C: k\r\n"
"B: a\r\n"
"Content-Length: 0\r\n"
"\r\n");
if (http_method == HTTP_POST) {
res.iov[0].iov_base = (void*)bad_data_post.c_str();
res.iov[0].iov_len = bad_data_post.length();
} else {
res.iov[0].iov_base = (void*)bad_data_get.c_str();
res.iov[0].iov_len = bad_data_get.length();
}
res.iov_size = 1;
}
void SendResponse(http_response& res, const std::string& data) {
res.iov[0].iov_base = (void*)data.c_str();
res.iov[0].iov_len = data.length();
res.iov_size = 1;
}
void SendOk(http_response& res) {
static const std::string ok = "HTTP/1.1 200 OK\r\n"
"S: b\r\n"
"C: k\r\n"
"B: a\r\n"
"Content-Length: 2\r\n"
"\r\n"
"{}";
res.iov[0].iov_base = (void*)ok.c_str();
res.iov[0].iov_len = ok.length();
res.iov_size = 1;
}
bool GetInt(const char* val, int* output) {
int base = 1;
uint32_t number = 0;
int sign = 1;
if (*val == '-') {
sign = -1;
val++;
}
if (!GetUint32(val, &number)) {
return false;
}
*output = number * sign;
return true;
}
bool GetUint32(const char* val, uint32_t* output) {
int base = 10;
int number = 0;
while (*val) {
if (*val < '0' || *val > '9') {
return false;
}
number = number * base + (*val - '0');
val++;
}
*output = number;
return true;
}