1use crate::cookies::Cookie;
4use crate::error::Error;
5use bytes::Bytes;
6use http::StatusCode;
7use serde::Serialize;
8
9pub struct Response {
11 pub status: StatusCode,
12 pub headers: http::HeaderMap,
13 pub body: Bytes,
14 cookies: Vec<Cookie>,
15 stream: Option<tokio::sync::mpsc::Receiver<Bytes>>,
16}
17
18pub(crate) type HyperBody = http_body_util::combinators::BoxBody<Bytes, std::convert::Infallible>;
20
21struct ChannelBody {
23 rx: tokio::sync::mpsc::Receiver<Bytes>,
24}
25
26impl hyper::body::Body for ChannelBody {
27 type Data = Bytes;
28 type Error = std::convert::Infallible;
29
30 fn poll_frame(
31 mut self: std::pin::Pin<&mut Self>,
32 cx: &mut std::task::Context<'_>,
33 ) -> std::task::Poll<Option<std::result::Result<hyper::body::Frame<Bytes>, Self::Error>>> {
34 self.rx
35 .poll_recv(cx)
36 .map(|chunk| chunk.map(|b| Ok(hyper::body::Frame::data(b))))
37 }
38}
39
40impl Response {
41 pub fn new(status: StatusCode) -> Self {
42 Self {
43 status,
44 headers: http::HeaderMap::new(),
45 body: Bytes::new(),
46 cookies: Vec::new(),
47 stream: None,
48 }
49 }
50
51 pub fn stream() -> (crate::stream::BodySender, Self) {
75 let (tx, rx) = tokio::sync::mpsc::channel(16);
76 let mut res = Self::ok();
77 res.stream = Some(rx);
78 (crate::stream::BodySender::new(tx), res)
79 }
80
81 pub fn is_streaming(&self) -> bool {
83 self.stream.is_some()
84 }
85
86 pub fn cookie(mut self, cookie: Cookie) -> Self {
88 self.cookies.push(cookie);
89 self
90 }
91
92 pub fn ok() -> Self {
93 Self::new(StatusCode::OK)
94 }
95
96 pub fn with_status(mut self, status: StatusCode) -> Self {
97 self.status = status;
98 self
99 }
100
101 pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
102 self.body = body.into();
103 self
104 }
105
106 pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
107 let key = key.into();
108 let value = value.into();
109
110 if let (Ok(header_name), Ok(header_value)) = (
112 http::HeaderName::from_bytes(key.as_bytes()),
113 http::HeaderValue::from_str(&value),
114 ) {
115 self.headers.insert(header_name, header_value);
116 } else {
117 eprintln!("Warning: Invalid header {}={}", key, value);
118 }
119 self
120 }
121
122 pub fn json<T: Serialize>(data: T) -> Self {
123 match serde_json::to_vec(&data) {
124 Ok(body) => Self::ok()
125 .with_header("content-type", "application/json")
126 .with_body(body),
127 Err(e) => {
128 eprintln!("JSON serialization error: {}", e);
129 Self::new(StatusCode::INTERNAL_SERVER_ERROR)
130 .with_header("content-type", "application/json")
131 .with_body("{\"error\":\"Internal serialization error\"}")
132 }
133 }
134 }
135
136 pub fn text(text: impl Into<String>) -> Self {
137 Self::ok()
138 .with_header("content-type", "text/plain")
139 .with_body(text.into())
140 }
141
142 pub fn html(html: impl Into<String>) -> Self {
144 Self::ok()
145 .with_header("content-type", "text/html; charset=utf-8")
146 .with_body(html.into())
147 }
148
149 pub fn redirect(location: impl Into<String>) -> Self {
151 Self::new(StatusCode::SEE_OTHER).with_header("location", location)
152 }
153
154 pub fn redirect_permanent(location: impl Into<String>) -> Self {
156 Self::new(StatusCode::PERMANENT_REDIRECT).with_header("location", location)
157 }
158
159 pub fn from_error(error: Error) -> Self {
160 let status = error.status();
161 let mut body = serde_json::json!({
162 "error": error.message(),
163 "status": error.status_code(),
164 });
165 if let Error::Validation(fields) = &error {
166 let mut by_field = serde_json::Map::new();
168 for f in fields {
169 if let Some(list) = by_field
170 .entry(f.field.clone())
171 .or_insert_with(|| serde_json::Value::Array(Vec::new()))
172 .as_array_mut()
173 {
174 list.push(serde_json::Value::String(f.message.clone()));
175 }
176 }
177 body["fields"] = serde_json::Value::Object(by_field);
178 }
179 let body_bytes =
180 serde_json::to_vec(&body).unwrap_or_else(|_| b"{\"error\":\"Unknown error\"}".to_vec());
181 Self::new(status)
182 .with_header("content-type", "application/json")
183 .with_body(body_bytes)
184 }
185
186 pub(crate) fn into_hyper(self) -> hyper::Response<HyperBody> {
187 use http_body_util::BodyExt;
188 let mut builder = hyper::Response::builder().status(self.status);
189
190 for (key, value) in self.headers.iter() {
191 builder = builder.header(key, value);
192 }
193
194 for cookie in self.cookies {
196 builder = builder.header("set-cookie", cookie.to_header_value());
197 }
198
199 let body: HyperBody = match self.stream {
200 Some(rx) => ChannelBody { rx }.boxed(),
201 None => http_body_util::Full::new(self.body)
202 .map_err(|never| match never {})
203 .boxed(),
204 };
205 builder.body(body).unwrap_or_else(|e| {
206 eprintln!("Failed to build response: {}", e);
207 hyper::Response::builder()
208 .status(StatusCode::INTERNAL_SERVER_ERROR)
209 .body(
210 http_body_util::Full::new(Bytes::from("Internal Server Error"))
211 .map_err(|never| match never {})
212 .boxed(),
213 )
214 .unwrap()
215 })
216 }
217}
218
219pub struct Json<T>(pub T);
221
222impl<T: Serialize> From<Json<T>> for Response {
223 fn from(json: Json<T>) -> Self {
224 Response::json(json.0)
225 }
226}