example.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2013 Thomas Davis
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE
  20. // Simple example program on how to use Embedded C++ interface.
  21. #include "CivetServer.h"
  22. #define DOCUMENT_ROOT "."
  23. #define PORT "8888"
  24. #define EXAMPLE_URI "/example"
  25. #define EXIT_URI "/exit"
  26. bool exitNow = false;
  27. class ExampleHandler: 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/html\r\n\r\n");
  31. mg_printf(conn, "<html><body>");
  32. mg_printf(conn, "<h2>This is example text!!!</h2>");
  33. mg_printf(conn, "<p>To exit <a href=\"%s\">click here</a></p>",
  34. EXIT_URI);
  35. mg_printf(conn, "</body></html>\n");
  36. return true;
  37. }
  38. };
  39. class ExitHandler: public CivetHandler {
  40. public:
  41. bool handleGet(CivetServer *server, struct mg_connection *conn) {
  42. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  43. mg_printf(conn, "Bye!\n");
  44. exitNow = true;
  45. return true;
  46. }
  47. };
  48. int main(int argc, char *argv[]) {
  49. const char * options[] = { "document_root", DOCUMENT_ROOT,
  50. "listening_ports", PORT, 0 };
  51. CivetServer server(options);
  52. server.addHandler(EXAMPLE_URI, new ExampleHandler());
  53. server.addHandler(EXIT_URI, new ExitHandler());
  54. printf("Browse files at http://localhost:%s/\n", PORT);
  55. printf("Run example at http://localhost:%s%s\n", PORT, EXIT_URI);
  56. printf("Exit at http://localhost:%s%s\n", PORT, EXIT_URI);
  57. while (!exitNow) {
  58. sleep(1);
  59. }
  60. printf("Bye!\n");
  61. return 0;
  62. }