1
0

http_server_test.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.Static("/", "./html");
  31. router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
  32. return resp->String("pong");
  33. });
  34. router.GET("/data", [](HttpRequest* req, HttpResponse* resp) {
  35. static char data[] = "0123456789";
  36. return resp->Data(data, 10 /*, false */);
  37. });
  38. router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) {
  39. return resp->Json(router.Paths());
  40. });
  41. router.GET("/get", [](HttpRequest* req, HttpResponse* resp) {
  42. resp->json["origin"] = req->client_addr.ip;
  43. resp->json["url"] = req->url;
  44. resp->json["args"] = req->query_params;
  45. resp->json["headers"] = req->headers;
  46. return 200;
  47. });
  48. router.POST("/echo", [](const HttpContextPtr& ctx) {
  49. return ctx->send(ctx->body(), ctx->type());
  50. });
  51. http_server_t server;
  52. server.service = &router;
  53. server.port = port;
  54. #if TEST_HTTPS
  55. server.https_port = 8443;
  56. hssl_ctx_init_param_t param;
  57. memset(&param, 0, sizeof(param));
  58. param.crt_file = "cert/server.crt";
  59. param.key_file = "cert/server.key";
  60. param.endpoint = HSSL_SERVER;
  61. if (hssl_ctx_init(&param) == NULL) {
  62. fprintf(stderr, "hssl_ctx_init 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. http_server_run(&server, 0);
  71. // press Enter to stop
  72. while (getchar() != '\n');
  73. http_server_stop(&server);
  74. return 0;
  75. }