handler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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::sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
  54. writer->WriteHeader("X-Response-tid", hv_gettid());
  55. unsigned long long start_ms = gettimeofday_ms();
  56. writer->response->Set("start_ms", start_ms);
  57. std::string strTime = req->GetParam("t", "1000");
  58. if (!strTime.empty()) {
  59. int ms = atoi(strTime.c_str());
  60. if (ms > 0) {
  61. hv_delay(ms);
  62. }
  63. }
  64. unsigned long long end_ms = gettimeofday_ms();
  65. writer->response->Set("end_ms", end_ms);
  66. writer->response->Set("cost_ms", end_ms - start_ms);
  67. response_status(writer, 0, "OK");
  68. return 200;
  69. }
  70. int Handler::setTimeout(const HttpContextPtr& ctx) {
  71. unsigned long long start_ms = gettimeofday_ms();
  72. ctx->set("start_ms", start_ms);
  73. std::string strTime = ctx->param("t", "1000");
  74. if (!strTime.empty()) {
  75. int ms = atoi(strTime.c_str());
  76. if (ms > 0) {
  77. hv::setTimeout(ms, [ctx, start_ms](hv::TimerID timerID){
  78. unsigned long long end_ms = gettimeofday_ms();
  79. ctx->set("end_ms", end_ms);
  80. ctx->set("cost_ms", end_ms - start_ms);
  81. response_status(ctx, 0, "OK");
  82. });
  83. }
  84. }
  85. return HTTP_STATUS_UNFINISHED;
  86. }
  87. int Handler::query(const HttpContextPtr& ctx) {
  88. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  89. // ?query => HttpRequest::query_params
  90. for (auto& param : ctx->params()) {
  91. ctx->set(param.first.c_str(), param.second);
  92. }
  93. response_status(ctx, 0, "OK");
  94. return 200;
  95. }
  96. int Handler::kv(HttpRequest* req, HttpResponse* resp) {
  97. if (req->content_type != APPLICATION_URLENCODED) {
  98. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  99. }
  100. resp->content_type = APPLICATION_URLENCODED;
  101. resp->kv = req->GetUrlEncoded();
  102. resp->SetUrlEncoded("int", 123);
  103. resp->SetUrlEncoded("float", 3.14);
  104. resp->SetUrlEncoded("string", "hello");
  105. return 200;
  106. }
  107. int Handler::json(HttpRequest* req, HttpResponse* resp) {
  108. if (req->content_type != APPLICATION_JSON) {
  109. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  110. }
  111. resp->content_type = APPLICATION_JSON;
  112. resp->json = req->GetJson();
  113. resp->json["int"] = 123;
  114. resp->json["float"] = 3.14;
  115. resp->json["string"] = "hello";
  116. return 200;
  117. }
  118. int Handler::form(HttpRequest* req, HttpResponse* resp) {
  119. if (req->content_type != MULTIPART_FORM_DATA) {
  120. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  121. }
  122. resp->content_type = MULTIPART_FORM_DATA;
  123. resp->form = req->GetForm();
  124. resp->SetFormData("int", 123);
  125. resp->SetFormData("float", 3.14);
  126. resp->SetFormData("string", "hello");
  127. // resp->SetFormFile("file", "test.jpg");
  128. return 200;
  129. }
  130. int Handler::grpc(HttpRequest* req, HttpResponse* resp) {
  131. if (req->content_type != APPLICATION_GRPC) {
  132. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  133. }
  134. // parse protobuf
  135. // ParseFromString(req->body);
  136. // resp->content_type = APPLICATION_GRPC;
  137. // serailize protobuf
  138. // resp->body = SerializeAsString(xxx);
  139. response_status(resp, 0, "OK");
  140. return 200;
  141. }
  142. int Handler::test(const HttpContextPtr& ctx) {
  143. ctx->setContentType(ctx->type());
  144. ctx->set("bool", ctx->get<bool>("bool"));
  145. ctx->set("int", ctx->get<int>("int"));
  146. ctx->set("float", ctx->get<float>("float"));
  147. ctx->set("string", ctx->get("string"));
  148. response_status(ctx, 0, "OK");
  149. return 200;
  150. }
  151. int Handler::restful(const HttpContextPtr& ctx) {
  152. // RESTful /:field/ => HttpRequest::query_params
  153. // path=/group/:group_name/user/:user_id
  154. std::string group_name = ctx->param("group_name");
  155. std::string user_id = ctx->param("user_id");
  156. ctx->set("group_name", group_name);
  157. ctx->set("user_id", user_id);
  158. response_status(ctx, 0, "OK");
  159. return 200;
  160. }
  161. int Handler::login(const HttpContextPtr& ctx) {
  162. std::string username = ctx->get("username");
  163. std::string password = ctx->get("password");
  164. if (username.empty() || password.empty()) {
  165. response_status(ctx, 10001, "Miss username or password");
  166. return HTTP_STATUS_BAD_REQUEST;
  167. }
  168. else if (strcmp(username.c_str(), "admin") != 0) {
  169. response_status(ctx, 10002, "Username not exist");
  170. return HTTP_STATUS_BAD_REQUEST;
  171. }
  172. else if (strcmp(password.c_str(), "123456") != 0) {
  173. response_status(ctx, 10003, "Password wrong");
  174. return HTTP_STATUS_BAD_REQUEST;
  175. }
  176. else {
  177. ctx->set("token", "abcdefg");
  178. response_status(ctx, 0, "OK");
  179. return HTTP_STATUS_OK;
  180. }
  181. }
  182. int Handler::upload(const HttpContextPtr& ctx) {
  183. int status_code = 200;
  184. std::string save_path = "html/uploads/";
  185. if (ctx->is(MULTIPART_FORM_DATA)) {
  186. status_code = ctx->request->SaveFormFile("file", save_path.c_str());
  187. } else {
  188. std::string filename = ctx->param("filename", "unnamed.txt");
  189. std::string filepath = save_path + filename;
  190. status_code = ctx->request->SaveFile(filepath.c_str());
  191. }
  192. return response_status(ctx, status_code);
  193. }
  194. int Handler::recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size) {
  195. switch (state) {
  196. case HP_HEADERS_COMPLETE:
  197. {
  198. ctx->setContentType(APPLICATION_JSON);
  199. std::string save_path = "html/uploads/";
  200. std::string filename = ctx->param("filename", "unnamed.txt");
  201. std::string filepath = save_path + filename;
  202. HFile* file = new HFile;
  203. if (file->open(filepath.c_str(), "wb") != 0) {
  204. return response_status(ctx, HTTP_STATUS_INTERNAL_SERVER_ERROR);
  205. }
  206. ctx->userdata = file;
  207. }
  208. case HP_BODY:
  209. {
  210. HFile* file = (HFile*)ctx->userdata;
  211. if (file && data && size) {
  212. if (file->write(data, size) != size) {
  213. return response_status(ctx, HTTP_STATUS_INTERNAL_SERVER_ERROR);
  214. }
  215. }
  216. }
  217. break;
  218. case HP_MESSAGE_COMPLETE:
  219. {
  220. HFile* file = (HFile*)ctx->userdata;
  221. delete file;
  222. return response_status(ctx, HTTP_STATUS_OK);
  223. }
  224. break;
  225. case HP_ERROR:
  226. {
  227. HFile* file = (HFile*)ctx->userdata;
  228. delete file;
  229. }
  230. break;
  231. default:
  232. break;
  233. }
  234. return HTTP_STATUS_UNFINISHED;
  235. }
  236. int Handler::sendLargeFile(const HttpContextPtr& ctx) {
  237. std::thread([ctx](){
  238. ctx->writer->Begin();
  239. std::string filepath = ctx->service->document_root + ctx->request->Path();
  240. HFile file;
  241. if (file.open(filepath.c_str(), "rb") != 0) {
  242. ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND);
  243. ctx->writer->WriteHeader("Content-Type", "text/html");
  244. ctx->writer->WriteBody("<center><h1>404 Not Found</h1></center>");
  245. ctx->writer->End();
  246. return;
  247. }
  248. http_content_type content_type = CONTENT_TYPE_NONE;
  249. const char* suffix = hv_suffixname(filepath.c_str());
  250. if (suffix) {
  251. content_type = http_content_type_enum_by_suffix(suffix);
  252. }
  253. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  254. content_type = APPLICATION_OCTET_STREAM;
  255. }
  256. size_t filesize = file.size();
  257. ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type));
  258. ctx->writer->WriteHeader("Content-Length", filesize);
  259. // ctx->writer->WriteHeader("Transfer-Encoding", "chunked");
  260. ctx->writer->EndHeaders();
  261. char* buf = NULL;
  262. int len = 40960; // 40K
  263. SAFE_ALLOC(buf, len);
  264. size_t total_readbytes = 0;
  265. int last_progress = 0;
  266. int sleep_ms_per_send = 0;
  267. if (ctx->service->limit_rate <= 0) {
  268. // unlimited
  269. } else {
  270. sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate;
  271. }
  272. if (sleep_ms_per_send == 0) sleep_ms_per_send = 1;
  273. int sleep_ms = sleep_ms_per_send;
  274. auto start_time = std::chrono::steady_clock::now();
  275. auto end_time = start_time;
  276. while (total_readbytes < filesize) {
  277. if (!ctx->writer->isConnected()) {
  278. break;
  279. }
  280. if (!ctx->writer->isWriteComplete()) {
  281. hv_delay(1);
  282. continue;
  283. }
  284. size_t readbytes = file.read(buf, len);
  285. if (readbytes <= 0) {
  286. // read file error!
  287. ctx->writer->close();
  288. break;
  289. }
  290. int nwrite = ctx->writer->WriteBody(buf, readbytes);
  291. if (nwrite < 0) {
  292. // disconnected!
  293. break;
  294. }
  295. total_readbytes += readbytes;
  296. int cur_progress = total_readbytes * 100 / filesize;
  297. if (cur_progress > last_progress) {
  298. // printf("<< %s progress: %ld/%ld = %d%%\n",
  299. // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress);
  300. last_progress = cur_progress;
  301. }
  302. end_time += std::chrono::milliseconds(sleep_ms);
  303. std::this_thread::sleep_until(end_time);
  304. }
  305. ctx->writer->End();
  306. SAFE_FREE(buf);
  307. // auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
  308. // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count());
  309. }).detach();
  310. return HTTP_STATUS_UNFINISHED;
  311. }
  312. int Handler::sse(const HttpContextPtr& ctx) {
  313. ctx->writer->EndHeaders("Content-Type", "text/event-stream");
  314. // send(message) every 1s
  315. hv::setInterval(1000, [ctx](hv::TimerID timerID) {
  316. char szTime[DATETIME_FMT_BUFLEN] = {0};
  317. datetime_t now = datetime_now();
  318. datetime_fmt(&now, szTime);
  319. // @test html/EventSource.html EventSource.onmessage
  320. std::string msg("event: message\n");
  321. msg += "data: ";
  322. msg += szTime;
  323. msg += "\n\n";
  324. ctx->writer->write(msg);
  325. });
  326. return HTTP_STATUS_UNFINISHED;
  327. }