handler.h 11 KB

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