-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb-server.h
More file actions
87 lines (74 loc) · 1.96 KB
/
web-server.h
File metadata and controls
87 lines (74 loc) · 1.96 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
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
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
//#include <netinet/in.h>
//#include <netinet/tcp.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <regex>
#include <thread>
#include <vector>
#include "string-utils.h"
using namespace std;
class Request {
public:
static Request from_string(string s);
string to_string() const;
string uri;
string method;
string http_version;
map<string, string> params;
private:
Request() {}
map<string, string> headers;
};
class Response {
public:
Response(int fd);
void add_header(string name, string value);
void write_status(int code = 200, string description = "OK");
void enable_multipart();
void write_content(string mime_type, const char *bytes, size_t byte_count);
void end();
bool is_closed();
int bytes_pending() {
int value = 0;
ioctl(fd, SIOCOUTQ, &value);
return value;
}
bool close_requested = false;
private:
bool status_written = false;
bool end_written = false;
int results_sent = 0;
const string multipart_boundary = "\r\n--boundarydonotcross\r\n";
const string multipart_final_boundary = "\r\n--boundarydonotcross--\r\n";
bool multipart = false;
map<string, string> headers;
void write_headers();
void write(string s);
void write(const char *bytes, size_t byte_count);
const int fd;
};
typedef std::function<void(const Request &, Response &)> Handler;
class WebServer {
public:
int max_connection_count = 30;
void add_handler(string method, string uri, Handler handler);
void run(int port);
private:
map<string, Handler> handler_map;
Handler default_handler = [](const Request &request, Response &response) {
response.write_status(404, "Not found");
string message = "Not found";
response.write_content("text/plain", message.c_str(), message.size());
};
};