atagen

jelq

public

an http based roguelike rpg about jelqing

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