Refactor: Extract new_reqwest_client(_builder)

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-06-22 16:01:05 +10:00
parent a747edffd5
commit 8e92db3dc6
No known key found for this signature in database
GPG key ID: 591C0B03040416D6
2 changed files with 17 additions and 5 deletions

View file

@ -7,7 +7,9 @@ use tokio::task::JoinHandle;
use url::Url; use url::Url;
use super::Data; use super::Data;
use crate::{download_and_extract, remote_exists, BinstallError, PkgFmt}; use crate::{
download_and_extract, new_reqwest_client_builder, remote_exists, BinstallError, PkgFmt,
};
const BASE_URL: &str = "https://github.com/alsuren/cargo-quickinstall/releases/download"; const BASE_URL: &str = "https://github.com/alsuren/cargo-quickinstall/releases/download";
const STATS_URL: &str = "https://warehouse-clerk-tmp.vercel.app/api/crate"; const STATS_URL: &str = "https://warehouse-clerk-tmp.vercel.app/api/crate";
@ -89,7 +91,7 @@ impl QuickInstall {
let url = Url::parse(&stats_url)?; let url = Url::parse(&stats_url)?;
debug!("Sending installation report to quickinstall ({url})"); debug!("Sending installation report to quickinstall ({url})");
reqwest::Client::builder() new_reqwest_client_builder()
.user_agent(USER_AGENT) .user_agent(USER_AGENT)
.build()? .build()?
.request(Method::HEAD, url.clone()) .request(Method::HEAD, url.clone())

View file

@ -5,7 +5,7 @@ use bytes::Bytes;
use cargo_toml::Manifest; use cargo_toml::Manifest;
use futures_util::stream::Stream; use futures_util::stream::Stream;
use log::debug; use log::debug;
use reqwest::{Method, Response}; use reqwest::{Client, ClientBuilder, Method, Response};
use serde::Serialize; use serde::Serialize;
use tinytemplate::TinyTemplate; use tinytemplate::TinyTemplate;
use url::Url; use url::Url;
@ -40,8 +40,16 @@ pub fn load_manifest_path<P: AsRef<Path>>(
Ok(manifest) Ok(manifest)
} }
pub fn new_reqwest_client_builder() -> ClientBuilder {
ClientBuilder::new()
}
pub fn new_reqwest_client() -> reqwest::Result<Client> {
new_reqwest_client_builder().build()
}
pub async fn remote_exists(url: Url, method: Method) -> Result<bool, BinstallError> { pub async fn remote_exists(url: Url, method: Method) -> Result<bool, BinstallError> {
let req = reqwest::Client::new() let req = new_reqwest_client()?
.request(method.clone(), url.clone()) .request(method.clone(), url.clone())
.send() .send()
.await .await
@ -54,7 +62,9 @@ async fn create_request(
) -> Result<impl Stream<Item = reqwest::Result<Bytes>>, BinstallError> { ) -> Result<impl Stream<Item = reqwest::Result<Bytes>>, BinstallError> {
debug!("Downloading from: '{url}'"); debug!("Downloading from: '{url}'");
reqwest::get(url.clone()) new_reqwest_client()?
.get(url.clone())
.send()
.await .await
.and_then(|r| r.error_for_status()) .and_then(|r| r.error_for_status())
.map_err(|err| BinstallError::Http { .map_err(|err| BinstallError::Http {