Web server in C
Saturday 29 April 2023
 1#include <microhttpd.h>
 2#include <time.h>
 3#include <string.h>
 4#include <stdio.h>
 5#include <err.h>
 6
 7#define PORT 8888
 8
 9double elapsed_format(clock_t start, clock_t end, char **o_unit);
10enum MHD_Result router(void *cls,
11                       struct MHD_Connection *conn,
12                       const char *url,
13                       const char *method,
14                       const char *version,
15                       const char *upload_data,
16                       size_t *upload_data_size,
17                       void **con_cls);
18
19int main() {
20  struct MHD_Daemon *daemon =
21      MHD_start_daemon(MHD_USE_EPOLL_INTERNAL_THREAD,
22                       PORT, NULL, NULL, &router, NULL, MHD_OPTION_END);
23  if (NULL == daemon) return 1;
24
25  printf("Server started at: http://localhost:%d\nPress any key to exit...\n", PORT);
26  getchar();
27
28  MHD_stop_daemon(daemon);
29  return 0;
30}
31
32enum MHD_Result router(void *cls, struct MHD_Connection *conn, const char *url,
33                       const char *method, const char *version,
34                       const char *upload_data, size_t *upload_data_size,
35                       void **con_cls) {
36  clock_t start = clock();
37
38  const char *page = "<html><body>Hello, browser!</body></html>";
39  struct MHD_Response *response = MHD_create_response_from_buffer(
40      strlen(page), (void *)page, MHD_RESPMEM_PERSISTENT);
41
42  MHD_set_response_options(response, MHD_RF_SEND_KEEP_ALIVE_HEADER);
43  enum MHD_Result ret = MHD_queue_response(conn, MHD_HTTP_OK, response);
44  MHD_destroy_response(response);
45
46  clock_t end = clock();
47  char *unit;
48  double period = elapsed_format(start, end, &unit);
49  printf("%s [%.2f%s] %s\n", method, period, unit, url);
50
51  return ret;
52}
53
54char *second_s = "s";
55char *millisecond_s = "ms";
56char *microsecond_s = "μs";
57
58double elapsed_format(clock_t start, clock_t end, char **o_unit) {
59  double s = ((double)(end - start)) / CLOCKS_PER_SEC;
60
61  if (s >= 1)
62    *o_unit = second_s;
63  else if ((s *= 1000) >= 1)
64    *o_unit = millisecond_s;
65  else {
66    s *= 1000;
67    *o_unit = microsecond_s;
68  }
69
70  return s;
71}

c

See Also