1
0

http_server_test.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 8080
  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(int argc, char** argv) {
  23. HV_MEMCHECK;
  24. int port = 0;
  25. if (argc > 1) {
  26. port = atoi(argv[1]);
  27. }
  28. if (port == 0) port = 8080;
  29. HttpService router;
  30. router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
  31. return resp->String("pong");
  32. });
  33. router.GET("/data", [](HttpRequest* req, HttpResponse* resp) {
  34. static char data[] = "0123456789";
  35. return resp->Data(data, 10);
  36. });
  37. router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) {
  38. return resp->Json(router.Paths());
  39. });
  40. router.GET("/get", [](HttpRequest* req, HttpResponse* resp) {
  41. resp->json["origin"] = req->client_addr.ip;
  42. resp->json["url"] = req->url;
  43. resp->json["args"] = req->query_params;
  44. resp->json["headers"] = req->headers;
  45. return 200;
  46. });
  47. router.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
  48. resp->content_type = req->content_type;
  49. resp->body = req->body;
  50. return 200;
  51. });
  52. http_server_t server;
  53. server.service = &router;
  54. server.port = port;
  55. #if TEST_HTTPS
  56. server.https_port = 8443;
  57. hssl_ctx_init_param_t param;
  58. memset(&param, 0, sizeof(param));
  59. param.crt_file = "cert/server.crt";
  60. param.key_file = "cert/server.key";
  61. if (hssl_ctx_init(&param) == NULL) {
  62. fprintf(stderr, "SSL certificate verify failed!\n");
  63. return -20;
  64. }
  65. #endif
  66. // uncomment to test multi-processes
  67. // server.worker_processes = 4;
  68. // uncomment to test multi-threads
  69. // server.worker_threads = 4;
  70. #if 1
  71. http_server_run(&server);
  72. #else
  73. // test http_server_stop
  74. http_server_run(&server, 0);
  75. hv_sleep(10);
  76. http_server_stop(&server);
  77. #endif
  78. return 0;
  79. }