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