test_package.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (c) 2018 the CivetWeb developers
  3. * MIT License
  4. */
  5. /* Simple demo of a REST callback. */
  6. #ifdef _WIN32
  7. #include <windows.h>
  8. #else
  9. #include <unistd.h>
  10. #endif
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <time.h>
  14. #include "civetweb.h"
  15. #define PORT "8080"
  16. #define HOST_INFO "http://localhost:8080"
  17. #define EXAMPLE_URI "/example"
  18. static int exitNow = 0;
  19. static int
  20. ExampleGET(struct mg_connection* conn)
  21. {
  22. mg_send_http_ok(conn, "text/plain", 10);
  23. exitNow = 1;
  24. return 200;
  25. }
  26. static int
  27. ExampleHandler(struct mg_connection *conn, void *cbdata)
  28. {
  29. const struct mg_request_info *ri = mg_get_request_info(conn);
  30. (void)cbdata; /* currently unused */
  31. if (0 == strcmp(ri->request_method, "GET")) {
  32. return ExampleGET(conn);
  33. }
  34. return 405;
  35. }
  36. int
  37. log_message(const struct mg_connection *conn, const char *message)
  38. {
  39. puts(message);
  40. return 1;
  41. }
  42. int
  43. main(int argc, char *argv[])
  44. {
  45. struct mg_callbacks callbacks;
  46. struct mg_context *ctx;
  47. time_t start_t;
  48. time_t end_t;
  49. double diff_t;
  50. int err = 0;
  51. mg_init_library(0);
  52. /* Callback will print error messages to console */
  53. memset(&callbacks, 0, sizeof(callbacks));
  54. callbacks.log_message = log_message;
  55. /* Start CivetWeb web server */
  56. ctx = mg_start(&callbacks, 0, NULL);
  57. /* Check return value: */
  58. if (ctx == NULL) {
  59. fprintf(stderr, "Cannot start CivetWeb - mg_start failed.\n");
  60. return EXIT_FAILURE;
  61. }
  62. /* Add handler EXAMPLE_URI, to explain the example */
  63. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  64. /* Show sone info */
  65. printf("Start example: %s%s\n", HOST_INFO, EXAMPLE_URI);
  66. /* Wait until the server should be closed */
  67. time(&start_t);
  68. while (!exitNow) {
  69. #ifdef _WIN32
  70. Sleep(1000);
  71. #else
  72. sleep(1);
  73. #endif
  74. time(&end_t);
  75. diff_t = difftime(end_t, start_t);
  76. if (diff_t > 3.0) {
  77. break;
  78. }
  79. }
  80. /* Stop the server */
  81. mg_stop(ctx);
  82. return EXIT_SUCCESS;
  83. }