|
26 | 26 | #define PORT "2001" |
27 | 27 | volatile sig_atomic_t application_running = 1; |
28 | 28 |
|
| 29 | +__attribute__((noreturn)) __attribute__((format(printf, 1, 2))) static void |
| 30 | +panic(const char* format, ...) { |
| 31 | + va_list arg; |
| 32 | + va_start(arg, format); |
| 33 | + vsyslog(LOG_ERR, format, arg); |
| 34 | + va_end(arg); |
| 35 | + exit(1); |
| 36 | +} |
| 37 | + |
29 | 38 | static void stop_application(int status) { |
30 | 39 | (void)status; |
31 | 40 | application_running = 0; |
32 | 41 | } |
33 | 42 |
|
34 | | -static int RootHandler(struct mg_connection* conn, void* cb_data __attribute__((unused))) { |
35 | | - mg_printf(conn, |
36 | | - "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " |
37 | | - "close\r\n\r\n"); |
38 | | - FILE* html_file = fopen("html/index.html", "r"); |
39 | | - int FILE_STR_SIZE = 128; |
40 | | - char file_str[FILE_STR_SIZE]; |
41 | | - while (fgets(file_str, FILE_STR_SIZE, html_file)) { |
42 | | - mg_printf(conn, "%s", file_str); |
43 | | - } |
44 | | - fclose(html_file); |
| 43 | +static int root_handler(struct mg_connection* conn, void* cb_data __attribute__((unused))) { |
| 44 | + mg_send_file(conn, "html/index.html"); |
45 | 45 | return 1; |
46 | 46 | } |
47 | 47 |
|
48 | 48 | int main(void) { |
49 | 49 | signal(SIGTERM, stop_application); |
50 | 50 | signal(SIGINT, stop_application); |
51 | 51 |
|
| 52 | + mg_init_library(0); |
| 53 | + |
| 54 | + struct mg_callbacks callbacks = {0}; |
52 | 55 | const char* options[] = |
53 | 56 | {"listening_ports", PORT, "request_timeout_ms", "10000", "error_log_file", "error.log", 0}; |
54 | 57 |
|
55 | | - struct mg_callbacks callbacks; |
56 | | - struct mg_context* context; |
57 | | - |
58 | | - mg_init_library(0); |
59 | | - |
60 | | - memset(&callbacks, 0, sizeof(callbacks)); |
| 58 | + struct mg_context* context = mg_start(&callbacks, 0, options); |
| 59 | + if (!context) { |
| 60 | + panic("Something went wrong when starting the web server"); |
| 61 | + } |
61 | 62 |
|
62 | | - context = mg_start(&callbacks, 0, options); |
63 | 63 | syslog(LOG_INFO, "Server has started"); |
64 | 64 |
|
65 | | - mg_set_request_handler(context, "/", RootHandler, 0); |
66 | | - |
67 | | - if (context == NULL) { |
68 | | - syslog(LOG_INFO, "Something went wrong when starting the web server.\n"); |
69 | | - return EXIT_FAILURE; |
70 | | - } |
| 65 | + mg_set_request_handler(context, "/", root_handler, 0); |
71 | 66 |
|
72 | 67 | while (application_running) { |
73 | 68 | sleep(1); |
74 | 69 | } |
75 | 70 |
|
| 71 | + mg_stop(context); |
| 72 | + mg_exit_library(); |
| 73 | + |
76 | 74 | return EXIT_SUCCESS; |
77 | 75 | } |
0 commit comments