HttpService.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. // NOTE: http_state_handler run on IO thread
  37. typedef std::function<int(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size)> http_state_handler;
  38. struct http_handler {
  39. http_sync_handler sync_handler;
  40. http_async_handler async_handler;
  41. http_ctx_handler ctx_handler;
  42. http_state_handler state_handler;
  43. http_handler() {}
  44. http_handler(http_sync_handler fn) : sync_handler(std::move(fn)) {}
  45. http_handler(http_async_handler fn) : async_handler(std::move(fn)) {}
  46. http_handler(http_ctx_handler fn) : ctx_handler(std::move(fn)) {}
  47. http_handler(http_state_handler fn) : state_handler(std::move(fn)) {}
  48. http_handler(const http_handler& rhs)
  49. : sync_handler(std::move(rhs.sync_handler))
  50. , async_handler(std::move(rhs.async_handler))
  51. , ctx_handler(std::move(rhs.ctx_handler))
  52. , state_handler(std::move(rhs.state_handler))
  53. {}
  54. const http_handler& operator=(http_sync_handler fn) {
  55. sync_handler = std::move(fn);
  56. return *this;
  57. }
  58. const http_handler& operator=(http_async_handler fn) {
  59. async_handler = std::move(fn);
  60. return *this;
  61. }
  62. const http_handler& operator=(http_ctx_handler fn) {
  63. ctx_handler = std::move(fn);
  64. return *this;
  65. }
  66. const http_handler& operator=(http_state_handler fn) {
  67. state_handler = std::move(fn);
  68. return *this;
  69. }
  70. bool isNull() {
  71. return sync_handler == NULL &&
  72. async_handler == NULL &&
  73. ctx_handler == NULL;
  74. }
  75. operator bool() {
  76. return !isNull();
  77. }
  78. };
  79. struct http_method_handler {
  80. http_method method;
  81. http_handler handler;
  82. http_method_handler() {}
  83. http_method_handler(http_method m, const http_handler& h) : method(m), handler(h) {}
  84. };
  85. // method => http_method_handler
  86. typedef std::list<http_method_handler> http_method_handlers;
  87. // path => http_method_handlers
  88. typedef std::unordered_map<std::string, std::shared_ptr<http_method_handlers>> http_api_handlers;
  89. namespace hv {
  90. struct HV_EXPORT HttpService {
  91. // preprocessor -> processor -> postprocessor
  92. http_handler preprocessor;
  93. // processor: api_handlers -> staticHandler -> errorHandler
  94. http_handler processor;
  95. http_handler postprocessor;
  96. // api service (that is http.ApiServer)
  97. std::string base_url;
  98. http_api_handlers api_handlers;
  99. // file service (that is http.FileServer)
  100. http_handler staticHandler;
  101. http_handler largeFileHandler;
  102. std::string document_root;
  103. std::string home_page;
  104. std::string error_page;
  105. // nginx: location => root
  106. std::map<std::string, std::string, std::greater<std::string>> staticDirs;
  107. // indexof service (that is http.DirectoryServer)
  108. std::string index_of;
  109. http_handler errorHandler;
  110. // proxy service (that is http.ProxyServer)
  111. // nginx: location => proxy_pass
  112. std::map<std::string, std::string, std::greater<std::string>> proxies;
  113. int proxy_connect_timeout;
  114. int proxy_read_timeout;
  115. int proxy_write_timeout;
  116. // options
  117. int keepalive_timeout;
  118. int max_file_cache_size; // cache small file
  119. int file_cache_stat_interval; // stat file is modified
  120. int file_cache_expired_time; // remove expired file cache
  121. /*
  122. * @test limit_rate
  123. * @build make examples
  124. * @server bin/httpd -c etc/httpd.conf -s restart -d
  125. * @client bin/wget http://127.0.0.1:8080/downloads/test.zip
  126. */
  127. int limit_rate; // limit send rate, unit: KB/s
  128. HttpService() {
  129. // base_url = DEFAULT_BASE_URL;
  130. document_root = DEFAULT_DOCUMENT_ROOT;
  131. home_page = DEFAULT_HOME_PAGE;
  132. // error_page = DEFAULT_ERROR_PAGE;
  133. // index_of = DEFAULT_INDEXOF_DIR;
  134. proxy_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
  135. proxy_read_timeout = 0;
  136. proxy_write_timeout = 0;
  137. keepalive_timeout = DEFAULT_KEEPALIVE_TIMEOUT;
  138. max_file_cache_size = MAX_FILE_CACHE_SIZE;
  139. file_cache_stat_interval = DEFAULT_FILE_CACHE_STAT_INTERVAL;
  140. file_cache_expired_time = DEFAULT_FILE_CACHE_EXPIRED_TIME;
  141. limit_rate = -1; // unlimited
  142. }
  143. void AddApi(const char* path, http_method method, const http_handler& handler);
  144. // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED
  145. int GetApi(const char* url, http_method method, http_handler** handler);
  146. // RESTful API /:field/ => req->query_params["field"]
  147. int GetApi(HttpRequest* req, http_handler** handler);
  148. // Static("/", "/var/www/html")
  149. void Static(const char* path, const char* dir);
  150. // @retval / => /var/www/html/index.html
  151. std::string GetStaticFilepath(const char* path);
  152. // Proxy("/api/v1/", "http://www.httpbin.org/");
  153. void Proxy(const char* path, const char* url);
  154. // @retval /api/v1/test => http://www.httpbin.org/test
  155. std::string GetProxyUrl(const char* path);
  156. hv::StringList Paths() {
  157. hv::StringList paths;
  158. for (auto& pair : api_handlers) {
  159. paths.emplace_back(pair.first);
  160. }
  161. return paths;
  162. }
  163. // github.com/gin-gonic/gin
  164. void Handle(const char* httpMethod, const char* relativePath, http_sync_handler handlerFunc) {
  165. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  166. }
  167. void Handle(const char* httpMethod, const char* relativePath, http_async_handler handlerFunc) {
  168. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  169. }
  170. void Handle(const char* httpMethod, const char* relativePath, http_ctx_handler handlerFunc) {
  171. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  172. }
  173. void Handle(const char* httpMethod, const char* relativePath, http_state_handler handlerFunc) {
  174. AddApi(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc));
  175. }
  176. // HEAD
  177. void HEAD(const char* relativePath, http_sync_handler handlerFunc) {
  178. Handle("HEAD", relativePath, handlerFunc);
  179. }
  180. void HEAD(const char* relativePath, http_async_handler handlerFunc) {
  181. Handle("HEAD", relativePath, handlerFunc);
  182. }
  183. void HEAD(const char* relativePath, http_ctx_handler handlerFunc) {
  184. Handle("HEAD", relativePath, handlerFunc);
  185. }
  186. void HEAD(const char* relativePath, http_state_handler handlerFunc) {
  187. Handle("HEAD", relativePath, handlerFunc);
  188. }
  189. // GET
  190. void GET(const char* relativePath, http_sync_handler handlerFunc) {
  191. Handle("GET", relativePath, handlerFunc);
  192. }
  193. void GET(const char* relativePath, http_async_handler handlerFunc) {
  194. Handle("GET", relativePath, handlerFunc);
  195. }
  196. void GET(const char* relativePath, http_ctx_handler handlerFunc) {
  197. Handle("GET", relativePath, handlerFunc);
  198. }
  199. void GET(const char* relativePath, http_state_handler handlerFunc) {
  200. Handle("GET", relativePath, handlerFunc);
  201. }
  202. // POST
  203. void POST(const char* relativePath, http_sync_handler handlerFunc) {
  204. Handle("POST", relativePath, handlerFunc);
  205. }
  206. void POST(const char* relativePath, http_async_handler handlerFunc) {
  207. Handle("POST", relativePath, handlerFunc);
  208. }
  209. void POST(const char* relativePath, http_ctx_handler handlerFunc) {
  210. Handle("POST", relativePath, handlerFunc);
  211. }
  212. void POST(const char* relativePath, http_state_handler handlerFunc) {
  213. Handle("POST", relativePath, handlerFunc);
  214. }
  215. // PUT
  216. void PUT(const char* relativePath, http_sync_handler handlerFunc) {
  217. Handle("PUT", relativePath, handlerFunc);
  218. }
  219. void PUT(const char* relativePath, http_async_handler handlerFunc) {
  220. Handle("PUT", relativePath, handlerFunc);
  221. }
  222. void PUT(const char* relativePath, http_ctx_handler handlerFunc) {
  223. Handle("PUT", relativePath, handlerFunc);
  224. }
  225. void PUT(const char* relativePath, http_state_handler handlerFunc) {
  226. Handle("PUT", relativePath, handlerFunc);
  227. }
  228. // DELETE
  229. // NOTE: Windows <winnt.h> #define DELETE as a macro, we have to replace DELETE with Delete.
  230. void Delete(const char* relativePath, http_sync_handler handlerFunc) {
  231. Handle("DELETE", relativePath, handlerFunc);
  232. }
  233. void Delete(const char* relativePath, http_async_handler handlerFunc) {
  234. Handle("DELETE", relativePath, handlerFunc);
  235. }
  236. void Delete(const char* relativePath, http_ctx_handler handlerFunc) {
  237. Handle("DELETE", relativePath, handlerFunc);
  238. }
  239. void Delete(const char* relativePath, http_state_handler handlerFunc) {
  240. Handle("DELETE", relativePath, handlerFunc);
  241. }
  242. // PATCH
  243. void PATCH(const char* relativePath, http_sync_handler handlerFunc) {
  244. Handle("PATCH", relativePath, handlerFunc);
  245. }
  246. void PATCH(const char* relativePath, http_async_handler handlerFunc) {
  247. Handle("PATCH", relativePath, handlerFunc);
  248. }
  249. void PATCH(const char* relativePath, http_ctx_handler handlerFunc) {
  250. Handle("PATCH", relativePath, handlerFunc);
  251. }
  252. void PATCH(const char* relativePath, http_state_handler handlerFunc) {
  253. Handle("PATCH", relativePath, handlerFunc);
  254. }
  255. // Any
  256. void Any(const char* relativePath, http_sync_handler handlerFunc) {
  257. Handle("HEAD", relativePath, handlerFunc);
  258. Handle("GET", relativePath, handlerFunc);
  259. Handle("POST", relativePath, handlerFunc);
  260. Handle("PUT", relativePath, handlerFunc);
  261. Handle("DELETE", relativePath, handlerFunc);
  262. Handle("PATCH", relativePath, handlerFunc);
  263. }
  264. void Any(const char* relativePath, http_async_handler handlerFunc) {
  265. Handle("HEAD", relativePath, handlerFunc);
  266. Handle("GET", relativePath, handlerFunc);
  267. Handle("POST", relativePath, handlerFunc);
  268. Handle("PUT", relativePath, handlerFunc);
  269. Handle("DELETE", relativePath, handlerFunc);
  270. Handle("PATCH", relativePath, handlerFunc);
  271. }
  272. void Any(const char* relativePath, http_ctx_handler handlerFunc) {
  273. Handle("HEAD", relativePath, handlerFunc);
  274. Handle("GET", relativePath, handlerFunc);
  275. Handle("POST", relativePath, handlerFunc);
  276. Handle("PUT", relativePath, handlerFunc);
  277. Handle("DELETE", relativePath, handlerFunc);
  278. Handle("PATCH", relativePath, handlerFunc);
  279. }
  280. void Any(const char* relativePath, http_state_handler handlerFunc) {
  281. Handle("HEAD", relativePath, handlerFunc);
  282. Handle("GET", relativePath, handlerFunc);
  283. Handle("POST", relativePath, handlerFunc);
  284. Handle("PUT", relativePath, handlerFunc);
  285. Handle("DELETE", relativePath, handlerFunc);
  286. Handle("PATCH", relativePath, handlerFunc);
  287. }
  288. };
  289. }
  290. #endif // HV_HTTP_SERVICE_H_