hello.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "civetweb.h"
  4. // This function will be called by civetweb on every new request.
  5. static int begin_request_handler(struct mg_connection *conn) {
  6. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7. char content[100];
  8. // Prepare the message we're going to send
  9. int content_length = snprintf(content, sizeof(content),
  10. "Hello from civetweb! Remote port: %d",
  11. request_info->remote_port);
  12. // Send HTTP reply to the client
  13. mg_printf(conn,
  14. "HTTP/1.1 200 OK\r\n"
  15. "Content-Type: text/plain\r\n"
  16. "Content-Length: %d\r\n" // Always set Content-Length
  17. "\r\n"
  18. "%s",
  19. content_length, content);
  20. // Returning non-zero tells civetweb that our function has replied to
  21. // the client, and civetweb should not send client any more data.
  22. return 1;
  23. }
  24. int main(void) {
  25. struct mg_context *ctx;
  26. struct mg_callbacks callbacks;
  27. // List of options. Last element must be NULL.
  28. const char *options[] = {"listening_ports", "8080", NULL};
  29. // Prepare callbacks structure. We have only one callback, the rest are NULL.
  30. memset(&callbacks, 0, sizeof(callbacks));
  31. callbacks.begin_request = begin_request_handler;
  32. // Start the web server.
  33. ctx = mg_start(&callbacks, NULL, options);
  34. // Wait until user hits "enter". Server is running in separate thread.
  35. // Navigating to http://localhost:8080 will invoke begin_request_handler().
  36. getchar();
  37. // Stop the server.
  38. mg_stop(ctx);
  39. return 0;
  40. }