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
|
#include "mongoose.h"
// HTML
char *
html_user_post(struct mg_str user) {
static char html[1024];
snprintf(html, 1024,
"<!DOCTYPE html>"
"<html>"
"<body>"
"<form action=\"/user/%.*s/post\" method=\"post\">"
" <input type=\"text\" id=\"content\" name=\"content\"><br>"
" <input type=\"submit\" value=\"Chirp!\">"
"</form>"
"</body>"
"</html>",
user.len, user.ptr);
return html;
}
// Post
// User
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_strcmp(hm->method, mg_str("post"))) {
printf("POST: %.*s\n", hm->body.len, hm->body.ptr);
}
if (mg_http_match_uri(hm, "/user/*/post")) {
struct mg_str caps[2];
printf("uri: %.*s\n", hm->uri.len, hm->uri.ptr);
mg_match(hm->uri, mg_str("/user/*/post"), caps);
mg_http_reply(c, 200, "", html_user_post(caps[0]));
}
else {
mg_http_reply(c, 404, "", "Not found :/");
}
}
}
int main(int argc, char *argv[]) {
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Init manager
mg_http_listen(&mgr, "http://0.0.0.0:8000", fn, &mgr); // Setup listener
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
mg_mgr_free(&mgr); // Cleanup
return 0;
}
|