http_server_test.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * sample http server
  3. * more detail see examples/httpd
  4. *
  5. */
  6. #include "HttpServer.h"
  7. #include "hssl.h"
  8. /*
  9. * #define TEST_HTTPS 1
  10. *
  11. * @build ./configure --with-openssl && make clean && make
  12. *
  13. * @server bin/http_server_test
  14. *
  15. * @client curl -v http://127.0.0.1:8080/ping
  16. * curl -v https://127.0.0.1:8443/ping --insecure
  17. * bin/curl -v http://127.0.0.1:8080/ping
  18. * bin/curl -v https://127.0.0.1:8443/ping
  19. *
  20. */
  21. #define TEST_HTTPS 0
  22. int main() {
  23. HV_MEMCHECK;
  24. HttpService router;
  25. router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
  26. return resp->String("pong");
  27. });
  28. router.GET("/data", [](HttpRequest* req, HttpResponse* resp) {
  29. static char data[] = "0123456789";
  30. return resp->Data(data, 10);
  31. });
  32. router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) {
  33. return resp->Json(router.Paths());
  34. });
  35. router.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
  36. resp->content_type = req->content_type;
  37. resp->body = req->body;
  38. return 200;
  39. });
  40. http_server_t server;
  41. server.service = &router;
  42. server.port = 8080;
  43. #if TEST_HTTPS
  44. server.https_port = 8443;
  45. hssl_ctx_init_param_t param;
  46. memset(&param, 0, sizeof(param));
  47. param.crt_file = "cert/server.crt";
  48. param.key_file = "cert/server.key";
  49. if (hssl_ctx_init(&param) == NULL) {
  50. fprintf(stderr, "SSL certificate verify failed!\n");
  51. return -20;
  52. }
  53. #endif
  54. // uncomment to test multi-processes
  55. // server.worker_processes = 4;
  56. // uncomment to test multi-threads
  57. // server.worker_threads = 4;
  58. #if 1
  59. http_server_run(&server);
  60. #else
  61. // test http_server_stop
  62. http_server_run(&server, 0);
  63. hv_sleep(10);
  64. http_server_stop(&server);
  65. #endif
  66. return 0;
  67. }