embedded_cpp.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. public:
  17. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  18. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  19. mg_printf(conn, "<html><body>");
  20. mg_printf(conn, "<h2>This is example text!!!</h2>");
  21. mg_printf(conn, "<p>To exit <a href=\"%s\">click here</a></p>",
  22. EXIT_URI);
  23. mg_printf(conn, "</body></html>\n");
  24. return true;
  25. }
  26. };
  27. class ExitHandler: public CivetHandler {
  28. public:
  29. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  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 = true;
  33. return true;
  34. }
  35. };
  36. class AHandler: public CivetHandler {
  37. public:
  38. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  39. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  40. mg_printf(conn, "<html><body>");
  41. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  42. mg_printf(conn, "</body></html>\n");
  43. return true;
  44. }
  45. };
  46. class ABHandler: public CivetHandler {
  47. public:
  48. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  49. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  50. mg_printf(conn, "<html><body>");
  51. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  52. mg_printf(conn, "</body></html>\n");
  53. return true;
  54. }
  55. };
  56. int main(int argc, char *argv[]) {
  57. const char * options[] = { "document_root", DOCUMENT_ROOT,
  58. "listening_ports", PORT, 0 };
  59. CivetServer server(options);
  60. server.addHandler(EXAMPLE_URI, new ExampleHandler());
  61. server.addHandler(EXIT_URI, new ExitHandler());
  62. server.addHandler("/a", new AHandler());
  63. server.addHandler("/a/b", new ABHandler());
  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. }