use crate::error::BaseError;
use crate::http::response::Response;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Method};
use serde::Serialize;
use std::time::Duration;
pub struct RequestBuilder {
client: Client,
method: Method,
url: String,
headers: HeaderMap,
header_errors: Vec<String>,
query_params: Vec<(String, String)>,
body: Option<Vec<u8>>,
timeout: Duration,
token: Option<String>,
}
impl RequestBuilder {
pub(crate) fn new(
client: Client,
method: Method,
url: String,
timeout: Duration,
token: Option<String>,
) -> Self {
Self {
client,
method,
url,
headers: HeaderMap::new(),
header_errors: Vec::new(),
query_params: Vec::new(),
body: None,
timeout,
token,
}
}
pub fn header(mut self, name: &str, value: &str) -> Self {
let header_name = match HeaderName::from_bytes(name.as_bytes()) {
Ok(n) => n,
Err(e) => {
self.header_errors
.push(format!("非法 header 名称 '{}': {}", name, e));
return self;
}
};
let header_value = match HeaderValue::from_str(value) {
Ok(v) => v,
Err(e) => {
self.header_errors
.push(format!("非法 header 值 '{}': {}", value, e));
return self;
}
};
self.headers.insert(header_name, header_value);
self
}
pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
for (name, value) in headers {
let header_name = match HeaderName::from_bytes(name.as_bytes()) {
Ok(n) => n,
Err(e) => {
self.header_errors
.push(format!("非法 header 名称 '{}': {}", name, e));
continue;
}
};
let header_value = match HeaderValue::from_str(value) {
Ok(v) => v,
Err(e) => {
self.header_errors
.push(format!("非法 header 值 '{}': {}", value, e));
continue;
}
};
self.headers.insert(header_name, header_value);
}
self
}
pub fn content_type(self, content_type: &str) -> Self {
self.header("Content-Type", content_type)
}
pub fn bearer_token(mut self, token: &str) -> Self {
self.token = Some(token.to_string());
self
}
pub fn user_agent(self, user_agent: &str) -> Self {
self.header("User-Agent", user_agent)
}
pub fn query(mut self, key: &str, value: &str) -> Self {
self.query_params.push((key.to_string(), value.to_string()));
self
}
pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
for (key, value) in params {
self.query_params.push((key.to_string(), value.to_string()));
}
self
}
pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
let json_bytes =
serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
self.body = Some(json_bytes);
self = self.content_type("application/json");
Ok(self)
}
pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
match serde_urlencoded::to_string(&form) {
Ok(encoded) => {
self.body = Some(encoded.into_bytes());
self = self.content_type("application/x-www-form-urlencoded");
}
Err(e) => {
self.header_errors
.push(format!("表单数据编码失败: {}", e));
}
}
self
}
pub fn body(mut self, body: Vec<u8>) -> Self {
self.body = Some(body);
self
}
pub fn text(mut self, text: &str) -> Self {
self.body = Some(text.as_bytes().to_vec());
self = self.content_type("text/plain");
self
}
pub fn timeout(mut self, timeout_secs: u64) -> Self {
self.timeout = Duration::from_secs(timeout_secs);
self
}
pub async fn send(self) -> Result<Response, BaseError> {
if !self.header_errors.is_empty() {
return Err(BaseError::ParamInvalid(
"header".to_string(),
self.header_errors.join("; "),
));
}
let mut request = self
.client
.request(self.method, &self.url)
.timeout(self.timeout);
request = request.headers(self.headers);
if let Some(token) = self.token {
request = request.bearer_auth(token);
}
if !self.query_params.is_empty() {
request = request.query(&self.query_params);
}
if let Some(body) = self.body {
request = request.body(body);
}
let response = request
.send()
.await
.map_err(BaseError::HttpRequestFailed)?;
Ok(Response::new(response))
}
}