use crate::{enums::RequestMethod, errors::ClientError};
use serde_json::Value;
use std::ops::RangeInclusive;
use url::Url;
const HTTP_SUCCESS_CODES: RangeInclusive<u16> = 200..=208;
pub trait Client {
fn send(&self, req: crate::client::Request) -> Result<crate::client::Response, ClientError>;
fn base(&self) -> &str;
fn execute(&self, req: Request) -> Result<Response, ClientError> {
log::info!(
"Client sending {:#?} request to {} with {} bytes of data",
req.method,
req.url,
req.body.len()
);
let response = self.send(req)?;
log::info!(
"Client received {} response from {} with {} bytes of body data",
response.code,
response.url,
response.body.len()
);
if !HTTP_SUCCESS_CODES.contains(&response.code) {
return Err(ClientError::ServerResponseError {
url: response.url.to_string(),
code: response.code,
content: String::from_utf8(response.body).ok(),
});
}
Ok(response)
}
}
#[derive(Debug, Clone)]
pub struct Request {
pub url: Url,
pub method: RequestMethod,
pub query: Vec<(String, Value)>,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct Response {
pub url: Url,
pub code: u16,
pub body: Vec<u8>,
}