atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
ef7d6dee59769add5c495a6bc02beb265fc01f56
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/ctx.rsRust90 lines2.7 KB
1
use std::{collections::HashMap, time::Instant};
2
3
use axum::{
4
    body::Bytes,
5
    extract::{FromRequest, FromRequestParts, Query, RawPathParams, Request},
6
    http::{HeaderMap, HeaderName, Method, StatusCode, Uri, Version, header},
7
    response::{IntoResponse, Response},
8
};
9
use hyper::upgrade::OnUpgrade;
10
11
use crate::problem::Problem;
12
13
const BODY_LIMIT: usize = 64 * 1024;
14
15
/// Everything a handler may look at, gathered once per request.
16
pub struct Ctx {
17
    pub method: Method,
18
    pub uri: Uri,
19
    pub version: Version,
20
    pub headers: HeaderMap,
21
    pub query: HashMap<String, String>,
22
    pub params: HashMap<String, String>,
23
    pub body: Bytes,
24
    pub now: Instant,
25
    pub upgrade: Option<OnUpgrade>,
26
}
27
28
impl Ctx {
29
    pub fn header(&self, name: HeaderName) -> Option<&str> {
30
        self.headers.get(name).and_then(|v| v.to_str().ok())
31
    }
32
33
    pub fn cookie(&self, name: &str) -> Option<&str> {
34
        self.headers
35
            .get_all(header::COOKIE)
36
            .iter()
37
            .filter_map(|v| v.to_str().ok())
38
            .flat_map(|v| v.split(';'))
39
            .filter_map(|pair| pair.trim().split_once('='))
40
            .find(|(key, _)| *key == name)
41
            .map(|(_, value)| value)
42
    }
43
44
    pub fn param(&self, name: &str) -> &str {
45
        self.params.get(name).map_or("", String::as_str)
46
    }
47
48
    pub fn query(&self, name: &str) -> Option<&str> {
49
        self.query.get(name).map(String::as_str)
50
    }
51
}
52
53
impl<S: Send + Sync> FromRequest<S> for Ctx {
54
    type Rejection = Response;
55
56
    async fn from_request(mut request: Request, state: &S) -> Result<Self, Self::Rejection> {
57
        let upgrade = request.extensions_mut().remove::<OnUpgrade>();
58
        let (mut parts, body) = request.into_parts();
59
        let params = RawPathParams::from_request_parts(&mut parts, state)
60
            .await
61
            .map(|raw| {
62
                raw.iter()
63
                    .map(|(k, v)| (k.to_owned(), v.to_owned()))
64
                    .collect()
65
            })
66
            .unwrap_or_default();
67
        let query = Query::<HashMap<String, String>>::try_from_uri(&parts.uri)
68
            .map(|q| q.0)
69
            .unwrap_or_default();
70
        let body = axum::body::to_bytes(body, BODY_LIMIT).await.map_err(|_| {
71
            Problem::new(
72
                StatusCode::PAYLOAD_TOO_LARGE,
73
                "body-too-large",
74
                "The request body is larger than anything the server is prepared to receive.",
75
            )
76
            .into_response()
77
        })?;
78
        Ok(Self {
79
            method: parts.method,
80
            uri: parts.uri,
81
            version: parts.version,
82
            headers: parts.headers,
83
            query,
84
            params,
85
            body,
86
            now: Instant::now(),
87
            upgrade,
88
        })
89
    }
90
}