-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestful_api.c
executable file
·77 lines (62 loc) · 1.94 KB
/
restful_api.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mongoose.h"
static const char *s_no_cache_header =
"Cache-Control: max-age=0, post-check=0, "
"pre-check=0, no-store, no-cache, must-revalidate\r\n";
static void handle_restful_call(struct mg_connection *conn) {
char n1[100], n2[100];
// Get form variables
mg_get_var(conn, "n1", n1, sizeof(n1));
mg_get_var(conn, "n2", n2, sizeof(n2));
mg_printf_data(conn, "{ \"result\": %lf }", strtod(n1, NULL) + strtod(n2, NULL));
}
static void handle_restful_multi(struct mg_connection *conn) {
char n1[100], n2[100];
// Get form variables
mg_get_var(conn, "n1", n1, sizeof(n1));
mg_get_var(conn, "n2", n2, sizeof(n2));
mg_printf_data(conn, "{ \"result\": %lf }", strtod(n1, NULL) * strtod(n2, NULL));
}
int status_msg = 1;
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
switch (ev) {
case MG_AUTH: return MG_TRUE;
case MG_REQUEST:
if (!strcmp(conn->uri, "/api/sum")) {
handle_restful_call(conn);
return MG_TRUE;
}
else if (!strcmp(conn->uri, "/api/multiply")) {
status_msg = 1;
handle_restful_multi(conn);
return MG_TRUE;
}
else {
status_msg = 0;
}
if (status_msg == 1 || !strcmp(conn->uri, "/")) {
mg_send_file(conn, "index.html", s_no_cache_header);
}
else {
mg_send_file(conn, "404.html", s_no_cache_header);
}
return MG_MORE;
default: return MG_FALSE;
}
}
int main(void) {
struct mg_server *server;
// Create and configure the server
server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8000");
// Serve request. Hit Ctrl-C to terminate the program
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
// Cleanup, and free server instance
mg_destroy_server(&server);
return 0;
}