use super::Response;
use crate::body::Body;
use crate::header::{
ResponseHeader, StatusCode, ContentType, HeaderValues, HeaderValue,
values::IntoHeaderName, CONTENT_LENGTH
};
use std::fmt;
#[derive(Debug)]
pub struct ResponseBuilder {
header: ResponseHeader,
body: Body
}
impl ResponseBuilder {
pub fn new() -> Self {
Self {
header: ResponseHeader::default(),
body: Body::new()
}
}
pub fn status_code(mut self, status_code: StatusCode) -> Self {
self.header.status_code = status_code;
self
}
pub fn content_type(
mut self,
content_type: impl Into<ContentType>
) -> Self {
self.header.content_type = content_type.into();
self
}
pub fn header<K, V>(mut self, key: K, val: V) -> Self
where
K: IntoHeaderName,
V: TryInto<HeaderValue>,
V::Error: fmt::Debug
{
self.values_mut().insert(key, val);
self
}
pub fn values_mut(&mut self) -> &mut HeaderValues {
&mut self.header.values
}
pub fn body(mut self, body: impl Into<Body>) -> Self {
self.body = body.into();
self
}
pub fn build(mut self) -> Response {
if let Some(len) = self.body.len() {
self.values_mut().insert(CONTENT_LENGTH, len);
}
Response::new(self.header, self.body)
}
}