httplib.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2012 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPSLIB_H_
  8. #define _CPPHTTPLIB_HTTPSLIB_H_
  9. #ifdef _MSC_VER
  10. #define _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_NONSTDC_NO_DEPRECATE
  12. #ifndef SO_SYNCHRONOUS_NONALERT
  13. #define SO_SYNCHRONOUS_NONALERT 0x20;
  14. #endif
  15. #ifndef SO_OPENTYPE
  16. #define SO_OPENTYPE 0x7008
  17. #endif
  18. #ifndef snprintf
  19. #define snprintf _snprintf_s
  20. #endif
  21. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  22. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  23. #include <fcntl.h>
  24. #include <io.h>
  25. #include <winsock2.h>
  26. #include <ws2tcpip.h>
  27. #undef min
  28. #undef max
  29. typedef SOCKET socket_t;
  30. #else
  31. #include <pthread.h>
  32. #include <unistd.h>
  33. #include <netdb.h>
  34. #include <cstring>
  35. #include <netinet/in.h>
  36. #include <arpa/inet.h>
  37. #include <sys/socket.h>
  38. typedef int socket_t;
  39. #endif
  40. #include <fstream>
  41. #include <functional>
  42. #include <map>
  43. #include <memory>
  44. #include <regex>
  45. #include <string>
  46. #include <sys/stat.h>
  47. #include <assert.h>
  48. namespace httplib
  49. {
  50. typedef std::map<std::string, std::string> Map;
  51. typedef std::multimap<std::string, std::string> MultiMap;
  52. typedef std::smatch Match;
  53. struct Request {
  54. std::string method;
  55. std::string url;
  56. MultiMap headers;
  57. std::string body;
  58. Map params;
  59. Match matches;
  60. bool has_header(const char* key) const;
  61. std::string get_header_value(const char* key) const;
  62. void set_header(const char* key, const char* val);
  63. bool has_param(const char* key) const;
  64. };
  65. struct Response {
  66. int status;
  67. MultiMap headers;
  68. std::string body;
  69. bool has_header(const char* key) const;
  70. std::string get_header_value(const char* key) const;
  71. void set_header(const char* key, const char* val);
  72. void set_redirect(const char* url);
  73. void set_content(const std::string& s, const char* content_type);
  74. Response() : status(-1) {}
  75. };
  76. class Server {
  77. public:
  78. typedef std::function<void (const Request&, Response&)> Handler;
  79. typedef std::function<void (const Request&, const Response&)> Logger;
  80. Server();
  81. void get(const char* pattern, Handler handler);
  82. void post(const char* pattern, Handler handler);
  83. bool set_base_dir(const char* path);
  84. void set_error_handler(Handler handler);
  85. void set_logger(Logger logger);
  86. bool listen(const char* host, int port);
  87. void stop();
  88. private:
  89. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  90. void process_request(FILE* fp_read, FILE* fp_write);
  91. bool read_request_line(FILE* fp, Request& req);
  92. bool routing(Request& req, Response& res);
  93. bool handle_file_request(Request& req, Response& res);
  94. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  95. socket_t svr_sock_;
  96. std::string base_dir_;
  97. Handlers get_handlers_;
  98. Handlers post_handlers_;
  99. Handler error_handler_;
  100. Logger logger_;
  101. };
  102. class Client {
  103. public:
  104. Client(const char* host, int port);
  105. std::shared_ptr<Response> get(const char* url);
  106. std::shared_ptr<Response> head(const char* url);
  107. std::shared_ptr<Response> post(const char* url, const std::string& body, const char* content_type);
  108. std::shared_ptr<Response> post(const char* url, const Map& params);
  109. bool send(const Request& req, Response& res);
  110. private:
  111. bool read_response_line(FILE* fp, Response& res);
  112. const std::string host_;
  113. const int port_;
  114. };
  115. // Implementation
  116. namespace detail {
  117. template <class Fn>
  118. void split(const char* b, const char* e, char d, Fn fn)
  119. {
  120. int i = 0;
  121. int beg = 0;
  122. while (e ? (b + i != e) : (b[i] != '\0')) {
  123. if (b[i] == d) {
  124. fn(&b[beg], &b[i]);
  125. beg = i + 1;
  126. }
  127. i++;
  128. }
  129. if (i) {
  130. fn(&b[beg], &b[i]);
  131. }
  132. }
  133. template <typename T>
  134. inline bool read_and_close_socket(socket_t sock, T callback)
  135. {
  136. FILE* fp_read;
  137. FILE* fp_write;
  138. #ifdef _MSC_VER
  139. int osfhandle = _open_osfhandle(sock, _O_RDONLY);
  140. fp_read = _fdopen(osfhandle, "rb");
  141. fp_write = _fdopen(osfhandle, "wb");
  142. #else
  143. fp_read = fdopen(sock, "rb");
  144. fp_write = fdopen(sock, "wb");
  145. #endif
  146. auto ret = callback(fp_read, fp_write);
  147. #ifdef _MSC_VER
  148. sock = osfhandle;
  149. #else
  150. fclose(fp_read);
  151. fclose(fp_write);
  152. #endif
  153. return ret;
  154. }
  155. inline int shutdown_socket(socket_t sock)
  156. {
  157. #ifdef _MSC_VER
  158. return shutdown(sock, SD_BOTH);
  159. #else
  160. return shutdown(sock, SHUT_RDWR);
  161. #endif
  162. }
  163. inline int close_socket(socket_t sock)
  164. {
  165. #ifdef _MSC_VER
  166. return closesocket(sock);
  167. #else
  168. return close(sock);
  169. #endif
  170. }
  171. template <typename Fn>
  172. socket_t create_socket(const char* host, int port, Fn fn)
  173. {
  174. #ifdef _MSC_VER
  175. int opt = SO_SYNCHRONOUS_NONALERT;
  176. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  177. #endif
  178. // Get address info
  179. struct addrinfo hints;
  180. struct addrinfo *result;
  181. memset(&hints, 0, sizeof(struct addrinfo));
  182. hints.ai_family = AF_UNSPEC;
  183. hints.ai_socktype = SOCK_STREAM;
  184. hints.ai_flags = 0;
  185. hints.ai_protocol = 0;
  186. auto service = std::to_string(port);
  187. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  188. return -1;
  189. }
  190. for (auto rp = result; rp; rp = rp->ai_next) {
  191. // Create a socket
  192. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  193. if (sock == -1) {
  194. continue;
  195. }
  196. // Make 'reuse address' option available
  197. int yes = 1;
  198. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  199. // bind or connect
  200. if (fn(sock, *rp)) {
  201. freeaddrinfo(result);
  202. return sock;
  203. }
  204. close_socket(sock);
  205. }
  206. freeaddrinfo(result);
  207. return -1;
  208. }
  209. inline socket_t create_server_socket(const char* host, int port)
  210. {
  211. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  212. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  213. return false;
  214. }
  215. if (listen(sock, 5)) { // Listen through 5 channels
  216. return false;
  217. }
  218. return true;
  219. });
  220. }
  221. inline socket_t create_client_socket(const char* host, int port)
  222. {
  223. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  224. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  225. return false;
  226. }
  227. return true;
  228. });
  229. }
  230. inline bool is_file(const std::string& s)
  231. {
  232. struct stat st;
  233. return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  234. }
  235. inline bool is_dir(const std::string& s)
  236. {
  237. struct stat st;
  238. return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  239. }
  240. inline void read_file(const std::string& path, std::string& out)
  241. {
  242. auto fs = std::ifstream(path, std::ios_base::binary);
  243. fs.seekg(0, std::ios_base::end);
  244. auto size = fs.tellg();
  245. fs.seekg(0);
  246. out.resize(size);
  247. fs.read(&out[0], size);
  248. }
  249. inline std::string get_file_extention(const std::string& path)
  250. {
  251. std::smatch m;
  252. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  253. auto ret = std::regex_search(path, m, pat);
  254. std::string content_type;
  255. if (ret) {
  256. return m[1].str();
  257. }
  258. return std::string();
  259. }
  260. inline const char* get_content_type_from_file_extention(const std::string& ext)
  261. {
  262. if (ext == "html") {
  263. return "text/html";
  264. }
  265. return "text/plain";
  266. }
  267. inline const char* status_message(int status)
  268. {
  269. switch (status) {
  270. case 200: return "OK";
  271. case 400: return "Bad Request";
  272. case 404: return "Not Found";
  273. default:
  274. case 500: return "Internal Server Error";
  275. }
  276. }
  277. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  278. {
  279. auto it = map.find(key);
  280. if (it != map.end()) {
  281. return it->second.c_str();
  282. }
  283. return def;
  284. }
  285. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  286. {
  287. auto it = map.find(key);
  288. if (it != map.end()) {
  289. return std::stoi(it->second);
  290. }
  291. return def;
  292. }
  293. inline bool read_headers(FILE* fp, MultiMap& headers)
  294. {
  295. static std::regex re("(.+?): (.+?)\r\n");
  296. const auto BUFSIZ_HEADER = 2048;
  297. char buf[BUFSIZ_HEADER];
  298. for (;;) {
  299. if (!fgets(buf, BUFSIZ_HEADER, fp)) {
  300. return false;
  301. }
  302. if (!strcmp(buf, "\r\n")) {
  303. break;
  304. }
  305. std::cmatch m;
  306. if (std::regex_match(buf, m, re)) {
  307. auto key = std::string(m[1]);
  308. auto val = std::string(m[2]);
  309. headers.insert(std::make_pair(key, val));
  310. }
  311. }
  312. return true;
  313. }
  314. template <typename T>
  315. bool read_content(T& x, FILE* fp)
  316. {
  317. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  318. if (len) {
  319. x.body.assign(len, 0);
  320. if (!fread(&x.body[0], x.body.size(), 1, fp)) {
  321. return false;
  322. }
  323. }
  324. return true;
  325. }
  326. template <typename T>
  327. inline void write_headers(FILE* fp, const T& res)
  328. {
  329. fprintf(fp, "Connection: close\r\n");
  330. for (const auto& x: res.headers) {
  331. if (x.first != "Content-Type" && x.first != "Content-Length") {
  332. fprintf(fp, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  333. }
  334. }
  335. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  336. fprintf(fp, "Content-Type: %s\r\n", t);
  337. fprintf(fp, "Content-Length: %ld\r\n", res.body.size());
  338. fprintf(fp, "\r\n");
  339. }
  340. inline void write_response(FILE* fp, const Request& req, const Response& res)
  341. {
  342. fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  343. write_headers(fp, res);
  344. if (!res.body.empty() && req.method != "HEAD") {
  345. fprintf(fp, "%s", res.body.c_str());
  346. }
  347. }
  348. inline std::string encode_url(const std::string& s)
  349. {
  350. std::string result;
  351. for (auto i = 0; s[i]; i++) {
  352. switch (s[i]) {
  353. case ' ': result += "+"; break;
  354. case '\'': result += "%27"; break;
  355. case ',': result += "%2C"; break;
  356. case ':': result += "%3A"; break;
  357. case ';': result += "%3B"; break;
  358. default:
  359. if (s[i] < 0) {
  360. result += '%';
  361. char hex[4];
  362. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  363. assert(len == 2);
  364. result.append(hex, len);
  365. } else {
  366. result += s[i];
  367. }
  368. break;
  369. }
  370. }
  371. return result;
  372. }
  373. inline bool is_hex(char c, int& v)
  374. {
  375. if (0x20 <= c && isdigit(c)) {
  376. v = c - '0';
  377. return true;
  378. } else if ('A' <= c && c <= 'F') {
  379. v = c - 'A' + 10;
  380. return true;
  381. } else if ('a' <= c && c <= 'f') {
  382. v = c - 'a' + 10;
  383. return true;
  384. }
  385. return false;
  386. }
  387. inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  388. {
  389. val = 0;
  390. for (; s[i] && cnt; i++, cnt--) {
  391. int v = 0;
  392. if (is_hex(s[i], v)) {
  393. val = val * 16 + v;
  394. } else {
  395. break;
  396. }
  397. }
  398. return --i;
  399. }
  400. inline size_t to_utf8(int code, char* buff)
  401. {
  402. if (code < 0x0080) {
  403. buff[0] = (code & 0x7F);
  404. return 1;
  405. } else if (code < 0x0800) {
  406. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  407. buff[1] = (0x80 | (code & 0x3F));
  408. return 2;
  409. } else if (code < 0xD800) {
  410. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  411. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  412. buff[2] = (0x80 | (code & 0x3F));
  413. return 3;
  414. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  415. return 0;
  416. } else if (code < 0x10000) {
  417. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  418. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  419. buff[2] = (0x80 | (code & 0x3F));
  420. return 3;
  421. } else if (code < 0x110000) {
  422. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  423. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  424. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  425. buff[3] = (0x80 | (code & 0x3F));
  426. return 4;
  427. }
  428. // NOTREACHED
  429. return 0;
  430. }
  431. inline std::string decode_url(const std::string& s)
  432. {
  433. std::string result;
  434. for (int i = 0; s[i]; i++) {
  435. if (s[i] == '%') {
  436. i++;
  437. assert(s[i]);
  438. if (s[i] == '%') {
  439. result += s[i];
  440. } else if (s[i] == 'u') {
  441. // Unicode
  442. i++;
  443. assert(s[i]);
  444. int val = 0;
  445. i = from_hex_to_i(s, i, 4, val);
  446. char buff[4];
  447. size_t len = to_utf8(val, buff);
  448. if (len > 0) {
  449. result.append(buff, len);
  450. }
  451. } else {
  452. // HEX
  453. int val = 0;
  454. i = from_hex_to_i(s, i, 2, val);
  455. result += val;
  456. }
  457. } else if (s[i] == '+') {
  458. result += ' ';
  459. } else {
  460. result += s[i];
  461. }
  462. }
  463. return result;
  464. }
  465. inline void write_request(FILE* fp, const Request& req)
  466. {
  467. auto url = encode_url(req.url);
  468. fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), url.c_str());
  469. write_headers(fp, req);
  470. if (!req.body.empty()) {
  471. if (req.has_header("application/x-www-form-urlencoded")) {
  472. fprintf(fp, "%s", encode_url(req.body).c_str());
  473. } else {
  474. fprintf(fp, "%s", req.body.c_str());
  475. }
  476. }
  477. }
  478. inline void parse_query_text(const std::string& s, Map& params)
  479. {
  480. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  481. std::string key;
  482. std::string val;
  483. split(b, e, '=', [&](const char* b, const char* e) {
  484. if (key.empty()) {
  485. key.assign(b, e);
  486. } else {
  487. val.assign(b, e);
  488. }
  489. });
  490. params[key] = detail::decode_url(val);
  491. });
  492. }
  493. #ifdef _MSC_VER
  494. class WSInit {
  495. public:
  496. WSInit::WSInit() {
  497. WSADATA wsaData;
  498. WSAStartup(0x0002, &wsaData);
  499. }
  500. WSInit::~WSInit() {
  501. WSACleanup();
  502. }
  503. };
  504. static WSInit wsinit_;
  505. #endif
  506. } // namespace detail
  507. // Request implementation
  508. inline bool Request::has_header(const char* key) const
  509. {
  510. return headers.find(key) != headers.end();
  511. }
  512. inline std::string Request::get_header_value(const char* key) const
  513. {
  514. return detail::get_header_value(headers, key, "");
  515. }
  516. inline void Request::set_header(const char* key, const char* val)
  517. {
  518. headers.insert(std::make_pair(key, val));
  519. }
  520. inline bool Request::has_param(const char* key) const
  521. {
  522. return params.find(key) != params.end();
  523. }
  524. // Response implementation
  525. inline bool Response::has_header(const char* key) const
  526. {
  527. return headers.find(key) != headers.end();
  528. }
  529. inline std::string Response::get_header_value(const char* key) const
  530. {
  531. return detail::get_header_value(headers, key, "");
  532. }
  533. inline void Response::set_header(const char* key, const char* val)
  534. {
  535. headers.insert(std::make_pair(key, val));
  536. }
  537. inline void Response::set_redirect(const char* url)
  538. {
  539. set_header("Location", url);
  540. status = 302;
  541. }
  542. inline void Response::set_content(const std::string& s, const char* content_type)
  543. {
  544. body = s;
  545. set_header("Content-Type", content_type);
  546. }
  547. // HTTP server implementation
  548. inline Server::Server()
  549. : svr_sock_(-1)
  550. {
  551. }
  552. inline void Server::get(const char* pattern, Handler handler)
  553. {
  554. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  555. }
  556. inline void Server::post(const char* pattern, Handler handler)
  557. {
  558. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  559. }
  560. inline bool Server::set_base_dir(const char* path)
  561. {
  562. if (detail::is_dir(path)) {
  563. base_dir_ = path;
  564. return true;
  565. }
  566. return false;
  567. }
  568. inline void Server::set_error_handler(Handler handler)
  569. {
  570. error_handler_ = handler;
  571. }
  572. inline void Server::set_logger(Logger logger)
  573. {
  574. logger_ = logger;
  575. }
  576. inline bool Server::listen(const char* host, int port)
  577. {
  578. svr_sock_ = detail::create_server_socket(host, port);
  579. if (svr_sock_ == -1) {
  580. return false;
  581. }
  582. auto ret = true;
  583. for (;;) {
  584. socket_t sock = accept(svr_sock_, NULL, NULL);
  585. if (sock == -1) {
  586. if (svr_sock_ != -1) {
  587. detail::close_socket(svr_sock_);
  588. ret = false;
  589. } else {
  590. ; // The server socket was closed by user.
  591. }
  592. break;
  593. }
  594. // TODO: should be async
  595. detail::read_and_close_socket(sock, [this](FILE* fp_read, FILE* fp_write) {
  596. process_request(fp_read, fp_write);
  597. return true;
  598. });
  599. }
  600. return ret;
  601. }
  602. inline void Server::stop()
  603. {
  604. detail::shutdown_socket(svr_sock_);
  605. detail::close_socket(svr_sock_);
  606. svr_sock_ = -1;
  607. }
  608. inline bool Server::read_request_line(FILE* fp, Request& req)
  609. {
  610. const auto BUFSIZ_REQUESTLINE = 2048;
  611. char buf[BUFSIZ_REQUESTLINE];
  612. if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
  613. return false;
  614. }
  615. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  616. std::cmatch m;
  617. if (std::regex_match(buf, m, re)) {
  618. req.method = std::string(m[1]);
  619. req.url = detail::decode_url(m[2]);
  620. // Parse query text
  621. auto len = std::distance(m[3].first, m[3].second);
  622. if (len > 0) {
  623. detail::parse_query_text(m[3], req.params);
  624. }
  625. return true;
  626. }
  627. return false;
  628. }
  629. inline bool Server::handle_file_request(Request& req, Response& res)
  630. {
  631. if (!base_dir_.empty()) {
  632. std::string path = base_dir_ + req.url;
  633. if (!path.empty() && path.back() == '/') {
  634. path += "index.html";
  635. }
  636. if (detail::is_file(path)) {
  637. detail::read_file(path, res.body);
  638. res.set_header("Content-Type",
  639. detail::get_content_type_from_file_extention(
  640. detail::get_file_extention(path)));
  641. res.status = 200;
  642. return true;
  643. }
  644. }
  645. return false;
  646. }
  647. inline bool Server::routing(Request& req, Response& res)
  648. {
  649. if (req.method == "GET" && handle_file_request(req, res)) {
  650. return true;
  651. }
  652. if (req.method == "GET" || req.method == "HEAD") {
  653. return dispatch_request(req, res, get_handlers_);
  654. } else if (req.method == "POST") {
  655. return dispatch_request(req, res, post_handlers_);
  656. }
  657. return false;
  658. }
  659. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  660. {
  661. for (const auto& x: handlers) {
  662. const auto& pattern = x.first;
  663. const auto& handler = x.second;
  664. if (std::regex_match(req.url, req.matches, pattern)) {
  665. handler(req, res);
  666. return true;
  667. }
  668. }
  669. return false;
  670. }
  671. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  672. {
  673. Request req;
  674. Response res;
  675. if (!read_request_line(fp_read, req) ||
  676. !detail::read_headers(fp_read, req.headers)) {
  677. return;
  678. }
  679. if (req.method == "POST") {
  680. if (!detail::read_content(req, fp_read)) {
  681. return;
  682. }
  683. static std::string type = "application/x-www-form-urlencoded";
  684. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  685. detail::parse_query_text(req.body, req.params);
  686. }
  687. }
  688. if (routing(req, res)) {
  689. if (res.status == -1) {
  690. res.status = 200;
  691. }
  692. } else {
  693. res.status = 404;
  694. }
  695. assert(res.status != -1);
  696. if (400 <= res.status && error_handler_) {
  697. error_handler_(req, res);
  698. }
  699. detail::write_response(fp_write, req, res);
  700. fflush(fp_write);
  701. if (logger_) {
  702. logger_(req, res);
  703. }
  704. }
  705. // HTTP client implementation
  706. inline Client::Client(const char* host, int port)
  707. : host_(host)
  708. , port_(port)
  709. {
  710. }
  711. inline bool Client::read_response_line(FILE* fp, Response& res)
  712. {
  713. const auto BUFSIZ_RESPONSELINE = 2048;
  714. char buf[BUFSIZ_RESPONSELINE];
  715. if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
  716. return false;
  717. }
  718. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  719. std::cmatch m;
  720. if (std::regex_match(buf, m, re)) {
  721. res.status = std::stoi(std::string(m[1]));
  722. }
  723. return true;
  724. }
  725. inline bool Client::send(const Request& req, Response& res)
  726. {
  727. auto sock = detail::create_client_socket(host_.c_str(), port_);
  728. if (sock == -1) {
  729. return false;
  730. }
  731. return detail::read_and_close_socket(sock, [&](FILE* fp_read, FILE* fp_write) {
  732. // Send request
  733. detail::write_request(fp_write, req);
  734. fflush(fp_write);
  735. // Receive response
  736. if (!read_response_line(fp_read, res) ||
  737. !detail::read_headers(fp_read, res.headers)) {
  738. return false;
  739. }
  740. if (req.method != "HEAD") {
  741. if (!detail::read_content(res, fp_read)) {
  742. return false;
  743. }
  744. }
  745. return true;
  746. });
  747. }
  748. inline std::shared_ptr<Response> Client::get(const char* url)
  749. {
  750. Request req;
  751. req.method = "GET";
  752. req.url = url;
  753. auto res = std::make_shared<Response>();
  754. return send(req, *res) ? res : nullptr;
  755. }
  756. inline std::shared_ptr<Response> Client::head(const char* url)
  757. {
  758. Request req;
  759. req.method = "HEAD";
  760. req.url = url;
  761. auto res = std::make_shared<Response>();
  762. return send(req, *res) ? res : nullptr;
  763. }
  764. inline std::shared_ptr<Response> Client::post(
  765. const char* url, const std::string& body, const char* content_type)
  766. {
  767. Request req;
  768. req.method = "POST";
  769. req.url = url;
  770. req.set_header("Content-Type", content_type);
  771. req.body = body;
  772. auto res = std::make_shared<Response>();
  773. return send(req, *res) ? res : nullptr;
  774. }
  775. inline std::shared_ptr<Response> Client::post(
  776. const char* url, const Map& params)
  777. {
  778. std::string query;
  779. for (auto it = params.begin(); it != params.end(); ++it) {
  780. if (it != params.begin()) {
  781. query += "&";
  782. }
  783. query += it->first;
  784. query += "=";
  785. query += it->second;
  786. }
  787. return post(url, query, "application/x-www-form-urlencoded");
  788. }
  789. } // namespace httplib
  790. #endif
  791. // vim: et ts=4 sw=4 cin cino={1s ff=unix