HttpService.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #ifndef HV_HTTP_SERVICE_H_
  2. #define HV_HTTP_SERVICE_H_
  3. #include <string>
  4. #include <map>
  5. #include <unordered_map>
  6. #include <list>
  7. #include <memory>
  8. #include <functional>
  9. #include "hexport.h"
  10. #include "HttpMessage.h"
  11. #include "HttpResponseWriter.h"
  12. #include "HttpContext.h"
  13. #define DEFAULT_BASE_URL "/api/v1"
  14. #define DEFAULT_DOCUMENT_ROOT "/var/www/html"
  15. #define DEFAULT_HOME_PAGE "index.html"
  16. #define DEFAULT_ERROR_PAGE "error.html"
  17. #define DEFAULT_INDEXOF_DIR "/downloads/"
  18. #define DEFAULT_KEEPALIVE_TIMEOUT 75000 // ms
  19. // for FileCache
  20. #define MAX_FILE_CACHE_SIZE (1 << 22) // 4M
  21. #define DEFAULT_FILE_CACHE_STAT_INTERVAL 10 // s
  22. #define DEFAULT_FILE_CACHE_EXPIRED_TIME 60 // s
  23. /*
  24. * @param[in] req: parsed structured http request
  25. * @param[out] resp: structured http response
  26. * @return 0: handle unfinished
  27. * http_status_code: handle done
  28. */
  29. #define HTTP_STATUS_UNFINISHED 0
  30. // NOTE: http_sync_handler run on IO thread
  31. typedef std::function<int(HttpRequest* req, HttpResponse* resp)> http_sync_handler;
  32. // NOTE: http_async_handler run on hv::async threadpool
  33. typedef std::function<void(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer)> http_async_handler;
  34. // NOTE: http_ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing.
  35. typedef std::function<int(const HttpContextPtr& ctx)> http_ctx_handler;
  36. struct http_handler {
  37. http_sync_handler sync_handler;
  38. http_async_handler async_handler;
  39. http_ctx_handler ctx_handler;
  40. http_handler() {}
  41. http_handler(http_sync_handler fn) : sync_handler(std::move(fn)) {}
  42. http_handler(http_async_handler fn) : async_handler(std::move(fn)) {}
  43. http_handler(http_ctx_handler fn) : ctx_handler(std::move(fn)) {}
  44. http_handler(const http_handler& rhs)
  45. : sync_handler(std::move(rhs.sync_handler))
  46. , async_handler(std::move(rhs.async_handler))
  47. , ctx_handler(std::move(rhs.ctx_handler))
  48. {}
  49. const http_handler& operator=(http_sync_handler fn) {
  50. sync_handler = std::move(fn);
  51. return *this;
  52. }
  53. const http_handler& operator=(http_async_handler fn) {
  54. async_handler = std::move(fn);
  55. return *this;
  56. }
  57. const http_handler& operator=(http_ctx_handler fn) {
  58. ctx_handler = std::move(fn);
  59. return *this;
  60. }
  61. bool isNull() {
  62. return sync_handler == NULL &&
  63. async_handler == NULL &&
  64. ctx_handler == NULL;
  65. }
  66. operator bool() {
  67. return !isNull();
  68. }
  69. };
  70. struct http_method_handler {
  71. http_method method;
  72. http_handler handler;
  73. http_method_handler() {}
  74. http_method_handler(http_method m, const http_handler& h) : method(m), handler(h) {}
  75. };
  76. // method => http_method_handler
  77. typedef std::list<http_method_handler> http_method_handlers;
  78. // path => http_method_handlers
  79. typedef std::unordered_map<std::string, std::shared_ptr<http_method_handlers>> http_api_handlers;
  80. namespace hv {
  81. struct HV_EXPORT HttpService {
  82. // preprocessor -> processor -> postprocessor
  83. http_handler preprocessor;
  84. // processor: api_handlers -> staticHandler -> errorHandler
  85. http_handler processor;
  86. http_handler postprocessor;
  87. // api service (that is http.APIServer)
  88. std::string base_url;
  89. http_api_handlers api_handlers;
  90. // file service (that is http.FileServer)
  91. http_handler staticHandler;
  92. http_handler largeFileHandler;
  93. std::string document_root;
  94. std::string home_page;
  95. std::string error_page;
  96. // location => root
  97. std::map<std::string, std::string, std::greater<std::string>> staticDirs;
  98. // indexof service (that is http.DirectoryServer)
  99. std::string index_of;
  100. http_handler errorHandler;
  101. // options
  102. int keepalive_timeout;
  103. int max_file_cache_size; // cache small file
  104. int file_cache_stat_interval; // stat file is modified
  105. int file_cache_expired_time; // remove expired file cache
  106. /*
  107. * @test limit_rate
  108. * @build make examples
  109. * @server bin/httpd -c etc/httpd.conf -s restart -d
  110. * @client bin/wget http://127.0.0.1:8080/downloads/test.zip
  111. */
  112. int limit_rate; // limit send rate, unit: KB/s
  113. HttpService() {
  114. // base_url = DEFAULT_BASE_URL;
  115. document_root = DEFAULT_DOCUMENT_ROOT;
  116. home_page = DEFAULT_HOME_PAGE;
  117. // error_page = DEFAULT_ERROR_PAGE;
  118. // index_of = DEFAULT_INDEXOF_DIR;
  119. keepalive_timeout = DEFAULT_KEEPALIVE_TIMEOUT;
  120. max_file_cache_size = MAX_FILE_CACHE_SIZE;
  121. file_cache_stat_interval = DEFAULT_FILE_CACHE_STAT_INTERVAL;
  122. file_cache_expired_time = DEFAULT_FILE_CACHE_EXPIRED_TIME;
  123. limit_rate = -1; // unlimited
  124. }
  125. void AddApi(const char* path, http_method method, const http_handler& handler);
  126. // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED
  127. int GetApi(const char* url, http_method method, http_handler** handler);
  128. // RESTful API /:field/ => req->query_params["field"]
  129. int GetApi(HttpRequest* req, http_handler** handler);
  130. // Static("/", "/var/www/html")
  131. void Static(const char* path, const char* dir);
  132. // @retval / => /var/www/html/index.html
  133. std::string GetStaticFilepath(const char* path);
  134. hv::StringList Paths() {
  135. hv::StringList paths;
  136. for (auto& pair : api_handlers) {
  137. paths.emplace_back(pair.first);
  138. }
  139. return paths;
  140. }
  141. // github.com/gin-gonic/gin
  142. void Handle(const char* httpMethod, const char* relativePath, http_sync_handler handlerFunc) {
  143. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  144. }
  145. void Handle(const char* httpMethod, const char* relativePath, http_async_handler handlerFunc) {
  146. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  147. }
  148. void Handle(const char* httpMethod, const char* relativePath, http_ctx_handler handlerFunc) {
  149. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  150. }
  151. // HEAD
  152. void HEAD(const char* relativePath, http_sync_handler handlerFunc) {
  153. Handle("HEAD", relativePath, handlerFunc);
  154. }
  155. void HEAD(const char* relativePath, http_async_handler handlerFunc) {
  156. Handle("HEAD", relativePath, handlerFunc);
  157. }
  158. void HEAD(const char* relativePath, http_ctx_handler handlerFunc) {
  159. Handle("HEAD", relativePath, handlerFunc);
  160. }
  161. // GET
  162. void GET(const char* relativePath, http_sync_handler handlerFunc) {
  163. Handle("GET", relativePath, handlerFunc);
  164. }
  165. void GET(const char* relativePath, http_async_handler handlerFunc) {
  166. Handle("GET", relativePath, handlerFunc);
  167. }
  168. void GET(const char* relativePath, http_ctx_handler handlerFunc) {
  169. Handle("GET", relativePath, handlerFunc);
  170. }
  171. // POST
  172. void POST(const char* relativePath, http_sync_handler handlerFunc) {
  173. Handle("POST", relativePath, handlerFunc);
  174. }
  175. void POST(const char* relativePath, http_async_handler handlerFunc) {
  176. Handle("POST", relativePath, handlerFunc);
  177. }
  178. void POST(const char* relativePath, http_ctx_handler handlerFunc) {
  179. Handle("POST", relativePath, handlerFunc);
  180. }
  181. // PUT
  182. void PUT(const char* relativePath, http_sync_handler handlerFunc) {
  183. Handle("PUT", relativePath, handlerFunc);
  184. }
  185. void PUT(const char* relativePath, http_async_handler handlerFunc) {
  186. Handle("PUT", relativePath, handlerFunc);
  187. }
  188. void PUT(const char* relativePath, http_ctx_handler handlerFunc) {
  189. Handle("PUT", relativePath, handlerFunc);
  190. }
  191. // DELETE
  192. // NOTE: Windows <winnt.h> #define DELETE as a macro, we have to replace DELETE with Delete.
  193. void Delete(const char* relativePath, http_sync_handler handlerFunc) {
  194. Handle("DELETE", relativePath, handlerFunc);
  195. }
  196. void Delete(const char* relativePath, http_async_handler handlerFunc) {
  197. Handle("DELETE", relativePath, handlerFunc);
  198. }
  199. void Delete(const char* relativePath, http_ctx_handler handlerFunc) {
  200. Handle("DELETE", relativePath, handlerFunc);
  201. }
  202. // PATCH
  203. void PATCH(const char* relativePath, http_sync_handler handlerFunc) {
  204. Handle("PATCH", relativePath, handlerFunc);
  205. }
  206. void PATCH(const char* relativePath, http_async_handler handlerFunc) {
  207. Handle("PATCH", relativePath, handlerFunc);
  208. }
  209. void PATCH(const char* relativePath, http_ctx_handler handlerFunc) {
  210. Handle("PATCH", relativePath, handlerFunc);
  211. }
  212. // Any
  213. void Any(const char* relativePath, http_sync_handler handlerFunc) {
  214. Handle("HEAD", relativePath, handlerFunc);
  215. Handle("GET", relativePath, handlerFunc);
  216. Handle("POST", relativePath, handlerFunc);
  217. Handle("PUT", relativePath, handlerFunc);
  218. Handle("DELETE", relativePath, handlerFunc);
  219. Handle("PATCH", relativePath, handlerFunc);
  220. }
  221. void Any(const char* relativePath, http_async_handler handlerFunc) {
  222. Handle("HEAD", relativePath, handlerFunc);
  223. Handle("GET", relativePath, handlerFunc);
  224. Handle("POST", relativePath, handlerFunc);
  225. Handle("PUT", relativePath, handlerFunc);
  226. Handle("DELETE", relativePath, handlerFunc);
  227. Handle("PATCH", relativePath, handlerFunc);
  228. }
  229. void Any(const char* relativePath, http_ctx_handler handlerFunc) {
  230. Handle("HEAD", relativePath, handlerFunc);
  231. Handle("GET", relativePath, handlerFunc);
  232. Handle("POST", relativePath, handlerFunc);
  233. Handle("PUT", relativePath, handlerFunc);
  234. Handle("DELETE", relativePath, handlerFunc);
  235. Handle("PATCH", relativePath, handlerFunc);
  236. }
  237. };
  238. }
  239. #endif // HV_HTTP_SERVICE_H_