1
0

HttpServer.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #ifndef HV_HTTP_SERVER_H_
  2. #define HV_HTTP_SERVER_H_
  3. #include "hexport.h"
  4. #include "HttpService.h"
  5. // #include "WebSocketServer.h"
  6. namespace hv {
  7. struct WebSocketService;
  8. }
  9. using hv::HttpService;
  10. using hv::WebSocketService;
  11. typedef struct http_server_s {
  12. char host[64];
  13. int port; // http_port
  14. int https_port;
  15. int http_version;
  16. int worker_processes;
  17. int worker_threads;
  18. HttpService* service; // http service
  19. WebSocketService* ws; // websocket service
  20. void* userdata;
  21. //private:
  22. int listenfd[2]; // 0: http, 1: https
  23. void* privdata;
  24. #ifdef __cplusplus
  25. http_server_s() {
  26. strcpy(host, "0.0.0.0");
  27. // port = DEFAULT_HTTP_PORT;
  28. // https_port = DEFAULT_HTTPS_PORT;
  29. // port = 8080;
  30. // https_port = 8443;
  31. port = https_port = 0;
  32. http_version = 1;
  33. worker_processes = 0;
  34. worker_threads = 0;
  35. service = NULL;
  36. ws = NULL;
  37. listenfd[0] = listenfd[1] = -1;
  38. userdata = NULL;
  39. privdata = NULL;
  40. }
  41. #endif
  42. } http_server_t;
  43. // @param wait: Whether to occupy current thread
  44. HV_EXPORT int http_server_run(http_server_t* server, int wait = 1);
  45. // NOTE: stop all loops and join all threads
  46. HV_EXPORT int http_server_stop(http_server_t* server);
  47. /*
  48. #include "HttpServer.h"
  49. using namespace hv;
  50. int main() {
  51. HttpService service;
  52. service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
  53. resp->body = "pong";
  54. return 200;
  55. });
  56. HttpServer server;
  57. server.registerHttpService(&service);
  58. server.setPort(8080);
  59. server.setThreadNum(4);
  60. server.run();
  61. return 0;
  62. }
  63. */
  64. namespace hv {
  65. class HttpServer : public http_server_t {
  66. public:
  67. HttpServer() : http_server_t() {}
  68. ~HttpServer() { stop(); }
  69. void registerHttpService(HttpService* service) {
  70. this->service = service;
  71. }
  72. void setHost(const char* host = "0.0.0.0") {
  73. if (host) strcpy(this->host, host);
  74. }
  75. void setPort(int port = 0, int ssl_port = 0) {
  76. if (port != 0) this->port = port;
  77. if (ssl_port != 0) this->https_port = ssl_port;
  78. }
  79. void setProcessNum(int num) {
  80. this->worker_processes = num;
  81. }
  82. void setThreadNum(int num) {
  83. this->worker_threads = num;
  84. }
  85. int run(bool wait = true) {
  86. return http_server_run(this, wait);
  87. }
  88. int start() {
  89. return run(false);
  90. }
  91. int stop() {
  92. return http_server_stop(this);
  93. }
  94. };
  95. }
  96. #endif // HV_HTTP_SERVER_H_