atagen

jelq

public

an http based roguelike rpg about jelqing

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