handler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. // printf("recvLargeFile state=%d\n", (int)state);
  196. int status_code = HTTP_STATUS_UNFINISHED;
  197. HFile* file = (HFile*)ctx->userdata;
  198. switch (state) {
  199. case HP_HEADERS_COMPLETE:
  200. {
  201. std::string save_path = "html/uploads/";
  202. std::string filename = ctx->param("filename", "unnamed.txt");
  203. std::string filepath = save_path + filename;
  204. file = new HFile;
  205. if (file->open(filepath.c_str(), "wb") != 0) {
  206. ctx->close();
  207. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  208. }
  209. ctx->userdata = file;
  210. }
  211. break;
  212. case HP_BODY:
  213. {
  214. if (file && data && size) {
  215. if (file->write(data, size) != size) {
  216. ctx->close();
  217. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  218. }
  219. }
  220. }
  221. break;
  222. case HP_MESSAGE_COMPLETE:
  223. {
  224. status_code = HTTP_STATUS_OK;
  225. ctx->setContentType(APPLICATION_JSON);
  226. response_status(ctx, status_code);
  227. if (file) {
  228. delete file;
  229. ctx->userdata = NULL;
  230. }
  231. }
  232. break;
  233. case HP_ERROR:
  234. {
  235. if (file) {
  236. file->remove();
  237. delete file;
  238. ctx->userdata = NULL;
  239. }
  240. }
  241. break;
  242. default:
  243. break;
  244. }
  245. return status_code;
  246. }
  247. int Handler::sendLargeFile(const HttpContextPtr& ctx) {
  248. std::thread([ctx](){
  249. ctx->writer->Begin();
  250. std::string filepath = ctx->service->document_root + ctx->request->Path();
  251. HFile file;
  252. if (file.open(filepath.c_str(), "rb") != 0) {
  253. ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND);
  254. ctx->writer->WriteHeader("Content-Type", "text/html");
  255. ctx->writer->WriteBody("<center><h1>404 Not Found</h1></center>");
  256. ctx->writer->End();
  257. return;
  258. }
  259. http_content_type content_type = CONTENT_TYPE_NONE;
  260. const char* suffix = hv_suffixname(filepath.c_str());
  261. if (suffix) {
  262. content_type = http_content_type_enum_by_suffix(suffix);
  263. }
  264. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  265. content_type = APPLICATION_OCTET_STREAM;
  266. }
  267. size_t filesize = file.size();
  268. ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type));
  269. #if USE_TRANSFER_ENCODING_CHUNKED
  270. ctx->writer->WriteHeader("Transfer-Encoding", "chunked");
  271. #else
  272. ctx->writer->WriteHeader("Content-Length", filesize);
  273. #endif
  274. ctx->writer->EndHeaders();
  275. char* buf = NULL;
  276. int len = 40960; // 40K
  277. SAFE_ALLOC(buf, len);
  278. size_t total_readbytes = 0;
  279. int last_progress = 0;
  280. int sleep_ms_per_send = 0;
  281. if (ctx->service->limit_rate <= 0) {
  282. // unlimited
  283. } else {
  284. sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate;
  285. }
  286. if (sleep_ms_per_send == 0) sleep_ms_per_send = 1;
  287. int sleep_ms = sleep_ms_per_send;
  288. auto start_time = std::chrono::steady_clock::now();
  289. auto end_time = start_time;
  290. while (total_readbytes < filesize) {
  291. if (!ctx->writer->isConnected()) {
  292. break;
  293. }
  294. if (!ctx->writer->isWriteComplete()) {
  295. hv_delay(1);
  296. continue;
  297. }
  298. size_t readbytes = file.read(buf, len);
  299. if (readbytes <= 0) {
  300. // read file error!
  301. ctx->writer->close();
  302. break;
  303. }
  304. int nwrite = ctx->writer->WriteBody(buf, readbytes);
  305. if (nwrite < 0) {
  306. // disconnected!
  307. break;
  308. }
  309. total_readbytes += readbytes;
  310. int cur_progress = total_readbytes * 100 / filesize;
  311. if (cur_progress > last_progress) {
  312. // printf("<< %s progress: %ld/%ld = %d%%\n",
  313. // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress);
  314. last_progress = cur_progress;
  315. }
  316. end_time += std::chrono::milliseconds(sleep_ms);
  317. std::this_thread::sleep_until(end_time);
  318. }
  319. ctx->writer->End();
  320. SAFE_FREE(buf);
  321. // auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
  322. // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count());
  323. }).detach();
  324. return HTTP_STATUS_UNFINISHED;
  325. }
  326. int Handler::sse(const HttpContextPtr& ctx) {
  327. ctx->writer->EndHeaders("Content-Type", "text/event-stream");
  328. // send(message) every 1s
  329. hv::setInterval(1000, [ctx](hv::TimerID timerID) {
  330. char szTime[DATETIME_FMT_BUFLEN] = {0};
  331. datetime_t now = datetime_now();
  332. datetime_fmt(&now, szTime);
  333. // @test html/EventSource.html EventSource.onmessage
  334. std::string msg("event: message\n");
  335. msg += "data: ";
  336. msg += szTime;
  337. msg += "\n\n";
  338. ctx->writer->write(msg);
  339. });
  340. return HTTP_STATUS_UNFINISHED;
  341. }