handler.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #ifndef HV_HTTPD_HANDLER_H
  2. #define HV_HTTPD_HANDLER_H
  3. #include <future> // import std::async
  4. #include "hbase.h"
  5. #include "htime.h"
  6. #include "hfile.h"
  7. #include "hstring.h"
  8. #include "EventLoop.h" // import setTimeout, setInterval
  9. #include "HttpService.h"
  10. class Handler {
  11. public:
  12. // preprocessor => api_handlers => postprocessor
  13. static int preprocessor(HttpRequest* req, HttpResponse* resp) {
  14. // printf("%s:%d\n", req->client_addr.ip.c_str(), req->client_addr.port);
  15. // printf("%s\n", req->Dump(true, true).c_str());
  16. // if (req->content_type != APPLICATION_JSON) {
  17. // return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  18. // }
  19. req->ParseBody();
  20. resp->content_type = APPLICATION_JSON;
  21. // cors
  22. resp->headers["Access-Control-Allow-Origin"] = "*";
  23. if (req->method == HTTP_OPTIONS) {
  24. resp->headers["Access-Control-Allow-Origin"] = req->GetHeader("Origin", "*");
  25. resp->headers["Access-Control-Allow-Methods"] = req->GetHeader("Access-Control-Request-Method", "OPTIONS, HEAD, GET, POST, PUT, DELETE, PATCH");
  26. resp->headers["Access-Control-Allow-Headers"] = req->GetHeader("Access-Control-Request-Headers", "Content-Type");
  27. return HTTP_STATUS_NO_CONTENT;
  28. }
  29. #if 0
  30. // authentication sample code
  31. if (strcmp(req->path.c_str(), "/login") != 0) {
  32. string token = req->GetHeader("token");
  33. if (token.empty()) {
  34. response_status(resp, 10011, "Miss token");
  35. return HTTP_STATUS_UNAUTHORIZED;
  36. }
  37. else if (strcmp(token.c_str(), "abcdefg") != 0) {
  38. response_status(resp, 10012, "Token wrong");
  39. return HTTP_STATUS_UNAUTHORIZED;
  40. }
  41. return 0;
  42. }
  43. #endif
  44. return 0;
  45. }
  46. static int postprocessor(HttpRequest* req, HttpResponse* resp) {
  47. // printf("%s\n", resp->Dump(true, true).c_str());
  48. return 0;
  49. }
  50. static int errorHandler(const HttpContextPtr& ctx) {
  51. int error_code = ctx->response->status_code;
  52. return response_status(ctx->response.get(), error_code);
  53. }
  54. static int largeFileHandler(const HttpContextPtr& ctx) {
  55. std::async([ctx](){
  56. ctx->writer->Begin();
  57. std::string filepath = ctx->service->document_root + ctx->request->Path();
  58. HFile file;
  59. if (file.open(filepath.c_str(), "rb") != 0) {
  60. ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND);
  61. ctx->writer->WriteHeader("Content-Type", "text/html");
  62. ctx->writer->WriteBody("<center><h1>404 Not Found</h1></center>");
  63. ctx->writer->End();
  64. return;
  65. }
  66. http_content_type content_type = CONTENT_TYPE_NONE;
  67. const char* suffix = hv_suffixname(filepath.c_str());
  68. if (suffix) {
  69. content_type = http_content_type_enum_by_suffix(suffix);
  70. }
  71. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  72. content_type = APPLICATION_OCTET_STREAM;
  73. }
  74. size_t filesize = file.size();
  75. ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type));
  76. ctx->writer->WriteHeader("Content-Length", filesize);
  77. ctx->writer->EndHeaders();
  78. char* buf = NULL;
  79. int len = 4096; // 4K
  80. SAFE_ALLOC(buf, len);
  81. size_t total_readbytes = 0;
  82. while (total_readbytes < filesize) {
  83. size_t readbytes = file.read(buf, len);
  84. if (readbytes <= 0) {
  85. ctx->writer->close();
  86. break;
  87. }
  88. if (ctx->writer->WriteBody(buf, readbytes) < 0) {
  89. break;
  90. }
  91. total_readbytes += readbytes;
  92. }
  93. ctx->writer->End();
  94. SAFE_FREE(buf);
  95. });
  96. return 0;
  97. }
  98. static int sleep(HttpRequest* req, HttpResponse* resp) {
  99. resp->Set("start_ms", gettimeofday_ms());
  100. std::string strTime = req->GetParam("t");
  101. if (!strTime.empty()) {
  102. int ms = atoi(strTime.c_str());
  103. if (ms > 0) {
  104. hv_delay(ms);
  105. }
  106. }
  107. resp->Set("end_ms", gettimeofday_ms());
  108. response_status(resp, 0, "OK");
  109. return 200;
  110. }
  111. static void setTimeout(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
  112. writer->response->Set("start_ms", gettimeofday_ms());
  113. std::string strTime = req->GetParam("t");
  114. if (!strTime.empty()) {
  115. int ms = atoi(strTime.c_str());
  116. if (ms > 0) {
  117. hv::setTimeout(ms, [writer](hv::TimerID timerID){
  118. writer->Begin();
  119. HttpResponse* resp = writer->response.get();
  120. resp->Set("end_ms", gettimeofday_ms());
  121. response_status(resp, 0, "OK");
  122. writer->End();
  123. });
  124. }
  125. }
  126. }
  127. static int query(HttpRequest* req, HttpResponse* resp) {
  128. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  129. // ?query => HttpRequest::query_params
  130. for (auto& param : req->query_params) {
  131. resp->Set(param.first.c_str(), param.second);
  132. }
  133. response_status(resp, 0, "OK");
  134. return 200;
  135. }
  136. static int kv(HttpRequest* req, HttpResponse* resp) {
  137. if (req->content_type != APPLICATION_URLENCODED) {
  138. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  139. }
  140. resp->content_type = APPLICATION_URLENCODED;
  141. resp->kv = req->kv;
  142. resp->kv["int"] = hv::to_string(123);
  143. resp->kv["float"] = hv::to_string(3.14);
  144. resp->kv["string"] = "hello";
  145. return 200;
  146. }
  147. static int json(HttpRequest* req, HttpResponse* resp) {
  148. if (req->content_type != APPLICATION_JSON) {
  149. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  150. }
  151. resp->content_type = APPLICATION_JSON;
  152. resp->json = req->json;
  153. resp->json["int"] = 123;
  154. resp->json["float"] = 3.14;
  155. resp->json["string"] = "hello";
  156. return 200;
  157. }
  158. static int form(HttpRequest* req, HttpResponse* resp) {
  159. if (req->content_type != MULTIPART_FORM_DATA) {
  160. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  161. }
  162. resp->content_type = MULTIPART_FORM_DATA;
  163. resp->form = req->form;
  164. resp->form["int"] = 123;
  165. resp->form["float"] = 3.14;
  166. resp->form["string"] = "hello";
  167. // resp->form["file"] = FormData(NULL, "test.jpg");
  168. // resp->UploadFormFile("file", "test.jpg");
  169. return 200;
  170. }
  171. static int test(HttpRequest* req, HttpResponse* resp) {
  172. // bool b = req->Get<bool>("bool");
  173. // int64_t n = req->Get<int64_t>("int");
  174. // double f = req->Get<double>("float");
  175. bool b = req->GetBool("bool");
  176. int64_t n = req->GetInt("int");
  177. double f = req->GetFloat("float");
  178. string str = req->GetString("string");
  179. resp->content_type = req->content_type;
  180. resp->Set("bool", b);
  181. resp->Set("int", n);
  182. resp->Set("float", f);
  183. resp->Set("string", str);
  184. response_status(resp, 0, "OK");
  185. return 200;
  186. }
  187. static int grpc(HttpRequest* req, HttpResponse* resp) {
  188. if (req->content_type != APPLICATION_GRPC) {
  189. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  190. }
  191. // parse protobuf
  192. // ParseFromString(req->body);
  193. // resp->content_type = APPLICATION_GRPC;
  194. // serailize protobuf
  195. // resp->body = SerializeAsString(xxx);
  196. response_status(resp, 0, "OK");
  197. return 200;
  198. }
  199. static int restful(HttpRequest* req, HttpResponse* resp) {
  200. // RESTful /:field/ => HttpRequest::query_params
  201. // path=/group/:group_name/user/:user_id
  202. std::string group_name = req->GetParam("group_name");
  203. std::string user_id = req->GetParam("user_id");
  204. resp->Set("group_name", group_name);
  205. resp->Set("user_id", user_id);
  206. response_status(resp, 0, "OK");
  207. return 200;
  208. }
  209. static int login(HttpRequest* req, HttpResponse* resp) {
  210. string username = req->GetString("username");
  211. string password = req->GetString("password");
  212. if (username.empty() || password.empty()) {
  213. response_status(resp, 10001, "Miss username or password");
  214. return HTTP_STATUS_BAD_REQUEST;
  215. }
  216. else if (strcmp(username.c_str(), "admin") != 0) {
  217. response_status(resp, 10002, "Username not exist");
  218. return HTTP_STATUS_BAD_REQUEST;
  219. }
  220. else if (strcmp(password.c_str(), "123456") != 0) {
  221. response_status(resp, 10003, "Password wrong");
  222. return HTTP_STATUS_BAD_REQUEST;
  223. }
  224. else {
  225. resp->Set("token", "abcdefg");
  226. response_status(resp, 0, "OK");
  227. return HTTP_STATUS_OK;
  228. }
  229. }
  230. static int upload(HttpRequest* req, HttpResponse* resp) {
  231. // return resp->SaveFormFile("file", "html/uploads/test.jpg");
  232. if (req->content_type != MULTIPART_FORM_DATA) {
  233. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  234. }
  235. const FormData& file = req->form["file"];
  236. if (file.content.empty()) {
  237. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  238. }
  239. string filepath("html/uploads/");
  240. filepath += file.filename;
  241. FILE* fp = fopen(filepath.c_str(), "wb");
  242. if (fp) {
  243. fwrite(file.content.data(), 1, file.content.size(), fp);
  244. fclose(fp);
  245. }
  246. response_status(resp, 0, "OK");
  247. return 200;
  248. }
  249. private:
  250. static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) {
  251. resp->Set("code", code);
  252. if (message == NULL) message = http_status_str((enum http_status)code);
  253. resp->Set("message", message);
  254. resp->DumpBody();
  255. return code;
  256. }
  257. };
  258. #endif // HV_HTTPD_HANDLER_H