-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.h
More file actions
52 lines (43 loc) · 1.23 KB
/
response.h
File metadata and controls
52 lines (43 loc) · 1.23 KB
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
#pragma once
#include <string>
#include <string_view>
#include <unordered_map>
struct Response {
int status_code = 200;
std::string_view status_text = "OK";
std::unordered_map<std::string, std::string> headers;
std::string body;
std::string serialize() {
if (!headers.contains("Content-Length"))
headers["Content-Length"] = std::to_string(body.size());
if (!headers.contains("Connection"))
headers["Connection"] = "close";
if (!headers.contains("Content-Type"))
headers["Content-Type"] = "text/plain";
std::string out;
out.reserve(128 + body.size());
out += "HTTP/1.1 ";
out += std::to_string(status_code);
out += " ";
out += status_text;
out += "\r\n";
for (auto const &[k, v] : headers) {
out += k + ": " + v + "\r\n";
}
out += "\r\n";
out += body;
return out;
}
};
inline Response make_text_response(int code, std::string reason,
std::string body) {
Response res;
res.status_code = code;
res.status_text = reason;
res.body = std::move(body);
res.headers["Content-Type"] = "text/plain";
return res;
}
inline Response bad_request() {
return make_text_response(400, "Bad Request", "400 Bad Request\n");
}