atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
a9b016e4b248ebfb4326a7881143856a1fe77252
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/problem.rsRust77 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 with(mut self, key: &str, value: impl Into<Value>) -> Self {
33
        self.0.extensions.insert(key.into(), value.into());
34
        self
35
    }
36
37
    pub fn header(mut self, name: HeaderName, value: impl AsRef<str>) -> Self {
38
        let value = HeaderValue::from_str(value.as_ref()).expect("header values are visible ascii");
39
        self.0.headers.append(name, value);
40
        self
41
    }
42
}
43
44
// The http crate still uses the RFC 7231 names for these.
45
fn title(status: StatusCode) -> &'static str {
46
    match status.as_u16() {
47
        413 => "Content Too Large",
48
        422 => "Unprocessable Content",
49
        _ => status.canonical_reason().unwrap_or("Unknown"),
50
    }
51
}
52
53
impl IntoResponse for Problem {
54
    fn into_response(self) -> Response {
55
        let problem = *self.0;
56
        let mut body = Map::new();
57
        body.insert(
58
            "type".into(),
59
            json!(format!("{PROBLEM_BASE}{}", problem.slug)),
60
        );
61
        body.insert("title".into(), json!(title(problem.status)));
62
        body.insert("status".into(), json!(problem.status.as_u16()));
63
        body.insert("detail".into(), json!(problem.detail));
64
        body.extend(problem.extensions);
65
66
        let mut response = (problem.status, Json(body)).into_response();
67
        let headers = response.headers_mut();
68
        headers.insert(
69
            header::CONTENT_TYPE,
70
            HeaderValue::from_static("application/problem+json"),
71
        );
72
        for (name, value) in &problem.headers {
73
            headers.append(name, value.clone());
74
        }
75
        response
76
    }
77
}