atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
dfa38cf4cd4b9978f5ad92f39b2c735870aecaba
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/problem.rsRust81 lines2.3 KB
1
use axum::{
2
    Json,
3
    http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header},
4
    response::{IntoResponse, Response},
5
};
6
use serde_json::{Map, Value, json};
7
8
pub const PROBLEM_BASE: &str = "https://jelq.dev/problems/";
9
10
/// An RFC 9457 problem document.
11
pub struct Problem(Box<Inner>);
12
13
struct Inner {
14
    status: StatusCode,
15
    slug: &'static str,
16
    detail: String,
17
    extensions: Map<String, Value>,
18
    headers: HeaderMap,
19
}
20
21
impl Problem {
22
    pub fn new(status: StatusCode, slug: &'static str, detail: impl Into<String>) -> Self {
23
        Self(Box::new(Inner {
24
            status,
25
            slug,
26
            detail: detail.into(),
27
            extensions: Map::new(),
28
            headers: HeaderMap::new(),
29
        }))
30
    }
31
32
    pub fn status(&self) -> StatusCode {
33
        self.0.status
34
    }
35
36
    pub fn with(mut self, key: &str, value: impl Into<Value>) -> Self {
37
        self.0.extensions.insert(key.into(), value.into());
38
        self
39
    }
40
41
    pub fn header(mut self, name: HeaderName, value: impl AsRef<str>) -> Self {
42
        let value = HeaderValue::from_str(value.as_ref()).expect("header values are visible ascii");
43
        self.0.headers.append(name, value);
44
        self
45
    }
46
}
47
48
// The http crate still uses the RFC 7231 names for these.
49
fn title(status: StatusCode) -> &'static str {
50
    match status.as_u16() {
51
        413 => "Content Too Large",
52
        422 => "Unprocessable Content",
53
        _ => status.canonical_reason().unwrap_or("Unknown"),
54
    }
55
}
56
57
impl IntoResponse for Problem {
58
    fn into_response(self) -> Response {
59
        let problem = *self.0;
60
        let mut body = Map::new();
61
        body.insert(
62
            "type".into(),
63
            json!(format!("{PROBLEM_BASE}{}", problem.slug)),
64
        );
65
        body.insert("title".into(), json!(title(problem.status)));
66
        body.insert("status".into(), json!(problem.status.as_u16()));
67
        body.insert("detail".into(), json!(problem.detail));
68
        body.extend(problem.extensions);
69
70
        let mut response = (problem.status, Json(body)).into_response();
71
        let headers = response.headers_mut();
72
        headers.insert(
73
            header::CONTENT_TYPE,
74
            HeaderValue::from_static("application/problem+json"),
75
        );
76
        for (name, value) in &problem.headers {
77
            headers.append(name, value.clone());
78
        }
79
        response
80
    }
81
}