use std::collections::HashMap;
use thiserror::Error;
#[derive(Debug, Clone)]
pub struct HttpRequest {
pub url: String,
pub headers: HashMap<String, String>,
pub body: Vec<u8>,
}
impl HttpRequest {
pub fn new(url: impl Into<String>) -> Self {
Self {
url: url.into(),
headers: HashMap::new(),
body: Vec::new(),
}
}
pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.insert(key.into(), value.into());
self
}
pub fn json_body(mut self, body: Vec<u8>) -> Self {
self.headers
.insert("Content-Type".to_owned(), "application/json".to_owned());
self.body = body;
self
}
}
#[derive(Debug, Clone)]
pub struct HttpResponse {
pub status: u16,
pub body: Vec<u8>,
}
impl HttpResponse {
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
serde_json::from_slice(&self.body)
}
pub fn is_success(&self) -> bool {
self.status >= 200 && self.status < 300
}
}
pub trait HttpClient {
type Error: std::error::Error + 'static;
fn post(
&self,
req: HttpRequest,
) -> impl std::future::Future<Output = Result<HttpResponse, Self::Error>>;
}
#[derive(Debug, Error)]
#[error("HTTP transport error: {0}")]
pub struct HttpError(pub String);