example.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. int main(int argc, char *argv[]) {
  37. const char * options[] = { "document_root", DOCUMENT_ROOT,
  38. "listening_ports", PORT, 0 };
  39. CivetServer server(options);
  40. server.addHandler(EXAMPLE_URI, new ExampleHandler());
  41. server.addHandler(EXIT_URI, new ExitHandler());
  42. printf("Browse files at http://localhost:%s/\n", PORT);
  43. printf("Run example at http://localhost:%s%s\n", PORT, EXIT_URI);
  44. printf("Exit at http://localhost:%s%s\n", PORT, EXIT_URI);
  45. while (!exitNow) {
  46. #ifdef _WIN32
  47. Sleep(1000);
  48. #else
  49. sleep(1);
  50. #endif
  51. }
  52. printf("Bye!\n");
  53. return 0;
  54. }