http_client.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. #include "http_client.h"
  2. #include <mutex>
  3. #ifdef WITH_CURL
  4. #include "curl/curl.h"
  5. #endif
  6. #include "herr.h"
  7. #include "hlog.h"
  8. #include "hstring.h"
  9. #include "hsocket.h"
  10. #include "hssl.h"
  11. #include "HttpParser.h"
  12. // for async
  13. #include "AsyncHttpClient.h"
  14. using namespace hv;
  15. struct http_client_s {
  16. std::string host;
  17. int port;
  18. int https;
  19. int timeout; // s
  20. http_headers headers;
  21. // http_proxy
  22. std::string http_proxy_host;
  23. int http_proxy_port;
  24. // https_proxy
  25. std::string https_proxy_host;
  26. int https_proxy_port;
  27. // no_proxy
  28. StringList no_proxy_hosts;
  29. //private:
  30. #ifdef WITH_CURL
  31. CURL* curl;
  32. #endif
  33. // for sync
  34. int fd;
  35. hssl_t ssl;
  36. hssl_ctx_t ssl_ctx;
  37. bool alloced_ssl_ctx;
  38. HttpParserPtr parser;
  39. // for async
  40. std::mutex mutex_;
  41. std::shared_ptr<hv::AsyncHttpClient> async_client_;
  42. http_client_s() {
  43. host = LOCALHOST;
  44. port = DEFAULT_HTTP_PORT;
  45. https = 0;
  46. timeout = DEFAULT_HTTP_TIMEOUT;
  47. http_proxy_port = DEFAULT_HTTP_PORT;
  48. https_proxy_port = DEFAULT_HTTP_PORT;
  49. #ifdef WITH_CURL
  50. curl = NULL;
  51. #endif
  52. fd = -1;
  53. ssl = NULL;
  54. ssl_ctx = NULL;
  55. alloced_ssl_ctx = false;
  56. }
  57. ~http_client_s() {
  58. Close();
  59. if (ssl_ctx && alloced_ssl_ctx) {
  60. hssl_ctx_free(ssl_ctx);
  61. ssl_ctx = NULL;
  62. }
  63. }
  64. void Close() {
  65. #ifdef WITH_CURL
  66. if (curl) {
  67. curl_easy_cleanup(curl);
  68. curl = NULL;
  69. }
  70. #endif
  71. if (ssl) {
  72. hssl_free(ssl);
  73. ssl = NULL;
  74. }
  75. SAFE_CLOSESOCKET(fd);
  76. }
  77. };
  78. http_client_t* http_client_new(const char* host, int port, int https) {
  79. http_client_t* cli = new http_client_t;
  80. if (host) cli->host = host;
  81. cli->port = port;
  82. cli->https = https;
  83. cli->headers["Connection"] = "keep-alive";
  84. return cli;
  85. }
  86. int http_client_del(http_client_t* cli) {
  87. if (cli == NULL) return 0;
  88. delete cli;
  89. return 0;
  90. }
  91. int http_client_set_timeout(http_client_t* cli, int timeout) {
  92. cli->timeout = timeout;
  93. return 0;
  94. }
  95. int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx) {
  96. cli->ssl_ctx = ssl_ctx;
  97. return 0;
  98. }
  99. int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt) {
  100. opt->endpoint = HSSL_CLIENT;
  101. hssl_ctx_t ssl_ctx = hssl_ctx_new(opt);
  102. if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX;
  103. cli->alloced_ssl_ctx = true;
  104. return http_client_set_ssl_ctx(cli, ssl_ctx);
  105. }
  106. int http_client_clear_headers(http_client_t* cli) {
  107. cli->headers.clear();
  108. return 0;
  109. }
  110. int http_client_set_header(http_client_t* cli, const char* key, const char* value) {
  111. cli->headers[key] = value;
  112. return 0;
  113. }
  114. int http_client_del_header(http_client_t* cli, const char* key) {
  115. auto iter = cli->headers.find(key);
  116. if (iter != cli->headers.end()) {
  117. cli->headers.erase(iter);
  118. }
  119. return 0;
  120. }
  121. const char* http_client_get_header(http_client_t* cli, const char* key) {
  122. auto iter = cli->headers.find(key);
  123. if (iter != cli->headers.end()) {
  124. return iter->second.c_str();
  125. }
  126. return NULL;
  127. }
  128. int http_client_set_http_proxy(http_client_t* cli, const char* host, int port) {
  129. cli->http_proxy_host = host;
  130. cli->http_proxy_port = port;
  131. return 0;
  132. }
  133. int http_client_set_https_proxy(http_client_t* cli, const char* host, int port) {
  134. cli->https_proxy_host = host;
  135. cli->https_proxy_port = port;
  136. return 0;
  137. }
  138. int http_client_add_no_proxy(http_client_t* cli, const char* host) {
  139. cli->no_proxy_hosts.push_back(host);
  140. return 0;
  141. }
  142. static int http_client_make_request(http_client_t* cli, HttpRequest* req) {
  143. if (req->url.empty() || *req->url.c_str() == '/') {
  144. req->scheme = cli->https ? "https" : "http";
  145. req->host = cli->host;
  146. req->port = cli->port;
  147. }
  148. req->ParseUrl();
  149. bool https = req->IsHttps();
  150. bool use_proxy = https ? (!cli->https_proxy_host.empty()) : (!cli->http_proxy_host.empty());
  151. if (use_proxy) {
  152. if (req->host == "127.0.0.1" || req->host == "localhost") {
  153. use_proxy = false;
  154. }
  155. }
  156. if (use_proxy) {
  157. for (const auto& host : cli->no_proxy_hosts) {
  158. if (req->host == host) {
  159. use_proxy = false;
  160. break;
  161. }
  162. }
  163. }
  164. if (use_proxy) {
  165. req->SetProxy(https ? cli->https_proxy_host.c_str() : cli->http_proxy_host.c_str(),
  166. https ? cli->https_proxy_port : cli->http_proxy_port);
  167. }
  168. if (req->timeout == 0) {
  169. req->timeout = cli->timeout;
  170. }
  171. for (const auto& pair : cli->headers) {
  172. if (req->headers.find(pair.first) == req->headers.end()) {
  173. req->headers.insert(pair);
  174. }
  175. }
  176. return 0;
  177. }
  178. int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout) {
  179. int blocktime = DEFAULT_CONNECT_TIMEOUT;
  180. if (timeout > 0) {
  181. blocktime = MIN(timeout*1000, blocktime);
  182. }
  183. int connfd = ConnectTimeout(host, port, blocktime);
  184. if (connfd < 0) {
  185. fprintf(stderr, "* connect %s:%d failed!\n", host, port);
  186. hloge("connect %s:%d failed!", host, port);
  187. return connfd;
  188. }
  189. tcp_nodelay(connfd, 1);
  190. if (https && cli->ssl == NULL) {
  191. // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new
  192. hssl_ctx_t ssl_ctx = NULL;
  193. if (cli->ssl_ctx) {
  194. ssl_ctx = cli->ssl_ctx;
  195. } else if (g_ssl_ctx) {
  196. ssl_ctx = g_ssl_ctx;
  197. } else {
  198. cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
  199. cli->alloced_ssl_ctx = true;
  200. }
  201. if (ssl_ctx == NULL) {
  202. closesocket(connfd);
  203. return NABS(ERR_NEW_SSL_CTX);
  204. }
  205. cli->ssl = hssl_new(ssl_ctx, connfd);
  206. if (cli->ssl == NULL) {
  207. closesocket(connfd);
  208. return NABS(ERR_NEW_SSL);
  209. }
  210. if (!is_ipaddr(host)) {
  211. hssl_set_sni_hostname(cli->ssl, host);
  212. }
  213. int ret = hssl_connect(cli->ssl);
  214. if (ret != 0) {
  215. fprintf(stderr, "* ssl handshake failed: %d\n", ret);
  216. hloge("ssl handshake failed: %d", ret);
  217. hssl_free(cli->ssl);
  218. cli->ssl = NULL;
  219. closesocket(connfd);
  220. return NABS(ret);
  221. }
  222. }
  223. cli->fd = connfd;
  224. return connfd;
  225. }
  226. int http_client_close(http_client_t* cli) {
  227. if (cli == NULL) return 0;
  228. cli->Close();
  229. return 0;
  230. }
  231. int http_client_send_data(http_client_t* cli, const char* data, int size) {
  232. if (!cli || !data || size <= 0) return -1;
  233. if (cli->ssl) {
  234. return hssl_write(cli->ssl, data, size);
  235. }
  236. return send(cli->fd, data, size, 0);
  237. }
  238. int http_client_recv_data(http_client_t* cli, char* data, int size) {
  239. if (!cli || !data || size <= 0) return -1;
  240. if (cli->ssl) {
  241. return hssl_read(cli->ssl, data, size);
  242. }
  243. return recv(cli->fd, data, size, 0);
  244. }
  245. static int http_client_exec(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  246. // connect -> send -> recv -> http_parser
  247. int err = 0;
  248. int timeout = req->timeout;
  249. int connfd = cli->fd;
  250. bool https = req->IsHttps() && !req->IsProxy();
  251. bool keepalive = true;
  252. time_t start_time = time(NULL);
  253. time_t cur_time;
  254. int fail_cnt = 0;
  255. if (connfd <= 0) {
  256. connect:
  257. connfd = http_client_connect(cli, req->host.c_str(), req->port, https, MIN(req->connect_timeout, req->timeout));
  258. if (connfd < 0) {
  259. return connfd;
  260. }
  261. }
  262. if (cli->parser == NULL) {
  263. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  264. if (cli->parser == NULL) {
  265. hloge("New HttpParser failed!");
  266. return ERR_NULL_POINTER;
  267. }
  268. }
  269. cli->parser->SubmitRequest(req);
  270. char recvbuf[1024] = {0};
  271. int total_nsend, nsend, nrecv;
  272. total_nsend = nsend = nrecv = 0;
  273. send:
  274. char* data = NULL;
  275. size_t len = 0;
  276. while (cli->parser->GetSendData(&data, &len)) {
  277. total_nsend = 0;
  278. while (total_nsend < len) {
  279. if (timeout > 0) {
  280. cur_time = time(NULL);
  281. if (cur_time - start_time >= timeout) {
  282. return ERR_TASK_TIMEOUT;
  283. }
  284. so_sndtimeo(cli->fd, (timeout-(cur_time-start_time)) * 1000);
  285. }
  286. nsend = http_client_send_data(cli, data + total_nsend, len - total_nsend);
  287. if (nsend <= 0) {
  288. if (++fail_cnt == 1) {
  289. // maybe keep-alive timeout, try again
  290. cli->Close();
  291. goto connect;
  292. }
  293. else {
  294. err = socket_errno();
  295. if (err == EINTR) continue;
  296. goto disconnect;
  297. }
  298. }
  299. total_nsend += nsend;
  300. }
  301. }
  302. if (resp == NULL) return 0;
  303. cli->parser->InitResponse(resp);
  304. recv:
  305. do {
  306. if (timeout > 0) {
  307. cur_time = time(NULL);
  308. if (cur_time - start_time >= timeout) {
  309. return ERR_TASK_TIMEOUT;
  310. }
  311. so_rcvtimeo(cli->fd, (timeout-(cur_time-start_time)) * 1000);
  312. }
  313. nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf));
  314. if (nrecv <= 0) {
  315. if (resp->content_length == 0 && resp->http_major == 1 && resp->http_minor == 0) {
  316. // HTTP/1.0, assume close after body
  317. goto disconnect;
  318. }
  319. if (++fail_cnt == 1) {
  320. // maybe keep-alive timeout, try again
  321. cli->Close();
  322. goto connect;
  323. }
  324. else {
  325. err = socket_errno();
  326. if (err == EINTR) continue;
  327. goto disconnect;
  328. }
  329. }
  330. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  331. if (nparse != nrecv) {
  332. return ERR_PARSE;
  333. }
  334. } while(!cli->parser->IsComplete());
  335. keepalive = req->IsKeepAlive() && resp->IsKeepAlive();
  336. if (!keepalive) {
  337. cli->Close();
  338. }
  339. return 0;
  340. disconnect:
  341. cli->Close();
  342. return err;
  343. }
  344. int http_client_send_header(http_client_t* cli, HttpRequest* req) {
  345. if (!cli || !req) return ERR_NULL_POINTER;
  346. http_client_make_request(cli, req);
  347. return http_client_exec(cli, req, NULL);
  348. }
  349. int http_client_recv_response(http_client_t* cli, HttpResponse* resp) {
  350. if (!cli || !resp) return ERR_NULL_POINTER;
  351. if (!cli->parser) {
  352. hloge("Call http_client_send_header first!");
  353. return ERR_NULL_POINTER;
  354. }
  355. char recvbuf[1024] = {0};
  356. cli->parser->InitResponse(resp);
  357. do {
  358. int nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf));
  359. if (nrecv <= 0) {
  360. int err = socket_errno();
  361. if (err == EINTR) continue;
  362. cli->Close();
  363. return err;
  364. }
  365. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  366. if (nparse != nrecv) {
  367. return ERR_PARSE;
  368. }
  369. } while(!cli->parser->IsComplete());
  370. return 0;
  371. }
  372. #ifdef WITH_CURL
  373. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  374. if (buf == NULL || userdata == NULL) return 0;
  375. size_t len = size * cnt;
  376. std::string str(buf, len);
  377. HttpResponse* resp = (HttpResponse*)userdata;
  378. std::string::size_type pos = str.find_first_of(':');
  379. if (pos == std::string::npos) {
  380. if (strncmp(buf, "HTTP/", 5) == 0) {
  381. // status line
  382. //hlogd("%s", buf);
  383. int http_major = 1, http_minor = 1, status_code = 200;
  384. if (buf[5] == '1') {
  385. // HTTP/1.1 200 OK\r\n
  386. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  387. }
  388. else if (buf[5] == '2') {
  389. // HTTP/2 200\r\n
  390. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  391. http_minor = 0;
  392. }
  393. resp->http_major = http_major;
  394. resp->http_minor = http_minor;
  395. resp->status_code = (http_status)status_code;
  396. if (resp->http_cb) {
  397. resp->http_cb(resp, HP_MESSAGE_BEGIN, NULL, 0);
  398. }
  399. }
  400. }
  401. else {
  402. // headers
  403. std::string key = trim(str.substr(0, pos));
  404. std::string value = trim(str.substr(pos+1));
  405. resp->headers[key] = value;
  406. }
  407. return len;
  408. }
  409. static size_t s_body_cb(char* buf, size_t size, size_t cnt, void *userdata) {
  410. if (buf == NULL || userdata == NULL) return 0;
  411. size_t len = size * cnt;
  412. HttpMessage* resp = (HttpMessage*)userdata;
  413. if (resp->http_cb) {
  414. if (resp->content == NULL && resp->content_length == 0) {
  415. resp->content = buf;
  416. resp->content_length = len;
  417. resp->http_cb(resp, HP_HEADERS_COMPLETE, NULL, 0);
  418. }
  419. resp->http_cb(resp, HP_BODY, buf, len);
  420. } else {
  421. resp->body.append(buf, len);
  422. }
  423. return len;
  424. }
  425. static int http_client_exec_curl(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  426. if (cli->curl == NULL) {
  427. cli->curl = curl_easy_init();
  428. }
  429. CURL* curl = cli->curl;
  430. // proxy
  431. if (req->IsProxy()) {
  432. curl_easy_setopt(curl, CURLOPT_PROXY, req->host.c_str());
  433. curl_easy_setopt(curl, CURLOPT_PROXYPORT, req->port);
  434. }
  435. // SSL
  436. if (req->IsHttps()) {
  437. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  438. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  439. }
  440. // http2
  441. if (req->http_major == 2) {
  442. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  443. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  444. #else
  445. // No Connection: Upgrade
  446. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  447. #endif
  448. }
  449. // TCP_NODELAY
  450. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  451. // method
  452. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  453. // url
  454. req->DumpUrl();
  455. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  456. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  457. // headers
  458. req->FillContentType();
  459. struct curl_slist *headers = NULL;
  460. for (auto& pair : req->headers) {
  461. std::string header = pair.first;
  462. header += ": ";
  463. header += pair.second;
  464. headers = curl_slist_append(headers, header.c_str());
  465. }
  466. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  467. // body
  468. //struct curl_httppost* httppost = NULL;
  469. //struct curl_httppost* lastpost = NULL;
  470. if (req->body.size() == 0) {
  471. req->DumpBody();
  472. /*
  473. if (req->body.size() == 0 &&
  474. req->content_type == MULTIPART_FORM_DATA) {
  475. for (auto& pair : req->mp) {
  476. if (pair.second.filename.size() != 0) {
  477. curl_formadd(&httppost, &lastpost,
  478. CURLFORM_COPYNAME, pair.first.c_str(),
  479. CURLFORM_FILE, pair.second.filename.c_str(),
  480. CURLFORM_END);
  481. }
  482. else if (pair.second.content.size() != 0) {
  483. curl_formadd(&httppost, &lastpost,
  484. CURLFORM_COPYNAME, pair.first.c_str(),
  485. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  486. CURLFORM_END);
  487. }
  488. }
  489. if (httppost) {
  490. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  491. }
  492. }
  493. */
  494. }
  495. if (req->body.size() != 0) {
  496. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  497. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  498. }
  499. if (req->connect_timeout > 0) {
  500. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, req->connect_timeout);
  501. }
  502. if (req->timeout > 0) {
  503. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  504. }
  505. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  506. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  507. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  508. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  509. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  510. int ret = curl_easy_perform(curl);
  511. /*
  512. if (ret != 0) {
  513. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  514. }
  515. if (resp->body.length() != 0) {
  516. hlogd("[Response]\n%s", resp->body.c_str());
  517. }
  518. double total_time, name_time, conn_time, pre_time;
  519. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  520. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  521. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  522. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  523. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  524. */
  525. if (headers) {
  526. curl_slist_free_all(headers);
  527. }
  528. /*
  529. if (httppost) {
  530. curl_formfree(httppost);
  531. }
  532. */
  533. if (resp->http_cb) {
  534. resp->http_cb(resp, HP_MESSAGE_COMPLETE, NULL, 0);
  535. }
  536. return ret;
  537. }
  538. const char* http_client_strerror(int errcode) {
  539. return curl_easy_strerror((CURLcode)errcode);
  540. }
  541. #else
  542. const char* http_client_strerror(int errcode) {
  543. return socket_strerror(errcode);
  544. }
  545. #endif
  546. static int http_client_redirect(HttpRequest* req, HttpResponse* resp) {
  547. std::string location = resp->headers["Location"];
  548. if (!location.empty()) {
  549. hlogi("redirect %s => %s", req->url.c_str(), location.c_str());
  550. req->url = location;
  551. req->ParseUrl();
  552. req->headers["Host"] = req->host;
  553. resp->Reset();
  554. return http_client_send(req, resp);
  555. }
  556. return 0;
  557. }
  558. int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  559. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  560. http_client_make_request(cli, req);
  561. if (req->http_cb) resp->http_cb = std::move(req->http_cb);
  562. #if WITH_CURL
  563. int ret = http_client_exec_curl(cli, req, resp);
  564. #else
  565. int ret = http_client_exec(cli, req, resp);
  566. #endif
  567. if (ret != 0) return ret;
  568. // redirect
  569. if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) {
  570. return http_client_redirect(req, resp);
  571. }
  572. return 0;
  573. }
  574. int http_client_send(HttpRequest* req, HttpResponse* resp) {
  575. if (!req || !resp) return ERR_NULL_POINTER;
  576. http_client_t cli;
  577. return http_client_send(&cli, req, resp);
  578. }
  579. // below for async
  580. static int http_client_exec_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  581. if (cli->async_client_ == NULL) {
  582. cli->mutex_.lock();
  583. if (cli->async_client_ == NULL) {
  584. cli->async_client_.reset(new hv::AsyncHttpClient);
  585. }
  586. cli->mutex_.unlock();
  587. }
  588. return cli->async_client_->send(req, std::move(resp_cb));
  589. }
  590. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  591. if (!cli || !req) return ERR_NULL_POINTER;
  592. http_client_make_request(cli, req.get());
  593. return http_client_exec_async(cli, req, std::move(resp_cb));
  594. }
  595. static http_client_t* s_async_http_client = NULL;
  596. static void hv_destroy_default_async_http_client() {
  597. hlogi("destory default http async client");
  598. if (s_async_http_client) {
  599. http_client_del(s_async_http_client);
  600. s_async_http_client = NULL;
  601. }
  602. }
  603. static http_client_t* hv_default_async_http_client() {
  604. static std::mutex s_mutex;
  605. if (s_async_http_client == NULL) {
  606. s_mutex.lock();
  607. if (s_async_http_client == NULL) {
  608. hlogi("create default http async client");
  609. s_async_http_client = http_client_new();
  610. // NOTE: I have No better idea
  611. atexit(hv_destroy_default_async_http_client);
  612. }
  613. s_mutex.unlock();
  614. }
  615. return s_async_http_client;
  616. }
  617. int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
  618. if (req == NULL) return ERR_NULL_POINTER;
  619. if (req->timeout == 0) {
  620. req->timeout = DEFAULT_HTTP_TIMEOUT;
  621. }
  622. return http_client_exec_async(hv_default_async_http_client(), req, std::move(resp_cb));
  623. }