1
0

http_server_test.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 /*, false */);
  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", [](const HttpContextPtr& ctx) {
  48. return ctx->send(ctx->body(), ctx->type());
  49. });
  50. http_server_t server;
  51. server.service = &router;
  52. server.port = port;
  53. #if TEST_HTTPS
  54. server.https_port = 8443;
  55. hssl_ctx_init_param_t param;
  56. memset(&param, 0, sizeof(param));
  57. param.crt_file = "cert/server.crt";
  58. param.key_file = "cert/server.key";
  59. if (hssl_ctx_init(&param) == NULL) {
  60. fprintf(stderr, "SSL certificate verify failed!\n");
  61. return -20;
  62. }
  63. #endif
  64. // uncomment to test multi-processes
  65. // server.worker_processes = 4;
  66. // uncomment to test multi-threads
  67. // server.worker_threads = 4;
  68. #if 1
  69. http_server_run(&server);
  70. #else
  71. // test http_server_stop
  72. http_server_run(&server, 0);
  73. hv_sleep(10);
  74. http_server_stop(&server);
  75. #endif
  76. return 0;
  77. }