atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
2026362c76a617af2cdca92573dd85e96c0abfb0
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/problem.rsRust87 lines2.5 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 document(&self) -> Map<String, Value> {
42
        let problem = &self.0;
43
        let mut body = Map::new();
44
        body.insert(
45
            "type".into(),
46
            json!(format!("{PROBLEM_BASE}{}", problem.slug)),
47
        );
48
        body.insert("title".into(), json!(reason(problem.status)));
49
        body.insert("status".into(), json!(problem.status.as_u16()));
50
        body.insert("detail".into(), json!(problem.detail));
51
        body.extend(problem.extensions.clone());
52
        body
53
    }
54
55
    pub fn header(mut self, name: HeaderName, value: impl AsRef<str>) -> Self {
56
        if let Ok(value) = HeaderValue::from_str(value.as_ref()) {
57
            self.0.headers.append(name, value);
58
        }
59
        self
60
    }
61
}
62
63
// The http crate still uses the RFC 7231 names for these.
64
pub fn reason(status: StatusCode) -> &'static str {
65
    match status.as_u16() {
66
        413 => "Content Too Large",
67
        422 => "Unprocessable Content",
68
        _ => status.canonical_reason().unwrap_or("Unknown"),
69
    }
70
}
71
72
impl IntoResponse for Problem {
73
    fn into_response(self) -> Response {
74
        let body = self.document();
75
        let problem = *self.0;
76
        let mut response = (problem.status, Json(body)).into_response();
77
        let headers = response.headers_mut();
78
        headers.insert(
79
            header::CONTENT_TYPE,
80
            HeaderValue::from_static("application/problem+json"),
81
        );
82
        for (name, value) in &problem.headers {
83
            headers.append(name, value.clone());
84
        }
85
        response
86
    }
87
}