test_package.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. 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. int err = 0;
  48. mg_init_library(0);
  49. /* Callback will print error messages to console */
  50. memset(&callbacks, 0, sizeof(callbacks));
  51. callbacks.log_message = log_message;
  52. /* Start CivetWeb web server */
  53. ctx = mg_start(&callbacks, 0, NULL);
  54. /* Check return value: */
  55. if (ctx == NULL) {
  56. fprintf(stderr, "Cannot start CivetWeb - mg_start failed.\n");
  57. return EXIT_FAILURE;
  58. }
  59. /* Add handler EXAMPLE_URI, to explain the example */
  60. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  61. /* Show sone info */
  62. printf("Start example: %s%s\n", HOST_INFO, EXAMPLE_URI);
  63. /* Wait until the server should be closed */
  64. while (!exitNow) {
  65. #ifdef _WIN32
  66. Sleep(1000);
  67. #else
  68. sleep(1);
  69. #endif
  70. }
  71. /* Stop the server */
  72. mg_stop(ctx);
  73. return EXIT_SUCCESS;
  74. }