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. typedef SOCKET socket_t;
  28. #else
  29. #include <pthread.h>
  30. #include <unistd.h>
  31. #include <netdb.h>
  32. #include <cstring>
  33. #include <netinet/in.h>
  34. #include <arpa/inet.h>
  35. #include <sys/socket.h>
  36. typedef int socket_t;
  37. #endif
  38. #include <fstream>
  39. #include <functional>
  40. #include <map>
  41. #include <memory>
  42. #include <regex>
  43. #include <string>
  44. #include <sys/stat.h>
  45. #include <assert.h>
  46. namespace httplib
  47. {
  48. typedef std::map<std::string, std::string> Map;
  49. typedef std::multimap<std::string, std::string> MultiMap;
  50. typedef std::smatch Match;
  51. struct Request {
  52. std::string method;
  53. std::string url;
  54. MultiMap headers;
  55. std::string body;
  56. Map params;
  57. Match matches;
  58. bool has_header(const char* key) const;
  59. std::string get_header_value(const char* key) const;
  60. void set_header(const char* key, const char* val);
  61. bool has_param(const char* key) const;
  62. };
  63. struct Response {
  64. int status;
  65. MultiMap headers;
  66. std::string body;
  67. bool has_header(const char* key) const;
  68. std::string get_header_value(const char* key) const;
  69. void set_header(const char* key, const char* val);
  70. void set_redirect(const char* url);
  71. void set_content(const std::string& s, const char* content_type);
  72. Response() : status(-1) {}
  73. };
  74. class Server {
  75. public:
  76. typedef std::function<void (const Request&, Response&)> Handler;
  77. typedef std::function<void (const Request&, const Response&)> Logger;
  78. Server();
  79. void get(const char* pattern, Handler handler);
  80. void post(const char* pattern, Handler handler);
  81. bool set_base_dir(const char* path);
  82. void set_error_handler(Handler handler);
  83. void set_logger(Logger logger);
  84. bool listen(const char* host, int port);
  85. void stop();
  86. private:
  87. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  88. void process_request(FILE* fp_read, FILE* fp_write);
  89. bool read_request_line(FILE* fp, Request& req);
  90. bool routing(Request& req, Response& res);
  91. bool handle_file_request(Request& req, Response& res);
  92. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  93. socket_t svr_sock_;
  94. std::string base_dir_;
  95. Handlers get_handlers_;
  96. Handlers post_handlers_;
  97. Handler error_handler_;
  98. Logger logger_;
  99. };
  100. class Client {
  101. public:
  102. Client(const char* host, int port);
  103. std::shared_ptr<Response> get(const char* url);
  104. std::shared_ptr<Response> head(const char* url);
  105. std::shared_ptr<Response> post(const char* url, const std::string& body, const char* content_type);
  106. std::shared_ptr<Response> post(const char* url, const Map& params);
  107. bool send(const Request& req, Response& res);
  108. private:
  109. bool read_response_line(FILE* fp, Response& res);
  110. const std::string host_;
  111. const int port_;
  112. };
  113. // Implementation
  114. namespace detail {
  115. template <class Fn>
  116. void split(const char* b, const char* e, char d, Fn fn)
  117. {
  118. int i = 0;
  119. int beg = 0;
  120. while (e ? (b + i != e) : (b[i] != '\0')) {
  121. if (b[i] == d) {
  122. fn(&b[beg], &b[i]);
  123. beg = i + 1;
  124. }
  125. i++;
  126. }
  127. if (i) {
  128. fn(&b[beg], &b[i]);
  129. }
  130. }
  131. template <typename T>
  132. inline bool read_and_close_socket(socket_t sock, T callback)
  133. {
  134. FILE* fp_read;
  135. FILE* fp_write;
  136. #ifdef _MSC_VER
  137. int osfhandle = _open_osfhandle(sock, _O_RDONLY);
  138. fp_read = _fdopen(osfhandle, "rb");
  139. fp_write = _fdopen(osfhandle, "wb");
  140. #else
  141. fp_read = fdopen(sock, "rb");
  142. fp_write = fdopen(sock, "wb");
  143. #endif
  144. auto ret = callback(fp_read, fp_write);
  145. #ifdef _MSC_VER
  146. sock = osfhandle;
  147. #else
  148. fclose(fp_read);
  149. fclose(fp_write);
  150. #endif
  151. return ret;
  152. }
  153. inline int shutdown_socket(socket_t sock)
  154. {
  155. #ifdef _MSC_VER
  156. return shutdown(sock, SD_BOTH);
  157. #else
  158. return shutdown(sock, SHUT_RDWR);
  159. #endif
  160. }
  161. inline int close_socket(socket_t sock)
  162. {
  163. #ifdef _MSC_VER
  164. return closesocket(sock);
  165. #else
  166. return close(sock);
  167. #endif
  168. }
  169. template <typename Fn>
  170. socket_t create_socket(const char* host, int port, Fn fn)
  171. {
  172. #ifdef _MSC_VER
  173. int opt = SO_SYNCHRONOUS_NONALERT;
  174. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  175. #endif
  176. // Get address info
  177. struct addrinfo hints;
  178. struct addrinfo *result;
  179. memset(&hints, 0, sizeof(struct addrinfo));
  180. hints.ai_family = AF_UNSPEC;
  181. hints.ai_socktype = SOCK_STREAM;
  182. hints.ai_flags = 0;
  183. hints.ai_protocol = 0;
  184. auto service = std::to_string(port);
  185. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  186. return -1;
  187. }
  188. for (auto rp = result; rp; rp = rp->ai_next) {
  189. // Create a socket
  190. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  191. if (sock == -1) {
  192. continue;
  193. }
  194. // Make 'reuse address' option available
  195. int yes = 1;
  196. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  197. // bind or connect
  198. if (fn(sock, *rp)) {
  199. freeaddrinfo(result);
  200. return sock;
  201. }
  202. close_socket(sock);
  203. }
  204. freeaddrinfo(result);
  205. return -1;
  206. }
  207. inline socket_t create_server_socket(const char* host, int port)
  208. {
  209. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  210. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  211. return false;
  212. }
  213. if (listen(sock, 5)) { // Listen through 5 channels
  214. return false;
  215. }
  216. return true;
  217. });
  218. }
  219. inline socket_t create_client_socket(const char* host, int port)
  220. {
  221. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  222. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  223. return false;
  224. }
  225. return true;
  226. });
  227. }
  228. inline bool is_file(const std::string& s)
  229. {
  230. struct stat st;
  231. return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  232. }
  233. inline bool is_dir(const std::string& s)
  234. {
  235. struct stat st;
  236. return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  237. }
  238. inline void read_file(const std::string& path, std::string& out)
  239. {
  240. auto fs = std::ifstream(path, std::ios_base::binary);
  241. fs.seekg(0, std::ios_base::end);
  242. auto size = fs.tellg();
  243. fs.seekg(0);
  244. out.resize(size);
  245. fs.read(&out[0], size);
  246. }
  247. inline std::string get_file_extention(const std::string& path)
  248. {
  249. std::smatch m;
  250. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  251. auto ret = std::regex_search(path, m, pat);
  252. std::string content_type;
  253. if (ret) {
  254. return m[1].str();
  255. }
  256. return std::string();
  257. }
  258. inline const char* get_content_type_from_file_extention(const std::string& ext)
  259. {
  260. if (ext == "html") {
  261. return "text/html";
  262. }
  263. return "text/plain";
  264. }
  265. inline const char* status_message(int status)
  266. {
  267. switch (status) {
  268. case 200: return "OK";
  269. case 400: return "Bad Request";
  270. case 404: return "Not Found";
  271. default:
  272. case 500: return "Internal Server Error";
  273. }
  274. }
  275. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  276. {
  277. auto it = map.find(key);
  278. if (it != map.end()) {
  279. return it->second.c_str();
  280. }
  281. return def;
  282. }
  283. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  284. {
  285. auto it = map.find(key);
  286. if (it != map.end()) {
  287. return std::stoi(it->second);
  288. }
  289. return def;
  290. }
  291. inline bool read_headers(FILE* fp, MultiMap& headers)
  292. {
  293. static std::regex re("(.+?): (.+?)\r\n");
  294. const auto BUFSIZ_HEADER = 2048;
  295. char buf[BUFSIZ_HEADER];
  296. for (;;) {
  297. if (!fgets(buf, BUFSIZ_HEADER, fp)) {
  298. return false;
  299. }
  300. if (!strcmp(buf, "\r\n")) {
  301. break;
  302. }
  303. std::cmatch m;
  304. if (std::regex_match(buf, m, re)) {
  305. auto key = std::string(m[1]);
  306. auto val = std::string(m[2]);
  307. headers.insert(std::make_pair(key, val));
  308. }
  309. }
  310. return true;
  311. }
  312. template <typename T>
  313. bool read_content(T& x, FILE* fp)
  314. {
  315. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  316. if (len) {
  317. x.body.assign(len, 0);
  318. if (!fread(&x.body[0], x.body.size(), 1, fp)) {
  319. return false;
  320. }
  321. }
  322. return true;
  323. }
  324. template <typename T>
  325. inline void write_headers(FILE* fp, const T& res)
  326. {
  327. fprintf(fp, "Connection: close\r\n");
  328. for (const auto& x: res.headers) {
  329. if (x.first != "Content-Type" && x.first != "Content-Length") {
  330. fprintf(fp, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  331. }
  332. }
  333. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  334. fprintf(fp, "Content-Type: %s\r\n", t);
  335. if (!res.body.empty()) {
  336. fprintf(fp, "Content-Length: %ld\r\n", res.body.size());
  337. }
  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] = 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(detail::decode_url(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. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  684. detail::parse_query_text(detail::decode_url(req.body), req.params);
  685. }
  686. }
  687. if (routing(req, res)) {
  688. if (res.status == -1) {
  689. res.status = 200;
  690. }
  691. } else {
  692. res.status = 404;
  693. }
  694. assert(res.status != -1);
  695. if (400 <= res.status && error_handler_) {
  696. error_handler_(req, res);
  697. }
  698. detail::write_response(fp_write, req, res);
  699. fflush(fp_write);
  700. if (logger_) {
  701. logger_(req, res);
  702. }
  703. }
  704. // HTTP client implementation
  705. inline Client::Client(const char* host, int port)
  706. : host_(host)
  707. , port_(port)
  708. {
  709. }
  710. inline bool Client::read_response_line(FILE* fp, Response& res)
  711. {
  712. const auto BUFSIZ_RESPONSELINE = 2048;
  713. char buf[BUFSIZ_RESPONSELINE];
  714. if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
  715. return false;
  716. }
  717. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  718. std::cmatch m;
  719. if (std::regex_match(buf, m, re)) {
  720. res.status = std::stoi(std::string(m[1]));
  721. }
  722. return true;
  723. }
  724. inline bool Client::send(const Request& req, Response& res)
  725. {
  726. auto sock = detail::create_client_socket(host_.c_str(), port_);
  727. if (sock == -1) {
  728. return false;
  729. }
  730. return detail::read_and_close_socket(sock, [&](FILE* fp_read, FILE* fp_write) {
  731. // Send request
  732. detail::write_request(fp_write, req);
  733. fflush(fp_write);
  734. // Receive response
  735. if (!read_response_line(fp_read, res) ||
  736. !detail::read_headers(fp_read, res.headers)) {
  737. return false;
  738. }
  739. if (req.method != "HEAD") {
  740. if (!detail::read_content(res, fp_read)) {
  741. return false;
  742. }
  743. }
  744. return true;
  745. });
  746. }
  747. inline std::shared_ptr<Response> Client::get(const char* url)
  748. {
  749. Request req;
  750. req.method = "GET";
  751. req.url = url;
  752. auto res = std::make_shared<Response>();
  753. return send(req, *res) ? res : nullptr;
  754. }
  755. inline std::shared_ptr<Response> Client::head(const char* url)
  756. {
  757. Request req;
  758. req.method = "HEAD";
  759. req.url = url;
  760. auto res = std::make_shared<Response>();
  761. return send(req, *res) ? res : nullptr;
  762. }
  763. inline std::shared_ptr<Response> Client::post(
  764. const char* url, const std::string& body, const char* content_type)
  765. {
  766. Request req;
  767. req.method = "POST";
  768. req.url = url;
  769. req.set_header("Content-Type", content_type);
  770. req.body = body;
  771. auto res = std::make_shared<Response>();
  772. return send(req, *res) ? res : nullptr;
  773. }
  774. inline std::shared_ptr<Response> Client::post(
  775. const char* url, const Map& params)
  776. {
  777. std::string query;
  778. for (auto it = params.begin(); it != params.end(); ++it) {
  779. if (it != params.begin()) {
  780. query += "&";
  781. }
  782. query += it->first;
  783. query += "=";
  784. query += it->second;
  785. }
  786. return post(url, query, "application/x-www-form-urlencoded");
  787. }
  788. } // namespace httplib
  789. #endif
  790. // vim: et ts=4 sw=4 cin cino={1s ff=unix