-
Notifications
You must be signed in to change notification settings - Fork 28
/
main.c
95 lines (75 loc) · 1.85 KB
/
main.c
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
#include "httpd.h"
#include <sys/stat.h>
#define CHUNK_SIZE 1024 // read 1024 bytes at a time
// Public directory settings
#define PUBLIC_DIR "./public"
#define INDEX_HTML "/index.html"
#define NOT_FOUND_HTML "/404.html"
int main(int c, char **v) {
char *port = c == 1 ? "8000" : v[1];
serve_forever(port);
return 0;
}
int file_exists(const char *file_name) {
struct stat buffer;
int exists;
exists = (stat(file_name, &buffer) == 0);
return exists;
}
int read_file(const char *file_name) {
char buf[CHUNK_SIZE];
FILE *file;
size_t nread;
int err = 1;
file = fopen(file_name, "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
err = ferror(file);
fclose(file);
}
return err;
}
void route() {
ROUTE_START()
GET("/") {
char index_html[20];
sprintf(index_html, "%s%s", PUBLIC_DIR, INDEX_HTML);
HTTP_200;
if (file_exists(index_html)) {
read_file(index_html);
} else {
printf("Hello! You are using %s\n\n", request_header("User-Agent"));
}
}
GET("/test") {
HTTP_200;
printf("List of request headers:\n\n");
header_t *h = request_headers();
while (h->name) {
printf("%s: %s\n", h->name, h->value);
h++;
}
}
POST("/") {
HTTP_201;
printf("Wow, seems that you POSTed %d bytes.\n", payload_size);
printf("Fetch the data using `payload` variable.\n");
if (payload_size > 0)
printf("Request body: %s", payload);
}
GET(uri) {
char file_name[255];
snprintf(file_name, sizeof(file_name), "%s%s", PUBLIC_DIR, uri);
if (file_exists(file_name)) {
HTTP_200;
read_file(file_name);
} else {
HTTP_404;
sprintf(file_name, "%s%s", PUBLIC_DIR, NOT_FOUND_HTML);
if (file_exists(file_name))
read_file(file_name);
}
}
ROUTE_END()
}