1
0

handler.cpp 9.1 KB

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