Skip to content

Commit 1f70d4d

Browse files
jojjuJohan Ljunggren
authored andcommitted
web-server: Send file using library function
Co-authored-by: Johan Ljunggren <[email protected]>
1 parent e69d868 commit 1f70d4d

File tree

1 file changed

+22
-24
lines changed

1 file changed

+22
-24
lines changed

web-server/app/web_server_rev_proxy.c

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -26,52 +26,50 @@
2626
#define PORT "2001"
2727
volatile sig_atomic_t application_running = 1;
2828

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+
2938
static void stop_application(int status) {
3039
(void)status;
3140
application_running = 0;
3241
}
3342

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");
4545
return 1;
4646
}
4747

4848
int main(void) {
4949
signal(SIGTERM, stop_application);
5050
signal(SIGINT, stop_application);
5151

52+
mg_init_library(0);
53+
54+
struct mg_callbacks callbacks = {0};
5255
const char* options[] =
5356
{"listening_ports", PORT, "request_timeout_ms", "10000", "error_log_file", "error.log", 0};
5457

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+
}
6162

62-
context = mg_start(&callbacks, 0, options);
6363
syslog(LOG_INFO, "Server has started");
6464

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);
7166

7267
while (application_running) {
7368
sleep(1);
7469
}
7570

71+
mg_stop(context);
72+
mg_exit_library();
73+
7674
return EXIT_SUCCESS;
7775
}

0 commit comments

Comments
 (0)