fire_http_api/
response.rs

1use fire::{
2	extractor::Extractor,
3	extractor_extract, extractor_prepare, extractor_validate,
4	header::{values::IntoHeaderName, HeaderValue, HeaderValues, StatusCode},
5	state::StateRefCell,
6};
7
8use std::{convert::Infallible, fmt};
9
10#[derive(Debug, Clone)]
11pub struct ResponseSettings {
12	pub(crate) headers: HeaderValues,
13	pub(crate) status: StatusCode,
14}
15
16impl ResponseSettings {
17	#[doc(hidden)]
18	pub fn new() -> Self {
19		Self {
20			headers: HeaderValues::new(),
21			status: StatusCode::OK,
22		}
23	}
24
25	#[doc(hidden)]
26	pub fn new_for_state() -> StateRefCell<Self> {
27		StateRefCell::new(Self::new())
28	}
29
30	pub fn headers_mut(&mut self) -> &mut HeaderValues {
31		&mut self.headers
32	}
33
34	/// Sets a header value.
35	///
36	/// ## Note
37	/// Only ASCII characters are allowed, use
38	/// `self.headers_mut().encode_value()` to allow any character.
39	///
40	/// ## Panics
41	/// If the value is not a valid `HeaderValue`.
42	pub fn header<K, V>(&mut self, key: K, val: V) -> &mut Self
43	where
44		K: IntoHeaderName,
45		V: TryInto<HeaderValue>,
46		V::Error: fmt::Debug,
47	{
48		self.headers.insert(key, val);
49		self
50	}
51
52	pub fn status(&mut self, status: StatusCode) -> &mut Self {
53		self.status = status;
54		self
55	}
56}
57
58impl<'a, R> Extractor<'a, R> for &'a mut ResponseSettings {
59	type Error = Infallible;
60	type Prepared = ();
61
62	extractor_validate!(|validate| {
63		assert!(
64			validate.state.validate::<StateRefCell<ResponseSettings>>(),
65			"ResponseSettings not in state"
66		);
67	});
68
69	extractor_prepare!();
70
71	extractor_extract!(|extract| {
72		Ok(extract
73			.state
74			.get::<StateRefCell<ResponseSettings>>()
75			.unwrap()
76			.get_mut())
77	});
78}