HttpClient.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #include "HttpClient.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. hloge("connect %s:%d failed!", host, port);
  186. return connfd;
  187. }
  188. tcp_nodelay(connfd, 1);
  189. if (https && cli->ssl == NULL) {
  190. // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new
  191. hssl_ctx_t ssl_ctx = NULL;
  192. if (cli->ssl_ctx) {
  193. ssl_ctx = cli->ssl_ctx;
  194. } else if (g_ssl_ctx) {
  195. ssl_ctx = g_ssl_ctx;
  196. } else {
  197. cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL);
  198. cli->alloced_ssl_ctx = true;
  199. }
  200. if (ssl_ctx == NULL) {
  201. closesocket(connfd);
  202. return NABS(ERR_NEW_SSL_CTX);
  203. }
  204. cli->ssl = hssl_new(ssl_ctx, connfd);
  205. if (cli->ssl == NULL) {
  206. closesocket(connfd);
  207. return NABS(ERR_NEW_SSL);
  208. }
  209. if (!is_ipaddr(host)) {
  210. hssl_set_sni_hostname(cli->ssl, host);
  211. }
  212. int ret = hssl_connect(cli->ssl);
  213. if (ret != 0) {
  214. fprintf(stderr, "* ssl handshake failed: %d\n", ret);
  215. hloge("ssl handshake failed: %d", ret);
  216. hssl_free(cli->ssl);
  217. cli->ssl = NULL;
  218. closesocket(connfd);
  219. return NABS(ret);
  220. }
  221. }
  222. cli->fd = connfd;
  223. return connfd;
  224. }
  225. int http_client_close(http_client_t* cli) {
  226. if (cli == NULL) return 0;
  227. cli->Close();
  228. return 0;
  229. }
  230. int http_client_send_data(http_client_t* cli, const char* data, int size) {
  231. if (!cli || !data || size <= 0) return -1;
  232. if (cli->ssl) {
  233. return hssl_write(cli->ssl, data, size);
  234. }
  235. return send(cli->fd, data, size, 0);
  236. }
  237. int http_client_recv_data(http_client_t* cli, char* data, int size) {
  238. if (!cli || !data || size <= 0) return -1;
  239. if (cli->ssl) {
  240. return hssl_read(cli->ssl, data, size);
  241. }
  242. return recv(cli->fd, data, size, 0);
  243. }
  244. static int http_client_exec(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  245. // connect -> send -> recv -> http_parser
  246. int err = 0;
  247. int timeout = req->timeout;
  248. int connfd = cli->fd;
  249. bool https = req->IsHttps() && !req->IsProxy();
  250. bool keepalive = true;
  251. time_t start_time = time(NULL);
  252. time_t cur_time;
  253. int fail_cnt = 0;
  254. if (connfd <= 0) {
  255. connect:
  256. connfd = http_client_connect(cli, req->host.c_str(), req->port, https, MIN(req->connect_timeout, req->timeout));
  257. if (connfd < 0) {
  258. return connfd;
  259. }
  260. }
  261. if (cli->parser == NULL) {
  262. cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
  263. if (cli->parser == NULL) {
  264. hloge("New HttpParser failed!");
  265. return ERR_NULL_POINTER;
  266. }
  267. }
  268. cli->parser->SubmitRequest(req);
  269. char recvbuf[1024] = {0};
  270. int total_nsend, nsend, nrecv;
  271. total_nsend = nsend = nrecv = 0;
  272. send:
  273. char* data = NULL;
  274. size_t len = 0;
  275. while (cli->parser->GetSendData(&data, &len)) {
  276. total_nsend = 0;
  277. while (total_nsend < len) {
  278. if (timeout > 0) {
  279. cur_time = time(NULL);
  280. if (cur_time - start_time >= timeout) {
  281. return ERR_TASK_TIMEOUT;
  282. }
  283. so_sndtimeo(cli->fd, (timeout-(cur_time-start_time)) * 1000);
  284. }
  285. nsend = http_client_send_data(cli, data + total_nsend, len - total_nsend);
  286. if (nsend <= 0) {
  287. err = socket_errno();
  288. if (err == EINTR) continue;
  289. if (++fail_cnt == 1) {
  290. // maybe keep-alive timeout, try again
  291. cli->Close();
  292. err = 0;
  293. goto connect;
  294. }
  295. goto disconnect;
  296. }
  297. total_nsend += nsend;
  298. }
  299. }
  300. if (resp == NULL) return 0;
  301. cli->parser->InitResponse(resp);
  302. recv:
  303. do {
  304. if (timeout > 0) {
  305. cur_time = time(NULL);
  306. if (cur_time - start_time >= timeout) {
  307. return ERR_TASK_TIMEOUT;
  308. }
  309. so_rcvtimeo(cli->fd, (timeout-(cur_time-start_time)) * 1000);
  310. }
  311. nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf));
  312. if (nrecv <= 0) {
  313. err = socket_errno();
  314. if (err == EINTR) continue;
  315. if (cli->parser->IsEof()) {
  316. err = 0;
  317. goto disconnect;
  318. }
  319. if (++fail_cnt == 1) {
  320. // maybe keep-alive timeout, try again
  321. cli->Close();
  322. err = 0;
  323. goto connect;
  324. }
  325. goto disconnect;
  326. }
  327. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  328. if (nparse != nrecv) {
  329. return ERR_PARSE;
  330. }
  331. } while(!cli->parser->IsComplete());
  332. keepalive = req->IsKeepAlive() && resp->IsKeepAlive();
  333. if (!keepalive) {
  334. cli->Close();
  335. }
  336. return 0;
  337. disconnect:
  338. cli->Close();
  339. return err;
  340. }
  341. int http_client_send_header(http_client_t* cli, HttpRequest* req) {
  342. if (!cli || !req) return ERR_NULL_POINTER;
  343. http_client_make_request(cli, req);
  344. return http_client_exec(cli, req, NULL);
  345. }
  346. int http_client_recv_response(http_client_t* cli, HttpResponse* resp) {
  347. if (!cli || !resp) return ERR_NULL_POINTER;
  348. if (!cli->parser) {
  349. hloge("Call http_client_send_header first!");
  350. return ERR_NULL_POINTER;
  351. }
  352. char recvbuf[1024] = {0};
  353. cli->parser->InitResponse(resp);
  354. do {
  355. int nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf));
  356. if (nrecv <= 0) {
  357. int err = socket_errno();
  358. if (err == EINTR) continue;
  359. cli->Close();
  360. return err;
  361. }
  362. int nparse = cli->parser->FeedRecvData(recvbuf, nrecv);
  363. if (nparse != nrecv) {
  364. return ERR_PARSE;
  365. }
  366. } while(!cli->parser->IsComplete());
  367. return 0;
  368. }
  369. #ifdef WITH_CURL
  370. static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) {
  371. if (buf == NULL || userdata == NULL) return 0;
  372. size_t len = size * cnt;
  373. std::string str(buf, len);
  374. HttpResponse* resp = (HttpResponse*)userdata;
  375. std::string::size_type pos = str.find_first_of(':');
  376. if (pos == std::string::npos) {
  377. if (strncmp(buf, "HTTP/", 5) == 0) {
  378. // status line
  379. //hlogd("%s", buf);
  380. int http_major = 1, http_minor = 1, status_code = 200;
  381. if (buf[5] == '1') {
  382. // HTTP/1.1 200 OK\r\n
  383. sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code);
  384. }
  385. else if (buf[5] == '2') {
  386. // HTTP/2 200\r\n
  387. sscanf(buf, "HTTP/%d %d", &http_major, &status_code);
  388. http_minor = 0;
  389. }
  390. resp->http_major = http_major;
  391. resp->http_minor = http_minor;
  392. resp->status_code = (http_status)status_code;
  393. if (resp->http_cb) {
  394. resp->http_cb(resp, HP_MESSAGE_BEGIN, NULL, 0);
  395. }
  396. }
  397. }
  398. else {
  399. // headers
  400. std::string key = trim(str.substr(0, pos));
  401. std::string value = trim(str.substr(pos+1));
  402. resp->headers[key] = value;
  403. }
  404. return len;
  405. }
  406. static size_t s_body_cb(char* buf, size_t size, size_t cnt, void *userdata) {
  407. if (buf == NULL || userdata == NULL) return 0;
  408. size_t len = size * cnt;
  409. HttpMessage* resp = (HttpMessage*)userdata;
  410. if (resp->http_cb) {
  411. if (resp->content == NULL && resp->content_length == 0) {
  412. resp->content = buf;
  413. resp->content_length = len;
  414. resp->http_cb(resp, HP_HEADERS_COMPLETE, NULL, 0);
  415. }
  416. resp->http_cb(resp, HP_BODY, buf, len);
  417. } else {
  418. resp->body.append(buf, len);
  419. }
  420. return len;
  421. }
  422. static int http_client_exec_curl(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  423. if (cli->curl == NULL) {
  424. cli->curl = curl_easy_init();
  425. }
  426. CURL* curl = cli->curl;
  427. // proxy
  428. if (req->IsProxy()) {
  429. curl_easy_setopt(curl, CURLOPT_PROXY, req->host.c_str());
  430. curl_easy_setopt(curl, CURLOPT_PROXYPORT, req->port);
  431. }
  432. // SSL
  433. if (req->IsHttps()) {
  434. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  435. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  436. }
  437. // http2
  438. if (req->http_major == 2) {
  439. #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0
  440. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0);
  441. #else
  442. // No Connection: Upgrade
  443. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
  444. #endif
  445. }
  446. // TCP_NODELAY
  447. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  448. // method
  449. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method));
  450. // url
  451. req->DumpUrl();
  452. curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str());
  453. //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor);
  454. // headers
  455. req->FillContentType();
  456. struct curl_slist *headers = NULL;
  457. for (auto& pair : req->headers) {
  458. std::string header = pair.first;
  459. header += ": ";
  460. header += pair.second;
  461. headers = curl_slist_append(headers, header.c_str());
  462. }
  463. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  464. // body
  465. //struct curl_httppost* httppost = NULL;
  466. //struct curl_httppost* lastpost = NULL;
  467. if (req->body.size() == 0) {
  468. req->DumpBody();
  469. /*
  470. if (req->body.size() == 0 &&
  471. req->content_type == MULTIPART_FORM_DATA) {
  472. for (auto& pair : req->mp) {
  473. if (pair.second.filename.size() != 0) {
  474. curl_formadd(&httppost, &lastpost,
  475. CURLFORM_COPYNAME, pair.first.c_str(),
  476. CURLFORM_FILE, pair.second.filename.c_str(),
  477. CURLFORM_END);
  478. }
  479. else if (pair.second.content.size() != 0) {
  480. curl_formadd(&httppost, &lastpost,
  481. CURLFORM_COPYNAME, pair.first.c_str(),
  482. CURLFORM_COPYCONTENTS, pair.second.content.c_str(),
  483. CURLFORM_END);
  484. }
  485. }
  486. if (httppost) {
  487. curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost);
  488. }
  489. }
  490. */
  491. }
  492. if (req->body.size() != 0) {
  493. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str());
  494. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size());
  495. }
  496. if (req->connect_timeout > 0) {
  497. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, req->connect_timeout);
  498. }
  499. if (req->timeout > 0) {
  500. curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout);
  501. }
  502. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb);
  503. curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
  504. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  505. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb);
  506. curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp);
  507. int ret = curl_easy_perform(curl);
  508. /*
  509. if (ret != 0) {
  510. hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret));
  511. }
  512. if (resp->body.length() != 0) {
  513. hlogd("[Response]\n%s", resp->body.c_str());
  514. }
  515. double total_time, name_time, conn_time, pre_time;
  516. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
  517. curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time);
  518. curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time);
  519. curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time);
  520. hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time);
  521. */
  522. if (headers) {
  523. curl_slist_free_all(headers);
  524. }
  525. /*
  526. if (httppost) {
  527. curl_formfree(httppost);
  528. }
  529. */
  530. if (resp->http_cb) {
  531. resp->http_cb(resp, HP_MESSAGE_COMPLETE, NULL, 0);
  532. }
  533. return ret;
  534. }
  535. const char* http_client_strerror(int errcode) {
  536. return curl_easy_strerror((CURLcode)errcode);
  537. }
  538. #else
  539. const char* http_client_strerror(int errcode) {
  540. return socket_strerror(errcode);
  541. }
  542. #endif
  543. static int http_client_redirect(HttpRequest* req, HttpResponse* resp) {
  544. std::string location = resp->headers["Location"];
  545. if (!location.empty()) {
  546. hlogi("redirect %s => %s", req->url.c_str(), location.c_str());
  547. req->url = location;
  548. req->ParseUrl();
  549. req->headers["Host"] = req->host;
  550. resp->Reset();
  551. return http_client_send(req, resp);
  552. }
  553. return 0;
  554. }
  555. int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) {
  556. if (!cli || !req || !resp) return ERR_NULL_POINTER;
  557. http_client_make_request(cli, req);
  558. if (req->http_cb) resp->http_cb = std::move(req->http_cb);
  559. #if WITH_CURL
  560. int ret = http_client_exec_curl(cli, req, resp);
  561. #else
  562. int ret = http_client_exec(cli, req, resp);
  563. #endif
  564. if (ret != 0) return ret;
  565. // redirect
  566. if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) {
  567. return http_client_redirect(req, resp);
  568. }
  569. return 0;
  570. }
  571. int http_client_send(HttpRequest* req, HttpResponse* resp) {
  572. if (!req || !resp) return ERR_NULL_POINTER;
  573. http_client_t cli;
  574. return http_client_send(&cli, req, resp);
  575. }
  576. // below for async
  577. static int http_client_exec_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  578. if (cli->async_client_ == NULL) {
  579. cli->mutex_.lock();
  580. if (cli->async_client_ == NULL) {
  581. cli->async_client_.reset(new hv::AsyncHttpClient);
  582. }
  583. cli->mutex_.unlock();
  584. }
  585. return cli->async_client_->send(req, std::move(resp_cb));
  586. }
  587. int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) {
  588. if (!cli || !req) return ERR_NULL_POINTER;
  589. http_client_make_request(cli, req.get());
  590. return http_client_exec_async(cli, req, std::move(resp_cb));
  591. }
  592. static http_client_t* s_async_http_client = NULL;
  593. static void hv_destroy_default_async_http_client() {
  594. hlogi("destory default http async client");
  595. if (s_async_http_client) {
  596. http_client_del(s_async_http_client);
  597. s_async_http_client = NULL;
  598. }
  599. }
  600. static http_client_t* hv_default_async_http_client() {
  601. static std::mutex s_mutex;
  602. if (s_async_http_client == NULL) {
  603. s_mutex.lock();
  604. if (s_async_http_client == NULL) {
  605. hlogi("create default http async client");
  606. s_async_http_client = http_client_new();
  607. // NOTE: I have No better idea
  608. atexit(hv_destroy_default_async_http_client);
  609. }
  610. s_mutex.unlock();
  611. }
  612. return s_async_http_client;
  613. }
  614. int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
  615. if (req == NULL) return ERR_NULL_POINTER;
  616. if (req->timeout == 0) {
  617. req->timeout = DEFAULT_HTTP_TIMEOUT;
  618. }
  619. return http_client_exec_async(hv_default_async_http_client(), req, std::move(resp_cb));
  620. }