httplib.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. if (!res.body.empty()) {
  338. fprintf(fp, "Content-Length: %ld\r\n", res.body.size());
  339. }
  340. fprintf(fp, "\r\n");
  341. }
  342. inline void write_response(FILE* fp, const Request& req, const Response& res)
  343. {
  344. fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  345. write_headers(fp, res);
  346. if (!res.body.empty() && req.method != "HEAD") {
  347. fprintf(fp, "%s", res.body.c_str());
  348. }
  349. }
  350. inline std::string encode_url(const std::string& s)
  351. {
  352. std::string result;
  353. for (auto i = 0; s[i]; i++) {
  354. switch (s[i]) {
  355. case ' ': result += "+"; break;
  356. case '\'': result += "%27"; break;
  357. case ',': result += "%2C"; break;
  358. case ':': result += "%3A"; break;
  359. case ';': result += "%3B"; break;
  360. default:
  361. if (s[i] < 0) {
  362. result += '%';
  363. char hex[4];
  364. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  365. assert(len == 2);
  366. result.append(hex, len);
  367. } else {
  368. result += s[i];
  369. }
  370. break;
  371. }
  372. }
  373. return result;
  374. }
  375. inline bool is_hex(char c, int& v)
  376. {
  377. if (0x20 <= c && isdigit(c)) {
  378. v = c - '0';
  379. return true;
  380. } else if ('A' <= c && c <= 'F') {
  381. v = c - 'A' + 10;
  382. return true;
  383. } else if ('a' <= c && c <= 'f') {
  384. v = c - 'a' + 10;
  385. return true;
  386. }
  387. return false;
  388. }
  389. inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  390. {
  391. val = 0;
  392. for (; s[i] && cnt; i++, cnt--) {
  393. int v = 0;
  394. if (is_hex(s[i], v)) {
  395. val = val * 16 + v;
  396. } else {
  397. break;
  398. }
  399. }
  400. return --i;
  401. }
  402. inline size_t to_utf8(int code, char* buff)
  403. {
  404. if (code < 0x0080) {
  405. buff[0] = (code & 0x7F);
  406. return 1;
  407. } else if (code < 0x0800) {
  408. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  409. buff[1] = (0x80 | (code & 0x3F));
  410. return 2;
  411. } else if (code < 0xD800) {
  412. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  413. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  414. buff[2] = (0x80 | (code & 0x3F));
  415. return 3;
  416. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  417. return 0;
  418. } else if (code < 0x10000) {
  419. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  420. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  421. buff[2] = (0x80 | (code & 0x3F));
  422. return 3;
  423. } else if (code < 0x110000) {
  424. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  425. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  426. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  427. buff[3] = (0x80 | (code & 0x3F));
  428. return 4;
  429. }
  430. // NOTREACHED
  431. return 0;
  432. }
  433. inline std::string decode_url(const std::string& s)
  434. {
  435. std::string result;
  436. for (int i = 0; s[i]; i++) {
  437. if (s[i] == '%') {
  438. i++;
  439. assert(s[i]);
  440. if (s[i] == '%') {
  441. result += s[i];
  442. } else if (s[i] == 'u') {
  443. // Unicode
  444. i++;
  445. assert(s[i]);
  446. int val = 0;
  447. i = from_hex_to_i(s, i, 4, val);
  448. char buff[4];
  449. size_t len = to_utf8(val, buff);
  450. if (len > 0) {
  451. result.append(buff, len);
  452. }
  453. } else {
  454. // HEX
  455. int val = 0;
  456. i = from_hex_to_i(s, i, 2, val);
  457. result += val;
  458. }
  459. } else if (s[i] == '+') {
  460. result += ' ';
  461. } else {
  462. result += s[i];
  463. }
  464. }
  465. return result;
  466. }
  467. inline void write_request(FILE* fp, const Request& req)
  468. {
  469. auto url = encode_url(req.url);
  470. fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), url.c_str());
  471. write_headers(fp, req);
  472. if (!req.body.empty()) {
  473. if (req.has_header("application/x-www-form-urlencoded")) {
  474. fprintf(fp, "%s", encode_url(req.body).c_str());
  475. } else {
  476. fprintf(fp, "%s", req.body.c_str());
  477. }
  478. }
  479. }
  480. inline void parse_query_text(const std::string& s, Map& params)
  481. {
  482. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  483. std::string key;
  484. std::string val;
  485. split(b, e, '=', [&](const char* b, const char* e) {
  486. if (key.empty()) {
  487. key.assign(b, e);
  488. } else {
  489. val.assign(b, e);
  490. }
  491. });
  492. params[key] = detail::decode_url(val);
  493. });
  494. }
  495. #ifdef _MSC_VER
  496. class WSInit {
  497. public:
  498. WSInit::WSInit() {
  499. WSADATA wsaData;
  500. WSAStartup(0x0002, &wsaData);
  501. }
  502. WSInit::~WSInit() {
  503. WSACleanup();
  504. }
  505. };
  506. static WSInit wsinit_;
  507. #endif
  508. } // namespace detail
  509. // Request implementation
  510. inline bool Request::has_header(const char* key) const
  511. {
  512. return headers.find(key) != headers.end();
  513. }
  514. inline std::string Request::get_header_value(const char* key) const
  515. {
  516. return detail::get_header_value(headers, key, "");
  517. }
  518. inline void Request::set_header(const char* key, const char* val)
  519. {
  520. headers.insert(std::make_pair(key, val));
  521. }
  522. inline bool Request::has_param(const char* key) const
  523. {
  524. return params.find(key) != params.end();
  525. }
  526. // Response implementation
  527. inline bool Response::has_header(const char* key) const
  528. {
  529. return headers.find(key) != headers.end();
  530. }
  531. inline std::string Response::get_header_value(const char* key) const
  532. {
  533. return detail::get_header_value(headers, key, "");
  534. }
  535. inline void Response::set_header(const char* key, const char* val)
  536. {
  537. headers.insert(std::make_pair(key, val));
  538. }
  539. inline void Response::set_redirect(const char* url)
  540. {
  541. set_header("Location", url);
  542. status = 302;
  543. }
  544. inline void Response::set_content(const std::string& s, const char* content_type)
  545. {
  546. body = s;
  547. set_header("Content-Type", content_type);
  548. }
  549. // HTTP server implementation
  550. inline Server::Server()
  551. : svr_sock_(-1)
  552. {
  553. }
  554. inline void Server::get(const char* pattern, Handler handler)
  555. {
  556. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  557. }
  558. inline void Server::post(const char* pattern, Handler handler)
  559. {
  560. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  561. }
  562. inline bool Server::set_base_dir(const char* path)
  563. {
  564. if (detail::is_dir(path)) {
  565. base_dir_ = path;
  566. return true;
  567. }
  568. return false;
  569. }
  570. inline void Server::set_error_handler(Handler handler)
  571. {
  572. error_handler_ = handler;
  573. }
  574. inline void Server::set_logger(Logger logger)
  575. {
  576. logger_ = logger;
  577. }
  578. inline bool Server::listen(const char* host, int port)
  579. {
  580. svr_sock_ = detail::create_server_socket(host, port);
  581. if (svr_sock_ == -1) {
  582. return false;
  583. }
  584. auto ret = true;
  585. for (;;) {
  586. socket_t sock = accept(svr_sock_, NULL, NULL);
  587. if (sock == -1) {
  588. if (svr_sock_ != -1) {
  589. detail::close_socket(svr_sock_);
  590. ret = false;
  591. } else {
  592. ; // The server socket was closed by user.
  593. }
  594. break;
  595. }
  596. // TODO: should be async
  597. detail::read_and_close_socket(sock, [this](FILE* fp_read, FILE* fp_write) {
  598. process_request(fp_read, fp_write);
  599. return true;
  600. });
  601. }
  602. return ret;
  603. }
  604. inline void Server::stop()
  605. {
  606. detail::shutdown_socket(svr_sock_);
  607. detail::close_socket(svr_sock_);
  608. svr_sock_ = -1;
  609. }
  610. inline bool Server::read_request_line(FILE* fp, Request& req)
  611. {
  612. const auto BUFSIZ_REQUESTLINE = 2048;
  613. char buf[BUFSIZ_REQUESTLINE];
  614. if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
  615. return false;
  616. }
  617. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  618. std::cmatch m;
  619. if (std::regex_match(buf, m, re)) {
  620. req.method = std::string(m[1]);
  621. req.url = detail::decode_url(m[2]);
  622. // Parse query text
  623. auto len = std::distance(m[3].first, m[3].second);
  624. if (len > 0) {
  625. detail::parse_query_text(m[3], req.params);
  626. }
  627. return true;
  628. }
  629. return false;
  630. }
  631. inline bool Server::handle_file_request(Request& req, Response& res)
  632. {
  633. if (!base_dir_.empty()) {
  634. std::string path = base_dir_ + req.url;
  635. if (!path.empty() && path.back() == '/') {
  636. path += "index.html";
  637. }
  638. if (detail::is_file(path)) {
  639. detail::read_file(path, res.body);
  640. res.set_header("Content-Type",
  641. detail::get_content_type_from_file_extention(
  642. detail::get_file_extention(path)));
  643. res.status = 200;
  644. return true;
  645. }
  646. }
  647. return false;
  648. }
  649. inline bool Server::routing(Request& req, Response& res)
  650. {
  651. if (req.method == "GET" && handle_file_request(req, res)) {
  652. return true;
  653. }
  654. if (req.method == "GET" || req.method == "HEAD") {
  655. return dispatch_request(req, res, get_handlers_);
  656. } else if (req.method == "POST") {
  657. return dispatch_request(req, res, post_handlers_);
  658. }
  659. return false;
  660. }
  661. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  662. {
  663. for (const auto& x: handlers) {
  664. const auto& pattern = x.first;
  665. const auto& handler = x.second;
  666. if (std::regex_match(req.url, req.matches, pattern)) {
  667. handler(req, res);
  668. return true;
  669. }
  670. }
  671. return false;
  672. }
  673. inline void Server::process_request(FILE* fp_read, FILE* fp_write)
  674. {
  675. Request req;
  676. Response res;
  677. if (!read_request_line(fp_read, req) ||
  678. !detail::read_headers(fp_read, req.headers)) {
  679. return;
  680. }
  681. if (req.method == "POST") {
  682. if (!detail::read_content(req, fp_read)) {
  683. return;
  684. }
  685. static std::string type = "application/x-www-form-urlencoded";
  686. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  687. detail::parse_query_text(req.body, req.params);
  688. }
  689. }
  690. if (routing(req, res)) {
  691. if (res.status == -1) {
  692. res.status = 200;
  693. }
  694. } else {
  695. res.status = 404;
  696. }
  697. assert(res.status != -1);
  698. if (400 <= res.status && error_handler_) {
  699. error_handler_(req, res);
  700. }
  701. detail::write_response(fp_write, req, res);
  702. fflush(fp_write);
  703. if (logger_) {
  704. logger_(req, res);
  705. }
  706. }
  707. // HTTP client implementation
  708. inline Client::Client(const char* host, int port)
  709. : host_(host)
  710. , port_(port)
  711. {
  712. }
  713. inline bool Client::read_response_line(FILE* fp, Response& res)
  714. {
  715. const auto BUFSIZ_RESPONSELINE = 2048;
  716. char buf[BUFSIZ_RESPONSELINE];
  717. if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
  718. return false;
  719. }
  720. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  721. std::cmatch m;
  722. if (std::regex_match(buf, m, re)) {
  723. res.status = std::stoi(std::string(m[1]));
  724. }
  725. return true;
  726. }
  727. inline bool Client::send(const Request& req, Response& res)
  728. {
  729. auto sock = detail::create_client_socket(host_.c_str(), port_);
  730. if (sock == -1) {
  731. return false;
  732. }
  733. return detail::read_and_close_socket(sock, [&](FILE* fp_read, FILE* fp_write) {
  734. // Send request
  735. detail::write_request(fp_write, req);
  736. fflush(fp_write);
  737. // Receive response
  738. if (!read_response_line(fp_read, res) ||
  739. !detail::read_headers(fp_read, res.headers)) {
  740. return false;
  741. }
  742. if (req.method != "HEAD") {
  743. if (!detail::read_content(res, fp_read)) {
  744. return false;
  745. }
  746. }
  747. return true;
  748. });
  749. }
  750. inline std::shared_ptr<Response> Client::get(const char* url)
  751. {
  752. Request req;
  753. req.method = "GET";
  754. req.url = url;
  755. auto res = std::make_shared<Response>();
  756. return send(req, *res) ? res : nullptr;
  757. }
  758. inline std::shared_ptr<Response> Client::head(const char* url)
  759. {
  760. Request req;
  761. req.method = "HEAD";
  762. req.url = url;
  763. auto res = std::make_shared<Response>();
  764. return send(req, *res) ? res : nullptr;
  765. }
  766. inline std::shared_ptr<Response> Client::post(
  767. const char* url, const std::string& body, const char* content_type)
  768. {
  769. Request req;
  770. req.method = "POST";
  771. req.url = url;
  772. req.set_header("Content-Type", content_type);
  773. req.body = body;
  774. auto res = std::make_shared<Response>();
  775. return send(req, *res) ? res : nullptr;
  776. }
  777. inline std::shared_ptr<Response> Client::post(
  778. const char* url, const Map& params)
  779. {
  780. std::string query;
  781. for (auto it = params.begin(); it != params.end(); ++it) {
  782. if (it != params.begin()) {
  783. query += "&";
  784. }
  785. query += it->first;
  786. query += "=";
  787. query += it->second;
  788. }
  789. return post(url, query, "application/x-www-form-urlencoded");
  790. }
  791. } // namespace httplib
  792. #endif
  793. // vim: et ts=4 sw=4 cin cino={1s ff=unix