httplib.h 19 KB

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