httplib.h 19 KB

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