zino_ntex/response/
mod.rs

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use ntex::{
    http::{
        body::Body,
        header::{self, HeaderName, HeaderValue},
        ResponseError, StatusCode,
    },
    web::{HttpRequest, HttpResponse, Responder, WebResponseError},
};
use std::fmt;
use zino_http::{
    response::{Rejection, Response, ResponseCode},
    timing::TimingMetric,
};

/// An HTTP response for `ntex`.
pub struct NtexResponse<S: ResponseCode = StatusCode>(Response<S>);

impl<S: ResponseCode> From<Response<S>> for NtexResponse<S> {
    #[inline]
    fn from(response: Response<S>) -> Self {
        Self(response)
    }
}

impl<S: ResponseCode> Responder for NtexResponse<S> {
    async fn respond_to(self, req: &HttpRequest) -> HttpResponse {
        let mut response = self.0;
        if !response.has_context() {
            let req = crate::Request::from(req.clone());
            response = response.context(&req);
        }

        let mut res = build_http_response(&mut response);
        for (key, value) in response.finalize() {
            if let Ok(header_name) = HeaderName::try_from(key.as_ref()) {
                if let Ok(header_value) = HeaderValue::try_from(value) {
                    res.headers_mut().insert(header_name, header_value);
                }
            }
        }

        res
    }
}

/// An HTTP rejection response for `ntex`.
pub struct NtexRejection(Response<StatusCode>);

impl fmt::Debug for NtexRejection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.message().unwrap_or("OK"))
    }
}

impl fmt::Display for NtexRejection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.status_code())
    }
}

impl From<Rejection> for NtexRejection {
    #[inline]
    fn from(rejection: Rejection) -> Self {
        Self(Response::from(rejection))
    }
}

impl ResponseError for NtexRejection {
    fn error_response(&self) -> HttpResponse {
        let mut response = self.0.clone();
        let mut res = build_http_response(&mut response);
        let request_id = response.request_id();
        if !request_id.is_nil() {
            if let Ok(header_value) = HeaderValue::try_from(request_id.to_string()) {
                let header_name = HeaderName::from_static("x-request-id");
                res.headers_mut().insert(header_name, header_value);
            }
        }

        let (traceparent, tracestate) = response.trace_context();
        if let Ok(header_value) = HeaderValue::try_from(traceparent) {
            let header_name = HeaderName::from_static("traceparent");
            res.headers_mut().insert(header_name, header_value);
        }
        if let Ok(header_value) = HeaderValue::try_from(tracestate) {
            let header_name = HeaderName::from_static("tracestate");
            res.headers_mut().insert(header_name, header_value);
        }

        let response_time = response.response_time();
        let timing = TimingMetric::new("total".into(), None, response_time.into());
        if let Ok(header_value) = HeaderValue::try_from(timing.to_string()) {
            let header_name = HeaderName::from_static("server-timing");
            res.headers_mut().insert(header_name, header_value);
        }

        for (key, value) in response.headers() {
            if let Ok(header_name) = HeaderName::try_from(key.as_ref()) {
                if let Ok(header_value) = HeaderValue::try_from(value) {
                    res.headers_mut().insert(header_name, header_value);
                }
            }
        }

        res
    }
}

impl WebResponseError for NtexRejection {
    #[inline]
    fn error_response(&self, _: &HttpRequest) -> HttpResponse {
        ResponseError::error_response(&self)
    }
}

/// Build http response from `zino_core::response::Response`.
fn build_http_response<S: ResponseCode>(response: &mut Response<S>) -> HttpResponse {
    match response.read_bytes() {
        Ok(data) => {
            let status_code = response
                .status_code()
                .try_into()
                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            let body = Body::from(data.to_vec());
            let mut res = HttpResponse::with_body(status_code, body);
            if let Ok(header_value) = HeaderValue::try_from(response.content_type()) {
                res.headers_mut().insert(header::CONTENT_TYPE, header_value);
            }
            res
        }
        Err(err) => {
            let status_code = StatusCode::INTERNAL_SERVER_ERROR;
            let body = Body::from(err.to_string());
            let mut res = HttpResponse::with_body(status_code, body);
            res.headers_mut().insert(
                header::CONTENT_TYPE,
                HeaderValue::from_static("text/plain; charset=utf-8"),
            );
            res
        }
    }
}