handler.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #ifndef HV_HTTPD_HANDLER_H
  2. #define HV_HTTPD_HANDLER_H
  3. #include "HttpMessage.h"
  4. #include "HttpResponseWriter.h"
  5. #include "htime.h"
  6. #include "EventLoop.h" // import setTimeout, setInterval
  7. class Handler {
  8. public:
  9. // preprocessor => api_handlers => postprocessor
  10. static int preprocessor(HttpRequest* req, HttpResponse* resp) {
  11. // printf("%s:%d\n", req->client_addr.ip.c_str(), req->client_addr.port);
  12. // printf("%s\n", req->Dump(true, true).c_str());
  13. // if (req->content_type != APPLICATION_JSON) {
  14. // return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  15. // }
  16. req->ParseBody();
  17. resp->content_type = APPLICATION_JSON;
  18. #if 0
  19. // authentication sample code
  20. if (strcmp(req->path.c_str(), "/login") != 0) {
  21. string token = req->GetHeader("token");
  22. if (token.empty()) {
  23. response_status(resp, 10011, "Miss token");
  24. return HTTP_STATUS_UNAUTHORIZED;
  25. }
  26. else if (strcmp(token.c_str(), "abcdefg") != 0) {
  27. response_status(resp, 10012, "Token wrong");
  28. return HTTP_STATUS_UNAUTHORIZED;
  29. }
  30. return 0;
  31. }
  32. #endif
  33. return 0;
  34. }
  35. static int postprocessor(HttpRequest* req, HttpResponse* resp) {
  36. // printf("%s\n", resp->Dump(true, true).c_str());
  37. return 0;
  38. }
  39. static int sleep(HttpRequest* req, HttpResponse* resp) {
  40. resp->Set("start_ms", gettimeofday_ms());
  41. std::string strTime = req->GetParam("t");
  42. if (!strTime.empty()) {
  43. int ms = atoi(strTime.c_str());
  44. if (ms > 0) {
  45. hv_delay(ms);
  46. }
  47. }
  48. resp->Set("end_ms", gettimeofday_ms());
  49. response_status(resp, 0, "OK");
  50. return 200;
  51. }
  52. static void setTimeout(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
  53. writer->response->Set("start_ms", gettimeofday_ms());
  54. std::string strTime = req->GetParam("t");
  55. if (!strTime.empty()) {
  56. int ms = atoi(strTime.c_str());
  57. if (ms > 0) {
  58. hv::setTimeout(ms, [writer](hv::TimerID timerID){
  59. writer->Begin();
  60. HttpResponse* resp = writer->response.get();
  61. resp->Set("end_ms", gettimeofday_ms());
  62. response_status(resp, 0, "OK");
  63. writer->End();
  64. });
  65. }
  66. }
  67. }
  68. static int query(HttpRequest* req, HttpResponse* resp) {
  69. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  70. // ?query => HttpRequest::query_params
  71. for (auto& param : req->query_params) {
  72. resp->Set(param.first.c_str(), param.second);
  73. }
  74. response_status(resp, 0, "OK");
  75. return 200;
  76. }
  77. static int kv(HttpRequest* req, HttpResponse* resp) {
  78. if (req->content_type != APPLICATION_URLENCODED) {
  79. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  80. }
  81. resp->content_type = APPLICATION_URLENCODED;
  82. resp->kv = req->kv;
  83. resp->kv["int"] = hv::to_string(123);
  84. resp->kv["float"] = hv::to_string(3.14);
  85. resp->kv["string"] = "hello";
  86. return 200;
  87. }
  88. static int json(HttpRequest* req, HttpResponse* resp) {
  89. if (req->content_type != APPLICATION_JSON) {
  90. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  91. }
  92. resp->content_type = APPLICATION_JSON;
  93. resp->json = req->json;
  94. resp->json["int"] = 123;
  95. resp->json["float"] = 3.14;
  96. resp->json["string"] = "hello";
  97. return 200;
  98. }
  99. static int form(HttpRequest* req, HttpResponse* resp) {
  100. if (req->content_type != MULTIPART_FORM_DATA) {
  101. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  102. }
  103. resp->content_type = MULTIPART_FORM_DATA;
  104. resp->form = req->form;
  105. resp->form["int"] = 123;
  106. resp->form["float"] = 3.14;
  107. resp->form["string"] = "hello";
  108. // resp->form["file"] = FormData(NULL, "test.jpg");
  109. // resp->UploadFormFile("file", "test.jpg");
  110. return 200;
  111. }
  112. static int test(HttpRequest* req, HttpResponse* resp) {
  113. // bool b = req->Get<bool>("bool");
  114. // int64_t n = req->Get<int64_t>("int");
  115. // double f = req->Get<double>("float");
  116. bool b = req->GetBool("bool");
  117. int64_t n = req->GetInt("int");
  118. double f = req->GetFloat("float");
  119. string str = req->GetString("string");
  120. resp->content_type = req->content_type;
  121. resp->Set("bool", b);
  122. resp->Set("int", n);
  123. resp->Set("float", f);
  124. resp->Set("string", str);
  125. response_status(resp, 0, "OK");
  126. return 200;
  127. }
  128. static int grpc(HttpRequest* req, HttpResponse* resp) {
  129. if (req->content_type != APPLICATION_GRPC) {
  130. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  131. }
  132. // parse protobuf
  133. // ParseFromString(req->body);
  134. // resp->content_type = APPLICATION_GRPC;
  135. // serailize protobuf
  136. // resp->body = SerializeAsString(xxx);
  137. response_status(resp, 0, "OK");
  138. return 200;
  139. }
  140. static int restful(HttpRequest* req, HttpResponse* resp) {
  141. // RESTful /:field/ => HttpRequest::query_params
  142. // path=/group/:group_name/user/:user_id
  143. // string group_name = req->GetParam("group_name");
  144. // string user_id = req->GetParam("user_id");
  145. for (auto& param : req->query_params) {
  146. resp->Set(param.first.c_str(), param.second);
  147. }
  148. response_status(resp, 0, "OK");
  149. return 200;
  150. }
  151. static int login(HttpRequest* req, HttpResponse* resp) {
  152. string username = req->GetString("username");
  153. string password = req->GetString("password");
  154. if (username.empty() || password.empty()) {
  155. response_status(resp, 10001, "Miss username or password");
  156. return HTTP_STATUS_BAD_REQUEST;
  157. }
  158. else if (strcmp(username.c_str(), "admin") != 0) {
  159. response_status(resp, 10002, "Username not exist");
  160. return HTTP_STATUS_BAD_REQUEST;
  161. }
  162. else if (strcmp(password.c_str(), "123456") != 0) {
  163. response_status(resp, 10003, "Password wrong");
  164. return HTTP_STATUS_BAD_REQUEST;
  165. }
  166. else {
  167. resp->Set("token", "abcdefg");
  168. response_status(resp, 0, "OK");
  169. return HTTP_STATUS_OK;
  170. }
  171. }
  172. static int upload(HttpRequest* req, HttpResponse* resp) {
  173. // return resp->SaveFormFile("file", "html/uploads/test.jpg");
  174. if (req->content_type != MULTIPART_FORM_DATA) {
  175. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  176. }
  177. FormData file = req->form["file"];
  178. if (file.content.empty()) {
  179. return response_status(resp, HTTP_STATUS_BAD_REQUEST);
  180. }
  181. string filepath("html/uploads/");
  182. filepath += file.filename;
  183. FILE* fp = fopen(filepath.c_str(), "wb");
  184. if (fp) {
  185. fwrite(file.content.data(), 1, file.content.size(), fp);
  186. fclose(fp);
  187. }
  188. response_status(resp, 0, "OK");
  189. return 200;
  190. }
  191. private:
  192. static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) {
  193. resp->Set("code", code);
  194. if (message == NULL) message = http_status_str((enum http_status)code);
  195. resp->Set("message", message);
  196. resp->DumpBody();
  197. return code;
  198. }
  199. };
  200. #endif // HV_HTTPD_HANDLER_H