atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
b85a0d4536c3b294547a682ac046d8a38beb47a3
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/response.rsRust48 lines1.7 KB
1
use axum::{
2
    Json,
3
    http::{HeaderValue, StatusCode, header},
4
    response::{IntoResponse, Response},
5
};
6
7
use crate::game::{Outcome, Payload};
8
9
impl IntoResponse for Outcome {
10
    fn into_response(self) -> Response {
11
        let mut response = match self.payload {
12
            // RFC 9110 §15.3.7 obliges a 206 to be a byte range of the full representation, so it is.
13
            Payload::Json(body) if self.status == StatusCode::PARTIAL_CONTENT => {
14
                let full = body.to_string().into_bytes();
15
                let half = full.len() / 2;
16
                let range = format!("bytes 0-{}/{}", half.saturating_sub(1), full.len());
17
                (
18
                    self.status,
19
                    [
20
                        (header::CONTENT_TYPE, "application/json".to_owned()),
21
                        (header::CONTENT_RANGE, range),
22
                    ],
23
                    full[..half].to_vec(),
24
                )
25
                    .into_response()
26
            }
27
            Payload::Json(body) => (self.status, Json(body)).into_response(),
28
            Payload::Raw(content_type, body) => {
29
                (self.status, [(header::CONTENT_TYPE, content_type)], body).into_response()
30
            }
31
            Payload::Empty => self.status.into_response(),
32
        };
33
        let headers = response.headers_mut();
34
        for (name, value) in self.headers {
35
            if let Ok(value) = HeaderValue::from_str(&value) {
36
                headers.append(name, value);
37
            }
38
        }
39
        response
40
    }
41
}
42
43
pub fn respond<T: IntoResponse, E: IntoResponse>(result: Result<T, E>) -> Response {
44
    match result {
45
        Ok(ok) => ok.into_response(),
46
        Err(err) => err.into_response(),
47
    }
48
}