aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/pages/mod.rs
blob: 6145886bd4be4472d153e1681443638ee0751172 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use actix_web::{
    body::BoxBody,
    http::{
        header::{HeaderName, HeaderValue},
        StatusCode,
    },
    HttpResponseBuilder, Responder,
};
use std::fmt::Display;

pub mod home;
pub mod layout;
pub mod node;

struct HtmlTemplate<T>(pub T);

impl<T: markup::Render> Responder for HtmlTemplate<T> {
    type Body = BoxBody;

    fn respond_to(self, req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
        let mut out = String::new();
        self.0.render(&mut out).unwrap();

        HttpResponseBuilder::new(StatusCode::OK)
            .body(out)
            .respond_to(req)
    }
}

pub struct ContentType<T>(pub &'static str, pub T);

impl<T: Responder> Responder for ContentType<T> {
    type Body = T::Body;

    fn respond_to(self, req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
        let mut r = self.1.respond_to(req);
        r.headers_mut().insert(
            HeaderName::from_static("content-type"),
            HeaderValue::from_static(self.0),
        );
        r
    }
}

pub type MyResult<T> = actix_web::Result<T, MyError>;

#[derive(Debug)]
pub struct MyError(anyhow::Error);

impl Responder for MyError {
    type Body = BoxBody;
    fn respond_to(self, req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
        HttpResponseBuilder::new(StatusCode::BAD_REQUEST)
            .body(format!("error: {}", self.0))
            .respond_to(req)
    }
}
impl actix_web::error::ResponseError for MyError {
    fn status_code(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}
impl Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl From<anyhow::Error> for MyError {
    fn from(err: anyhow::Error) -> MyError {
        MyError(err)
    }
}
impl From<std::fmt::Error> for MyError {
    fn from(err: std::fmt::Error) -> MyError {
        MyError(anyhow::anyhow!("{err}"))
    }
}