Skip to main content

luxid_core/http/
response.rs

1//! The owning response half of [`HttpContext`](crate::context::HttpContext).
2//!
3//! Builder methods return `Response`; terminal methods return
4//! `Result<Response>`, so an action ends naturally on `response.ok(users)`.
5//! The body stays a structured value rather than pre-serialized bytes so the
6//! Inertia adapter can later resolve the same action into either JSON or an
7//! HTML shell.
8
9use bytes::Bytes;
10use salvo::http::StatusCode;
11use serde::Serialize;
12use serde_json::Value;
13
14use crate::error::{Error, Result};
15
16/// A cookie to send with a response.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Cookie {
19    name: String,
20    value: String,
21    path: String,
22    max_age: Option<i64>,
23    http_only: bool,
24    secure: bool,
25    same_site: SameSite,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum SameSite {
30    Strict,
31    Lax,
32    None,
33}
34
35impl SameSite {
36    fn as_str(self) -> &'static str {
37        match self {
38            Self::Strict => "Strict",
39            Self::Lax => "Lax",
40            Self::None => "None",
41        }
42    }
43}
44
45impl Cookie {
46    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
47        Self {
48            name: name.into(),
49            value: value.into(),
50            path: "/".to_owned(),
51            max_age: None,
52            http_only: true,
53            secure: false,
54            same_site: SameSite::Lax,
55        }
56    }
57
58    /// A cookie that instructs the client to discard it.
59    pub fn removal(name: impl Into<String>) -> Self {
60        Self::new(name, "").max_age(0)
61    }
62
63    #[must_use]
64    pub fn path(mut self, path: impl Into<String>) -> Self {
65        self.path = path.into();
66        self
67    }
68
69    #[must_use]
70    pub fn max_age(mut self, seconds: i64) -> Self {
71        self.max_age = Some(seconds);
72        self
73    }
74
75    /// Allow JavaScript to read it. Rarely what you want.
76    #[must_use]
77    pub fn http_only(mut self, http_only: bool) -> Self {
78        self.http_only = http_only;
79        self
80    }
81
82    /// Send only over HTTPS. Should be on in production.
83    #[must_use]
84    pub fn secure(mut self, secure: bool) -> Self {
85        self.secure = secure;
86        self
87    }
88
89    #[must_use]
90    pub fn same_site(mut self, same_site: SameSite) -> Self {
91        self.same_site = same_site;
92        self
93    }
94
95    pub fn render(&self) -> String {
96        let mut out = format!("{}={}; Path={}", self.name, self.value, self.path);
97
98        if let Some(max_age) = self.max_age {
99            out.push_str(&format!("; Max-Age={max_age}"));
100        }
101        if self.http_only {
102            out.push_str("; HttpOnly");
103        }
104        if self.secure {
105            out.push_str("; Secure");
106        }
107
108        out.push_str(&format!("; SameSite={}", self.same_site.as_str()));
109        out
110    }
111}
112
113#[derive(Debug, Clone, PartialEq)]
114pub enum Body {
115    Empty,
116    Json(Value),
117    Bytes { data: Bytes, content_type: String },
118}
119
120#[derive(Debug)]
121pub struct Response {
122    pub(crate) status: StatusCode,
123    pub(crate) headers: Vec<(String, String)>,
124    pub(crate) body: Body,
125}
126
127impl Default for Response {
128    fn default() -> Self {
129        Self {
130            status: StatusCode::OK,
131            headers: Vec::new(),
132            body: Body::Empty,
133        }
134    }
135}
136
137impl Response {
138    // ---- builder methods -------------------------------------------------
139
140    /// Set the status. An out-of-range code is a programming error and is
141    /// surfaced as a 500 rather than a panic.
142    #[must_use]
143    pub fn status(mut self, code: u16) -> Self {
144        self.status = StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
145        self
146    }
147
148    /// Set a cookie.
149    ///
150    /// Defaults are the safe ones — `HttpOnly`, `SameSite=Lax`, `Path=/` — so a
151    /// session cookie is not reachable from JavaScript unless someone
152    /// deliberately makes it so.
153    #[must_use]
154    pub fn cookie(mut self, cookie: Cookie) -> Self {
155        self.headers
156            .push(("set-cookie".to_owned(), cookie.render()));
157        self
158    }
159
160    #[must_use]
161    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
162        self.headers.push((name.into(), value.into()));
163        self
164    }
165
166    // ---- terminal methods ------------------------------------------------
167
168    /// 200 with a JSON body.
169    pub fn ok<T: Serialize>(self, body: T) -> Result<Self> {
170        self.status(200).json(body)
171    }
172
173    /// 201 with a JSON body.
174    pub fn created<T: Serialize>(self, body: T) -> Result<Self> {
175        self.status(201).json(body)
176    }
177
178    /// 202 with a JSON body.
179    pub fn accepted<T: Serialize>(self, body: T) -> Result<Self> {
180        self.status(202).json(body)
181    }
182
183    /// 204, no body.
184    pub fn no_content(mut self) -> Result<Self> {
185        self.status = StatusCode::NO_CONTENT;
186        self.body = Body::Empty;
187        Ok(self)
188    }
189
190    /// JSON body, keeping whatever status is already set.
191    pub fn json<T: Serialize>(mut self, body: T) -> Result<Self> {
192        self.body = Body::Json(serde_json::to_value(body).map_err(|err| {
193            Error::Internal(anyhow::anyhow!("could not serialize response: {err}"))
194        })?);
195        Ok(self)
196    }
197
198    pub fn text(mut self, body: impl Into<String>) -> Result<Self> {
199        self.body = Body::Bytes {
200            data: Bytes::from(body.into()),
201            content_type: "text/plain; charset=utf-8".to_owned(),
202        };
203        Ok(self)
204    }
205
206    /// An HTML document. Used by the Inertia shell; also handy for a one-off
207    /// page that does not warrant a view layer.
208    pub fn html(self, body: impl Into<String>) -> Result<Self> {
209        self.bytes(body.into().into_bytes(), "text/html; charset=utf-8")
210    }
211
212    pub fn bytes(
213        mut self,
214        data: impl Into<Bytes>,
215        content_type: impl Into<String>,
216    ) -> Result<Self> {
217        self.body = Body::Bytes {
218            data: data.into(),
219            content_type: content_type.into(),
220        };
221        Ok(self)
222    }
223
224    /// 303 by default, which is what Inertia requires for PUT/PATCH/DELETE.
225    pub fn redirect(mut self, location: impl Into<String>) -> Result<Self> {
226        self.status = StatusCode::SEE_OTHER;
227        self.headers.push(("location".to_owned(), location.into()));
228        self.body = Body::Empty;
229        Ok(self)
230    }
231
232    // ---- accessors (used by the adapter and by tests) --------------------
233
234    pub fn status_code(&self) -> StatusCode {
235        self.status
236    }
237
238    pub fn body(&self) -> &Body {
239        &self.body
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use serde_json::json;
247
248    #[test]
249    fn ok_sets_200_and_a_json_body() {
250        let res = Response::default()
251            .ok(json!({ "id": 1 }))
252            .expect("serializes");
253
254        assert_eq!(res.status_code(), StatusCode::OK);
255        assert_eq!(res.body(), &Body::Json(json!({ "id": 1 })));
256    }
257
258    #[test]
259    fn created_sets_201() {
260        let res = Response::default()
261            .created(json!({ "id": 7 }))
262            .expect("serializes");
263        assert_eq!(res.status_code(), StatusCode::CREATED);
264    }
265
266    #[test]
267    fn builders_compose_before_a_terminal_method() {
268        let res = Response::default()
269            .status(207)
270            .header("x-trace", "abc")
271            .json(json!([]))
272            .expect("serializes");
273
274        assert_eq!(res.status_code().as_u16(), 207);
275        assert_eq!(res.headers, vec![("x-trace".to_owned(), "abc".to_owned())]);
276    }
277
278    #[test]
279    fn no_content_clears_the_body() {
280        let res = Response::default()
281            .ok(json!({ "a": 1 }))
282            .unwrap()
283            .no_content()
284            .unwrap();
285
286        assert_eq!(res.status_code(), StatusCode::NO_CONTENT);
287        assert_eq!(res.body(), &Body::Empty);
288    }
289
290    #[test]
291    fn an_invalid_status_becomes_500_rather_than_panicking() {
292        assert_eq!(
293            Response::default().status(9000).status_code(),
294            StatusCode::INTERNAL_SERVER_ERROR
295        );
296    }
297
298    #[test]
299    fn redirect_uses_303_and_sets_location() {
300        let res = Response::default().redirect("/users").expect("redirect");
301
302        assert_eq!(res.status_code(), StatusCode::SEE_OTHER);
303        assert_eq!(
304            res.headers,
305            vec![("location".to_owned(), "/users".to_owned())]
306        );
307    }
308}