1
0

handler.cpp 12 KB

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