handler.cpp 9.0 KB

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