Impl From for request::Error

This commit is contained in:
Kitaiti Makoto 2021-11-29 10:01:40 +09:00
parent a7d8d49faf
commit 48fab8ad2c

View file

@ -1,8 +1,10 @@
use chrono::{offset::Utc, DateTime}; use chrono::{offset::Utc, DateTime};
use openssl::hash::{Hasher, MessageDigest}; use openssl::hash::{Hasher, MessageDigest};
use reqwest::{ use reqwest::{
header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE, DATE, HOST, USER_AGENT}, header::{
ClientBuilder, Proxy, Response, Url, HeaderMap, HeaderValue, InvalidHeaderValue, ACCEPT, CONTENT_TYPE, DATE, HOST, USER_AGENT,
},
ClientBuilder, Proxy, Response, Url, UrlError,
}; };
use std::ops::Deref; use std::ops::Deref;
use std::time::SystemTime; use std::time::SystemTime;
@ -16,6 +18,24 @@ const PLUME_USER_AGENT: &str = concat!("Plume/", env!("CARGO_PKG_VERSION"));
#[derive(Debug)] #[derive(Debug)]
pub struct Error(); pub struct Error();
impl From<UrlError> for Error {
fn from(_err: UrlError) -> Self {
Error()
}
}
impl From<InvalidHeaderValue> for Error {
fn from(_err: InvalidHeaderValue) -> Self {
Error()
}
}
impl From<reqwest::Error> for Error {
fn from(_err: reqwest::Error) -> Self {
Error()
}
}
pub struct Digest(String); pub struct Digest(String);
impl Digest { impl Digest {
@ -169,12 +189,11 @@ pub fn signature(
pub fn get(url_str: &str, sender: &dyn Signer, proxy: Option<Proxy>) -> Result<Response, Error> { pub fn get(url_str: &str, sender: &dyn Signer, proxy: Option<Proxy>) -> Result<Response, Error> {
let mut headers = headers(); let mut headers = headers();
let url = Url::parse(url_str).map_err(|_| Error())?; // TODO: Define and use From trait let url = Url::parse(url_str)?;
if !url.has_host() { if !url.has_host() {
return Err(Error()); return Err(Error());
} }
let host_header_value = let host_header_value = HeaderValue::from_str(url.host_str().expect("Unreachable"))?;
HeaderValue::from_str(url.host_str().expect("Unreachable")).map_err(|_| Error())?;
headers.insert(HOST, host_header_value); headers.insert(HOST, host_header_value);
if let Some(proxy) = proxy { if let Some(proxy) = proxy {
ClientBuilder::new().proxy(proxy) ClientBuilder::new().proxy(proxy)
@ -182,13 +201,12 @@ pub fn get(url_str: &str, sender: &dyn Signer, proxy: Option<Proxy>) -> Result<R
ClientBuilder::new() ClientBuilder::new()
} }
.connect_timeout(Some(std::time::Duration::from_secs(5))) .connect_timeout(Some(std::time::Duration::from_secs(5)))
.build() .build()?
.map_err(|_| Error())?
.get(url_str) .get(url_str)
.headers(headers.clone()) .headers(headers.clone())
.header( .header(
"Signature", "Signature",
signature(sender, &headers, ("get", url.path(), url.query())).map_err(|_| Error())?, signature(sender, &headers, ("get", url.path(), url.query()))?,
) )
.send() .send()
.map_err(|_| Error()) .map_err(|_| Error())