use http::Uri;
use std::ops::Deref;
#[derive(Debug)]
pub struct RequestBuilder {
method: http::Method,
uri: Uri,
version: http::Version,
headers: http::HeaderMap,
}
impl RequestBuilder {
pub fn method(self, method: http::Method) -> Self {
Self { method, ..self }
}
pub fn version(self, version: http::Version) -> Self {
Self { version, ..self }
}
pub fn uri(self, uri: Uri) -> Self {
Self { uri, ..self }
}
pub fn header<K>(self, name: K, value: &str) -> Self
where
K: http::header::IntoHeaderName,
{
let mut headers = self.headers;
headers.insert(
name,
value
.parse()
.unwrap(),
);
Self { headers, ..self }
}
pub fn empty(self) -> Result<Request, http::Error> {
Ok(Request {
method: self.method,
version: self.version,
uri: self.uri,
headers: self.headers,
body: None,
})
}
pub fn body(self, body: &str) -> Result<Request, http::Error> {
Ok(Request {
method: self.method,
version: self.version,
uri: self.uri,
headers: self.headers,
body: Some(body.to_string()),
})
}
}
#[derive(Debug, PartialEq)]
pub struct Request {
method: http::Method,
uri: Uri,
version: http::Version,
headers: http::HeaderMap,
body: Option<String>,
}
impl Request {
fn builder(method: http::Method, uri: Uri) -> RequestBuilder {
RequestBuilder {
method,
version: http::Version::HTTP_11,
uri,
headers: http::HeaderMap::new(),
}
}
pub fn get(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::GET, uri)
}
pub fn post(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::POST, uri)
}
pub fn put(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::PUT, uri)
}
pub fn delete(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::DELETE, uri)
}
pub fn patch(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::PATCH, uri)
}
pub fn head(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::HEAD, uri)
}
pub fn options(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::OPTIONS, uri)
}
pub fn trace(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::TRACE, uri)
}
pub fn connect(uri: Uri) -> RequestBuilder {
Self::builder(http::Method::CONNECT, uri)
}
pub fn from_parts(parts: http::request::Parts, body: String) -> Self {
Self {
method: parts.method,
version: parts.version,
uri: parts.uri,
headers: parts.headers,
body: Some(body),
}
}
pub fn method(&self) -> &http::Method {
&self.method
}
pub fn version(&self) -> &http::Version {
&self.version
}
pub fn path(&self) -> &str {
self.uri.path()
}
pub fn headers(&self) -> &http::HeaderMap {
&self.headers
}
pub fn body(&self) -> &Option<String> {
&self.body
}
}
impl Deref for Request {
type Target = Option<String>;
fn deref(&self) -> &Self::Target {
&self.body
}
}