fire_http_representation/response/
builder.rs

1use super::Response;
2use crate::body::Body;
3use crate::header::{
4	values::IntoHeaderName, ContentType, HeaderValue, HeaderValues,
5	ResponseHeader, StatusCode, CONTENT_LENGTH,
6};
7
8use std::fmt;
9
10/// A builder to create a `Response`.
11#[derive(Debug)]
12pub struct ResponseBuilder {
13	header: ResponseHeader,
14	body: Body,
15}
16
17impl ResponseBuilder {
18	/// Creates a new `ResponseBuilder`.
19	pub fn new() -> Self {
20		Self {
21			header: ResponseHeader::default(),
22			body: Body::new(),
23		}
24	}
25
26	/// Sets the status code.
27	pub fn status_code(mut self, status_code: StatusCode) -> Self {
28		self.header.status_code = status_code;
29		self
30	}
31
32	/// Sets the content type.
33	pub fn content_type(
34		mut self,
35		content_type: impl Into<ContentType>,
36	) -> Self {
37		self.header.content_type = content_type.into();
38		self
39	}
40
41	/// Sets a header value.
42	///
43	/// ## Note
44	/// Only ASCII characters are allowed, use
45	/// `self.values_mut().insert_encoded()` to allow any character.
46	///
47	/// ## Panics
48	/// If the value is not a valid `HeaderValue`.
49	pub fn header<K, V>(mut self, key: K, val: V) -> Self
50	where
51		K: IntoHeaderName,
52		V: TryInto<HeaderValue>,
53		V::Error: fmt::Debug,
54	{
55		self.values_mut().insert(key, val);
56		self
57	}
58
59	/// Returns `HeaderValues` mutably.
60	pub fn values_mut(&mut self) -> &mut HeaderValues {
61		&mut self.header.values
62	}
63
64	/// Sets the body dropping the previous one.
65	pub fn body(mut self, body: impl Into<Body>) -> Self {
66		self.body = body.into();
67		self
68	}
69
70	/// Builds a `Response`. Adding the `content-length` header
71	/// if the len of the body is known.
72	pub fn build(mut self) -> Response {
73		// lets calculate content-length
74		// if the body size is already known
75		if let Some(len) = self.body.len() {
76			self.values_mut().insert(CONTENT_LENGTH, len);
77		}
78
79		Response::new(self.header, self.body)
80	}
81}