#[cfg(feature = "client")]
use reqwest::{
blocking::{Client, Response},
header::{self, HeaderMap, HeaderName, HeaderValue},
};
#[cfg(feature = "client")]
const CONTENT_JSON: &str = "application/json";
#[cfg(feature = "client")]
const CONTENT_FORM_URL_ENCODED: &str = "application/x-www-form-urlencoded";
#[derive(Debug, Copy, Clone)]
pub enum Method {
Get,
Post,
}
#[derive(Debug, Copy, Clone)]
pub enum ContentType {
FormUrlEncoded,
Json,
}
#[derive(Debug, Clone)]
pub struct UserAgent(pub String);
#[derive(Debug, Clone)]
pub struct Request {
pub url: String,
pub body: Option<String>,
pub content_type: Option<ContentType>,
pub user_agent: Option<UserAgent>,
pub headers: Option<Vec<(String, String)>>,
pub method: Method,
}
#[cfg(feature = "client")]
impl Request {
pub fn execute(&self, client: &Client) -> Result<Response, reqwest::Error> {
let mut builder = match self.method {
Method::Get => client.get(&self.url),
Method::Post => client.post(&self.url),
};
if let Some(agent) = self.user_agent.clone() {
builder = builder.header(header::USER_AGENT, agent.0);
}
if let Some(headers) = self.headers.clone() {
let mut map = HeaderMap::new();
for (name, value) in headers {
if let (Ok(n), Ok(v)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(&value),
) {
map.insert(n, v);
}
}
builder = builder.headers(map);
}
if let Some(content_type) = self.content_type {
builder = match content_type {
ContentType::Json => builder.header(header::CONTENT_TYPE, CONTENT_JSON),
ContentType::FormUrlEncoded => {
builder.header(header::CONTENT_TYPE, CONTENT_FORM_URL_ENCODED)
}
};
}
if let Some(body) = self.body.clone() {
builder = builder.body(body);
}
builder.send()
}
}