embedded_cpp.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #include "CivetServer.h"
  7. #ifdef _WIN32
  8. #include <Windows.h>
  9. #endif
  10. #define DOCUMENT_ROOT "."
  11. #define PORT "8888"
  12. #define EXAMPLE_URI "/example"
  13. #define EXIT_URI "/exit"
  14. bool exitNow = false;
  15. class ExampleHandler: public CivetHandler
  16. {
  17. public:
  18. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  19. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  20. mg_printf(conn, "<html><body>");
  21. mg_printf(conn, "<h2>This is example text!!!</h2>");
  22. mg_printf(conn, "<p>To exit <a href=\"%s\">click here</a></p>",
  23. EXIT_URI);
  24. mg_printf(conn, "</body></html>\n");
  25. return true;
  26. }
  27. };
  28. class ExitHandler: public CivetHandler
  29. {
  30. public:
  31. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  32. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  33. mg_printf(conn, "Bye!\n");
  34. exitNow = true;
  35. return true;
  36. }
  37. };
  38. class AHandler: public CivetHandler
  39. {
  40. public:
  41. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  42. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  43. mg_printf(conn, "<html><body>");
  44. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  45. mg_printf(conn, "</body></html>\n");
  46. return true;
  47. }
  48. };
  49. class ABHandler: public CivetHandler
  50. {
  51. public:
  52. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  53. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  54. mg_printf(conn, "<html><body>");
  55. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  56. mg_printf(conn, "</body></html>\n");
  57. return true;
  58. }
  59. };
  60. int main(int argc, char *argv[])
  61. {
  62. const char * options[] = { "document_root", DOCUMENT_ROOT,
  63. "listening_ports", PORT, 0
  64. };
  65. CivetServer server(options);
  66. server.addHandler(EXAMPLE_URI, new ExampleHandler());
  67. server.addHandler(EXIT_URI, new ExitHandler());
  68. server.addHandler("/a", new AHandler());
  69. server.addHandler("/a/b", new ABHandler());
  70. printf("Browse files at http://localhost:%s/\n", PORT);
  71. printf("Run example at http://localhost:%s%s\n", PORT, EXAMPLE_URI);
  72. printf("Exit at http://localhost:%s%s\n", PORT, EXIT_URI);
  73. while (!exitNow) {
  74. #ifdef _WIN32
  75. Sleep(1000);
  76. #else
  77. sleep(1);
  78. #endif
  79. }
  80. printf("Bye!\n");
  81. return 0;
  82. }