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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::http::{self, HeaderValue, Mime, StatusCode};
use crate::internal_prelude::*;

use std::convert::TryFrom;

use futures::future::{self, Either, Ready};
use serde::Serialize;

#[derive(Debug)]
pub struct Response {
    inner: Box<HyperResponse>,
}

impl Response {
    pub(crate) fn from_hyper(res: HyperResponse) -> Self {
        Self {
            inner: Box::new(res),
        }
    }

    pub(crate) fn into_hyper(self) -> HyperResponse {
        *self.inner
    }

    #[allow(dead_code)]
    pub(crate) fn as_mut_hyper(&mut self) -> &mut HyperResponse {
        &mut *self.inner
    }

    pub fn new(status: StatusCode, body: Body) -> Self {
        let mut res = HyperResponse::new(body);
        *res.status_mut() = status;
        Self::from_hyper(res)
    }

    pub fn new_ok(body: Body) -> Self {
        Self::from_hyper(HyperResponse::new(body))
    }

    pub(crate) fn set_static_mime(&mut self, mime: &'static Mime) {
        self.inner.headers_mut().insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static(mime.as_ref()),
        );
    }
}

pub trait Responder: Send + Sync {
    type Future: Future<Output = Result<Response>> + Send;

    fn respond(self) -> Self::Future;
}

impl Responder for () {
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(Ok(Response::new_ok(Body::empty())))
    }
}

impl Responder for Response {
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(Ok(self))
    }
}

impl<T, E> Responder for Result<T, E>
where
    T: Responder,
    E: Into<Error> + Send + Sync,
{
    type Future = Either<T::Future, Ready<Result<Response>>>;

    fn respond(self) -> Self::Future {
        match self {
            Ok(res) => Either::Left(res.respond()),
            Err(err) => Either::Right(future::ready(Err(err.into()))),
        }
    }
}

fn text(s: impl Into<String>) -> Response {
    let mut res = Response::new_ok(Body::from(s.into()));
    res.set_static_mime(&mime::TEXT_PLAIN_UTF_8);
    res
}

impl<'a> Responder for &'a str {
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(Ok(text(self)))
    }
}

impl Responder for Box<str> {
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(Ok(text(self)))
    }
}

impl Responder for String {
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(Ok(text(self)))
    }
}

fn json<T>(status: StatusCode, value: T) -> Result<Response, serde_json::Error>
where
    T: Serialize,
{
    let bytes_vec = serde_json::to_vec(&value)?;
    let mut res = Response::new(status, Body::from(bytes_vec));
    res.set_static_mime(&mime::APPLICATION_JSON);
    Ok(res)
}

pub struct Json<T> {
    status: StatusCode,
    value: T,
}

impl<T> Json<T>
where
    T: Serialize,
{
    pub fn new(status: StatusCode, value: T) -> Self {
        Self { status, value }
    }

    pub fn ok(value: T) -> Self {
        Self {
            status: StatusCode::OK,
            value,
        }
    }
}

impl<T> From<Json<T>> for Result<Response>
where
    T: Serialize,
{
    fn from(this: Json<T>) -> Self {
        json(this.status, this.value).map_err(Into::into)
    }
}

impl<T> TryFrom<Json<T>> for Response
where
    T: Serialize,
{
    type Error = serde_json::Error;

    fn try_from(j: Json<T>) -> Result<Self, Self::Error> {
        json(j.status, j.value)
    }
}

impl<T> Responder for Json<T>
where
    T: Serialize + Send + Sync,
{
    type Future = Ready<Result<Response>>;

    fn respond(self) -> Self::Future {
        future::ready(json(self.status, self.value).map_err(Into::into))
    }
}