hello.c 1.6 KB

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