embedded_c.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c) 2013 No Face Press, LLC
  3. * License http://opensource.org/licenses/mit-license.php MIT License
  4. */
  5. // Simple example program on how to use Embedded C interface.
  6. #ifdef _WIN32
  7. #include <Windows.h>
  8. #else
  9. #include <unistd.h>
  10. #endif
  11. #include <string.h>
  12. #include "civetweb.h"
  13. #define DOCUMENT_ROOT "."
  14. #define PORT "8888"
  15. #define EXAMPLE_URI "/example"
  16. #define EXIT_URI "/exit"
  17. int exitNow = 0;
  18. int ExampleHandler(struct mg_connection *conn, void *cbdata)
  19. {
  20. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  21. mg_printf(conn, "<html><body>");
  22. mg_printf(conn, "<h2>This is example text!!!</h2>");
  23. mg_printf(conn, "<p>To exit <a href=\"%s\">click here</a></p>",
  24. EXIT_URI);
  25. mg_printf(conn, "</body></html>\n");
  26. return 1;
  27. }
  28. int ExitHandler(struct mg_connection *conn, void *cbdata)
  29. {
  30. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  31. mg_printf(conn, "Bye!\n");
  32. exitNow = 1;
  33. return 1;
  34. }
  35. int AHandler(struct mg_connection *conn, void *cbdata)
  36. {
  37. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  38. mg_printf(conn, "<html><body>");
  39. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  40. mg_printf(conn, "</body></html>\n");
  41. return 1;
  42. }
  43. int ABHandler(struct mg_connection *conn, void *cbdata)
  44. {
  45. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  46. mg_printf(conn, "<html><body>");
  47. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  48. mg_printf(conn, "</body></html>\n");
  49. return 1;
  50. }
  51. int main(int argc, char *argv[])
  52. {
  53. const char * options[] = { "document_root", DOCUMENT_ROOT,
  54. "listening_ports", PORT, 0
  55. };
  56. struct mg_callbacks callbacks;
  57. struct mg_context *ctx;
  58. memset(&callbacks, 0, sizeof(callbacks));
  59. ctx = mg_start(&callbacks, 0, options);
  60. mg_set_request_handler(ctx,EXAMPLE_URI, ExampleHandler,0);
  61. mg_set_request_handler(ctx,EXIT_URI, ExitHandler,0);
  62. mg_set_request_handler(ctx,"/a", AHandler,0);
  63. mg_set_request_handler(ctx,"/a/b", ABHandler,0);
  64. printf("Browse files at http://localhost:%s/\n", PORT);
  65. printf("Run example at http://localhost:%s%s\n", PORT, EXAMPLE_URI);
  66. printf("Exit at http://localhost:%s%s\n", PORT, EXIT_URI);
  67. while (!exitNow) {
  68. #ifdef _WIN32
  69. Sleep(1000);
  70. #else
  71. sleep(1);
  72. #endif
  73. }
  74. printf("Bye!\n");
  75. return 0;
  76. }