1
0

http_server_test.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.GET("/get", [](HttpRequest* req, HttpResponse* resp) {
  36. resp->json["origin"] = req->client_addr.ip;
  37. resp->json["url"] = req->url;
  38. resp->json["args"] = req->query_params;
  39. resp->json["headers"] = req->headers;
  40. return 200;
  41. });
  42. router.POST("/echo", [](HttpRequest* req, HttpResponse* resp) {
  43. resp->content_type = req->content_type;
  44. resp->body = req->body;
  45. return 200;
  46. });
  47. http_server_t server;
  48. server.service = &router;
  49. server.port = 8080;
  50. #if TEST_HTTPS
  51. server.https_port = 8443;
  52. hssl_ctx_init_param_t param;
  53. memset(&param, 0, sizeof(param));
  54. param.crt_file = "cert/server.crt";
  55. param.key_file = "cert/server.key";
  56. if (hssl_ctx_init(&param) == NULL) {
  57. fprintf(stderr, "SSL certificate verify failed!\n");
  58. return -20;
  59. }
  60. #endif
  61. // uncomment to test multi-processes
  62. // server.worker_processes = 4;
  63. // uncomment to test multi-threads
  64. // server.worker_threads = 4;
  65. #if 1
  66. http_server_run(&server);
  67. #else
  68. // test http_server_stop
  69. http_server_run(&server, 0);
  70. hv_sleep(10);
  71. http_server_stop(&server);
  72. #endif
  73. return 0;
  74. }