about summary refs log tree commit diff stats
path: root/src/web/responses.rs
blob: bcdcc0a8d8ee95aaf4e16afbd2cb3bd162841097 (plain) (blame)
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
// Back - An extremely simple git bug visualization system. Inspired by TVL's
// panettone.
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This file is part of Back.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/agpl.txt>.

use std::convert::Infallible;

use bytes::Bytes;
use http::{Response, StatusCode, Version};
use http_body_util::{BodyExt, Full, combinators::BoxBody};

use crate::{error, git_bug::format::HtmlString};

pub(super) fn html_response<T: Into<Bytes>>(html_text: T) -> Response<BoxBody<Bytes, Infallible>> {
    html_response_status(html_text, StatusCode::OK)
}

pub(super) fn html_response_status<T: Into<Bytes>>(
    html_text: T,
    status: StatusCode,
) -> Response<BoxBody<Bytes, Infallible>> {
    html_response_status_content_type(html_text, status, "text/html")
}

pub(super) fn html_response_status_content_type<T: Into<Bytes>>(
    html_text: T,
    status: StatusCode,
    content_type: &str,
) -> Response<BoxBody<Bytes, Infallible>> {
    Response::builder()
        .status(status)
        .version(Version::HTTP_2)
        .header("Content-Type", format!("{}; charset=utf-8", content_type))
        .header("x-content-type-options", "nosniff")
        .header("x-frame-options", "SAMEORIGIN")
        .body(full(html_text))
        .expect("This will always build")
}

fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, Infallible> {
    Full::new(chunk.into()).boxed()
}

// FIXME: Not all errors should return `INTERNAL_SERVER_ERROR`. <2025-03-08>
impl error::Error {
    pub fn into_response(self) -> Response<BoxBody<Bytes, Infallible>> {
        html_response_status(
            format!(
                "<h1> Internal server error. </h1> <pre>Error: {}</pre>",
                HtmlString::from(self.to_string())
            ),
            StatusCode::INTERNAL_SERVER_ERROR,
        )
    }
}