1 | #include "util/mongoose.h" |
2 | |
3 | static const char* s_listen_on = "ws://localhost:8181" ; |
4 | static const char* s_web_root = "." ; |
5 | |
6 | // This RESTful server implements the following endpoints: |
7 | // /websocket - upgrade to Websocket, and implement websocket echo server |
8 | // /rest - respond with JSON string {"result": 123} |
9 | // any other URI serves static files from s_web_root |
10 | static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) |
11 | { |
12 | if (ev == MG_EV_OPEN) |
13 | { |
14 | c->is_hexdumping = 1; |
15 | } |
16 | |
17 | if (ev == MG_EV_ACCEPT) |
18 | { |
19 | // If url is wss://, use TLS |
20 | if (mg_url_is_ssl(s_listen_on)) |
21 | { |
22 | struct mg_tls_opts opts = |
23 | { |
24 | .cert = "files/cert.pem" , // Certificate file |
25 | .certkey = "files/key.pem" , // Private key file |
26 | }; |
27 | |
28 | mg_tls_init(c, &opts); |
29 | } |
30 | } |
31 | else if (ev == MG_EV_HTTP_MSG) |
32 | { |
33 | struct mg_http_message* hm = (struct mg_http_message*) ev_data; |
34 | |
35 | if (mg_http_match_uri(hm, "/websocket" )) |
36 | { |
37 | // Upgrade to websocket. From now on, a connection is a full-duplex |
38 | // Websocket connection, which will receive MG_EV_WS_MSG events. |
39 | mg_ws_upgrade(c, hm, NULL); |
40 | } |
41 | else if (mg_http_match_uri(hm, "/rest" )) |
42 | { |
43 | // Serve REST response |
44 | mg_http_reply(c, 200, "" , "{\"result\": %d}\n" , 123); |
45 | } |
46 | else |
47 | { |
48 | // Serve static files |
49 | struct mg_http_serve_opts opts = {.root_dir = s_web_root}; |
50 | mg_http_serve_dir(c, ev_data, &opts); |
51 | } |
52 | } |
53 | else if (ev == MG_EV_WS_MSG) |
54 | { |
55 | // Got websocket frame. Received data is wm->data. Echo it back! |
56 | struct mg_ws_message* wm = (struct mg_ws_message*) ev_data; |
57 | mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT); |
58 | } |
59 | |
60 | (void)fn_data; |
61 | } |
62 | |
63 | int main(void) |
64 | { |
65 | struct mg_mgr mgr; // Event manager |
66 | mg_mgr_init(&mgr); // Initialise event manager |
67 | printf("Starting WS listener on %s/websocket\n" , s_listen_on); |
68 | mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener |
69 | |
70 | // Infinite event loop |
71 | for (;;) |
72 | { |
73 | mg_mgr_poll(&mgr, 1000); |
74 | } |
75 | |
76 | mg_mgr_free(&mgr); |
77 | |
78 | return 0; |
79 | } |
80 | |