Skip to main content

luxid_core/http/
request.rs

1//! The owning request half of [`HttpContext`](crate::context::HttpContext).
2//!
3//! Luxid's `Request` owns its parts rather than borrowing salvo's. That is
4//! what allows actions to be written `async fn index(ctx: HttpContext)` with
5//! no lifetime parameter — edition 2024 makes elided lifetimes in paths a hard
6//! error (E0726), so a borrowing context would force `HttpContext<'_>`
7//! everywhere. Owning also keeps salvo entirely out of user-facing signatures.
8
9use std::collections::HashMap;
10use std::sync::OnceLock;
11
12use bytes::Bytes;
13use salvo::http::uri::Uri;
14use salvo::http::{HeaderMap, Method};
15use serde::de::DeserializeOwned;
16use serde_json::Value;
17
18use crate::error::{Error, Result};
19
20#[derive(Debug)]
21pub struct Request {
22    method: Method,
23    uri: Uri,
24    headers: HeaderMap,
25    queries: HashMap<String, Vec<String>>,
26    body: Bytes,
27    /// Parsed lazily: most requests never look at the JSON body, and a GET
28    /// should not pay for a parse attempt.
29    ///
30    /// `OnceLock` rather than `OnceCell` because `validate` borrows the request
31    /// across an await, and a future holding `&Request` is only `Send` if
32    /// `Request` is `Sync`.
33    json: OnceLock<Option<Value>>,
34}
35
36impl Request {
37    pub(crate) fn new(
38        method: Method,
39        uri: Uri,
40        headers: HeaderMap,
41        queries: HashMap<String, Vec<String>>,
42        body: Bytes,
43    ) -> Self {
44        Self {
45            method,
46            uri,
47            headers,
48            queries,
49            body,
50            json: OnceLock::new(),
51        }
52    }
53
54    pub fn method(&self) -> &Method {
55        &self.method
56    }
57
58    pub fn uri(&self) -> &Uri {
59        &self.uri
60    }
61
62    pub fn path(&self) -> &str {
63        self.uri.path()
64    }
65
66    pub fn headers(&self) -> &HeaderMap {
67        &self.headers
68    }
69
70    pub fn header(&self, name: &str) -> Option<&str> {
71        self.headers.get(name).and_then(|v| v.to_str().ok())
72    }
73
74    /// A cookie sent by the client.
75    ///
76    /// Parsed on demand from the `Cookie` header: most requests never ask, and
77    /// the ones that do usually ask once.
78    pub fn cookie(&self, name: &str) -> Option<&str> {
79        let header = self.header("cookie")?;
80
81        header.split(';').find_map(|pair| {
82            let (key, value) = pair.split_once('=')?;
83
84            (key.trim() == name).then(|| value.trim())
85        })
86    }
87
88    pub fn bearer_token(&self) -> Option<&str> {
89        self.header("authorization")?
90            .strip_prefix("Bearer ")
91            .map(str::trim)
92    }
93
94    pub fn body_bytes(&self) -> &Bytes {
95        &self.body
96    }
97
98    /// First value of a query-string key, decoded into `T`.
99    pub fn query<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
100        match self.queries.get(key).and_then(|values| values.first()) {
101            Some(raw) => decode_scalar(key, raw).map(Some),
102            None => Ok(None),
103        }
104    }
105
106    /// Every value of a repeated query-string key (`?tag=a&tag=b`).
107    pub fn query_all<T: DeserializeOwned>(&self, key: &str) -> Result<Vec<T>> {
108        self.queries
109            .get(key)
110            .map(|values| values.iter().map(|raw| decode_scalar(key, raw)).collect())
111            .unwrap_or_else(|| Ok(Vec::new()))
112    }
113
114    /// Query string first, then the JSON body — Adonis's `request.input()`.
115    pub fn input<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
116        if let Some(found) = self.query(key)? {
117            return Ok(Some(found));
118        }
119
120        match self.json_body().and_then(|json| json.get(key)) {
121            Some(value) => serde_json::from_value(value.clone())
122                .map(Some)
123                .map_err(|err| Error::BadRequest(format!("`{key}` in body: {err}"))),
124            None => Ok(None),
125        }
126    }
127
128    /// Deserialize the whole JSON body.
129    pub fn body_json<T: DeserializeOwned>(&self) -> Result<T> {
130        if self.body.is_empty() {
131            return Err(Error::BadRequest("a JSON body is required".into()));
132        }
133        Ok(serde_json::from_slice(&self.body)?)
134    }
135
136    /// Deserialize the JSON body and run its rules, or fail with a 422
137    /// listing every problem at once.
138    pub async fn validate<T>(&self) -> Result<T>
139    where
140        T: DeserializeOwned + crate::validation::Validate,
141    {
142        let value: T = self.body_json()?;
143        crate::validation::validate(&value).await?;
144
145        Ok(value)
146    }
147
148    fn json_body(&self) -> Option<&Value> {
149        self.json
150            .get_or_init(|| serde_json::from_slice(&self.body).ok())
151            .as_ref()
152    }
153}
154
155/// Query strings are untyped text, so `?page=2` must reach `u32` and
156/// `?name=ada` must reach `String`. Try the raw text as JSON first (which
157/// handles numbers, booleans and null), then fall back to treating it as a
158/// JSON string.
159pub(crate) fn decode_scalar<T: DeserializeOwned>(key: &str, raw: &str) -> Result<T> {
160    if let Ok(value) = serde_json::from_str::<T>(raw) {
161        return Ok(value);
162    }
163
164    serde_json::from_value(Value::String(raw.to_owned()))
165        .map_err(|err| Error::BadRequest(format!("`{key}` could not be read from `{raw}`: {err}")))
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn request(query: &[(&str, &str)], body: &str) -> Request {
173        let mut queries: HashMap<String, Vec<String>> = HashMap::new();
174        for (key, value) in query {
175            queries
176                .entry((*key).to_owned())
177                .or_default()
178                .push((*value).to_owned());
179        }
180
181        Request::new(
182            Method::POST,
183            "/users?x=1".parse().expect("valid uri"),
184            HeaderMap::new(),
185            queries,
186            Bytes::copy_from_slice(body.as_bytes()),
187        )
188    }
189
190    #[test]
191    fn decodes_typed_query_values() {
192        let req = request(&[("page", "2"), ("name", "ada"), ("active", "true")], "");
193
194        assert_eq!(req.query::<u32>("page").unwrap(), Some(2));
195        assert_eq!(req.query::<String>("name").unwrap(), Some("ada".into()));
196        assert_eq!(req.query::<bool>("active").unwrap(), Some(true));
197        assert_eq!(req.query::<u32>("missing").unwrap(), None);
198    }
199
200    #[test]
201    fn reports_undecodable_query_values() {
202        let req = request(&[("page", "not-a-number")], "");
203        let err = req.query::<u32>("page").unwrap_err();
204
205        assert_eq!(err.status_code(), salvo::http::StatusCode::BAD_REQUEST);
206        assert!(err.to_string().contains("page"));
207    }
208
209    #[test]
210    fn collects_repeated_query_values() {
211        let req = request(&[("tag", "a"), ("tag", "b")], "");
212        assert_eq!(req.query_all::<String>("tag").unwrap(), vec!["a", "b"]);
213    }
214
215    #[test]
216    fn input_prefers_query_then_falls_back_to_body() {
217        let req = request(&[("page", "9")], r#"{"page": 1, "search": "ada"}"#);
218
219        assert_eq!(req.input::<u32>("page").unwrap(), Some(9));
220        assert_eq!(req.input::<String>("search").unwrap(), Some("ada".into()));
221        assert_eq!(req.input::<String>("absent").unwrap(), None);
222    }
223
224    #[test]
225    fn body_json_rejects_an_empty_body() {
226        let err = request(&[], "").body_json::<Value>().unwrap_err();
227        assert_eq!(err.status_code(), salvo::http::StatusCode::BAD_REQUEST);
228    }
229
230    #[test]
231    fn extracts_a_bearer_token() {
232        let mut headers = HeaderMap::new();
233        headers.insert("authorization", "Bearer abc.def".parse().expect("header"));
234        let req = Request::new(
235            Method::GET,
236            "/".parse().expect("valid uri"),
237            headers,
238            HashMap::new(),
239            Bytes::new(),
240        );
241
242        assert_eq!(req.bearer_token(), Some("abc.def"));
243    }
244}