1
0

handler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 = 40960; // 40K
  80. SAFE_ALLOC(buf, len);
  81. size_t total_readbytes = 0;
  82. int last_progress = 0;
  83. int sleep_ms_per_send = 0;
  84. if (ctx->service->limit_rate <= 0) {
  85. // unlimited
  86. } else {
  87. sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate;
  88. }
  89. if (sleep_ms_per_send == 0) sleep_ms_per_send = 1;
  90. int sleep_ms = sleep_ms_per_send;
  91. auto start_time = std::chrono::steady_clock::now();
  92. auto end_time = start_time;
  93. while (total_readbytes < filesize) {
  94. if (!ctx->writer->isConnected()) {
  95. break;
  96. }
  97. if (!ctx->writer->isWriteComplete()) {
  98. hv_delay(1);
  99. continue;
  100. }
  101. size_t readbytes = file.read(buf, len);
  102. if (readbytes <= 0) {
  103. // read file error!
  104. ctx->writer->close();
  105. break;
  106. }
  107. int nwrite = ctx->writer->WriteBody(buf, readbytes);
  108. if (nwrite < 0) {
  109. // disconnected!
  110. break;
  111. }
  112. total_readbytes += readbytes;
  113. int cur_progress = total_readbytes * 100 / filesize;
  114. if (cur_progress > last_progress) {
  115. // printf("<< %s progress: %ld/%ld = %d%%\n",
  116. // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress);
  117. last_progress = cur_progress;
  118. }
  119. end_time += std::chrono::milliseconds(sleep_ms);
  120. std::this_thread::sleep_until(end_time);
  121. }
  122. ctx->writer->End();
  123. SAFE_FREE(buf);
  124. // auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
  125. // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count());
  126. }).detach();
  127. return HTTP_STATUS_UNFINISHED;
  128. }
  129. int Handler::sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
  130. writer->WriteHeader("X-Response-tid", hv_gettid());
  131. unsigned long long start_ms = gettimeofday_ms();
  132. writer->response->Set("start_ms", start_ms);
  133. std::string strTime = req->GetParam("t", "1000");
  134. if (!strTime.empty()) {
  135. int ms = atoi(strTime.c_str());
  136. if (ms > 0) {
  137. hv_delay(ms);
  138. }
  139. }
  140. unsigned long long end_ms = gettimeofday_ms();
  141. writer->response->Set("end_ms", end_ms);
  142. writer->response->Set("cost_ms", end_ms - start_ms);
  143. response_status(writer, 0, "OK");
  144. return 200;
  145. }
  146. int Handler::setTimeout(const HttpContextPtr& ctx) {
  147. unsigned long long start_ms = gettimeofday_ms();
  148. ctx->set("start_ms", start_ms);
  149. std::string strTime = ctx->param("t", "1000");
  150. if (!strTime.empty()) {
  151. int ms = atoi(strTime.c_str());
  152. if (ms > 0) {
  153. hv::setTimeout(ms, [ctx, start_ms](hv::TimerID timerID){
  154. unsigned long long end_ms = gettimeofday_ms();
  155. ctx->set("end_ms", end_ms);
  156. ctx->set("cost_ms", end_ms - start_ms);
  157. response_status(ctx, 0, "OK");
  158. });
  159. }
  160. }
  161. return HTTP_STATUS_UNFINISHED;
  162. }
  163. int Handler::query(const HttpContextPtr& ctx) {
  164. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  165. // ?query => HttpRequest::query_params
  166. for (auto& param : ctx->params()) {
  167. ctx->set(param.first.c_str(), param.second);
  168. }
  169. response_status(ctx, 0, "OK");
  170. return 200;
  171. }
  172. int Handler::kv(HttpRequest* req, HttpResponse* resp) {
  173. if (req->content_type != APPLICATION_URLENCODED) {
  174. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  175. }
  176. resp->content_type = APPLICATION_URLENCODED;
  177. resp->kv = req->GetUrlEncoded();
  178. resp->SetUrlEncoded("int", 123);
  179. resp->SetUrlEncoded("float", 3.14);
  180. resp->SetUrlEncoded("string", "hello");
  181. return 200;
  182. }
  183. int Handler::json(HttpRequest* req, HttpResponse* resp) {
  184. if (req->content_type != APPLICATION_JSON) {
  185. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  186. }
  187. resp->content_type = APPLICATION_JSON;
  188. resp->json = req->GetJson();
  189. resp->json["int"] = 123;
  190. resp->json["float"] = 3.14;
  191. resp->json["string"] = "hello";
  192. return 200;
  193. }
  194. int Handler::form(HttpRequest* req, HttpResponse* resp) {
  195. if (req->content_type != MULTIPART_FORM_DATA) {
  196. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  197. }
  198. resp->content_type = MULTIPART_FORM_DATA;
  199. resp->form = req->GetForm();
  200. resp->SetFormData("int", 123);
  201. resp->SetFormData("float", 3.14);
  202. resp->SetFormData("string", "hello");
  203. // resp->SetFormFile("file", "test.jpg");
  204. return 200;
  205. }
  206. int Handler::grpc(HttpRequest* req, HttpResponse* resp) {
  207. if (req->content_type != APPLICATION_GRPC) {
  208. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  209. }
  210. // parse protobuf
  211. // ParseFromString(req->body);
  212. // resp->content_type = APPLICATION_GRPC;
  213. // serailize protobuf
  214. // resp->body = SerializeAsString(xxx);
  215. response_status(resp, 0, "OK");
  216. return 200;
  217. }
  218. int Handler::test(const HttpContextPtr& ctx) {
  219. ctx->setContentType(ctx->type());
  220. ctx->set("bool", ctx->get<bool>("bool"));
  221. ctx->set("int", ctx->get<int>("int"));
  222. ctx->set("float", ctx->get<float>("float"));
  223. ctx->set("string", ctx->get("string"));
  224. response_status(ctx, 0, "OK");
  225. return 200;
  226. }
  227. int Handler::restful(const HttpContextPtr& ctx) {
  228. // RESTful /:field/ => HttpRequest::query_params
  229. // path=/group/:group_name/user/:user_id
  230. std::string group_name = ctx->param("group_name");
  231. std::string user_id = ctx->param("user_id");
  232. ctx->set("group_name", group_name);
  233. ctx->set("user_id", user_id);
  234. response_status(ctx, 0, "OK");
  235. return 200;
  236. }
  237. int Handler::login(const HttpContextPtr& ctx) {
  238. std::string username = ctx->get("username");
  239. std::string password = ctx->get("password");
  240. if (username.empty() || password.empty()) {
  241. response_status(ctx, 10001, "Miss username or password");
  242. return HTTP_STATUS_BAD_REQUEST;
  243. }
  244. else if (strcmp(username.c_str(), "admin") != 0) {
  245. response_status(ctx, 10002, "Username not exist");
  246. return HTTP_STATUS_BAD_REQUEST;
  247. }
  248. else if (strcmp(password.c_str(), "123456") != 0) {
  249. response_status(ctx, 10003, "Password wrong");
  250. return HTTP_STATUS_BAD_REQUEST;
  251. }
  252. else {
  253. ctx->set("token", "abcdefg");
  254. response_status(ctx, 0, "OK");
  255. return HTTP_STATUS_OK;
  256. }
  257. }
  258. int Handler::upload(const HttpContextPtr& ctx) {
  259. int status_code = 200;
  260. if (ctx->is(MULTIPART_FORM_DATA)) {
  261. status_code = ctx->request->SaveFormFile("file", "html/uploads/");
  262. } else {
  263. status_code = ctx->request->SaveFile("html/uploads/upload.txt");
  264. }
  265. return response_status(ctx, status_code);
  266. }
  267. int Handler::sse(const HttpContextPtr& ctx) {
  268. ctx->writer->EndHeaders("Content-Type", "text/event-stream");
  269. // send(message) every 1s
  270. hv::setInterval(1000, [ctx](hv::TimerID timerID) {
  271. char szTime[DATETIME_FMT_BUFLEN] = {0};
  272. datetime_t now = datetime_now();
  273. datetime_fmt(&now, szTime);
  274. // @test html/EventSource.html EventSource.onmessage
  275. std::string msg("event: message\n");
  276. msg += "data: ";
  277. msg += szTime;
  278. msg += "\n\n";
  279. ctx->writer->write(msg);
  280. });
  281. return HTTP_STATUS_UNFINISHED;
  282. }