aboutsummaryrefslogtreecommitdiff
path: root/src/response.rs
blob: 39e6c986d5e099f22aa179b28b1a0b82d6bac16e (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
//! Provides the [`Response`] convenience wrapper.

use cookie::Cookie;
use hyper::{StatusCode, header::{self, HeaderName, HeaderValue}};
use time::{Duration, OffsetDateTime};

type HyperResponse = hyper::Response<hyper::Body>;

/// Convenience wrapper around [`hyper::Response`].
pub struct Response {
    res: HyperResponse
}

impl Into<HyperResponse> for Response {
    fn into(self) -> HyperResponse {
        self.res
    }
}

impl Response {
    pub fn new() -> Self {
        Response{res: HyperResponse::new(hyper::Body::empty())}
    }

    pub fn status(&mut self) -> &mut StatusCode {
        self.res.status_mut()
    }

    pub fn body(&mut self) -> &mut hyper::Body {
        self.res.body_mut()
    }

    pub fn headers(&mut self) -> &mut hyper::HeaderMap<header::HeaderValue> {
        self.res.headers_mut()
    }

    pub fn set_header<S: AsRef<str>>(&mut self, header: HeaderName, value: S) {
        self.res.headers_mut().insert(header, HeaderValue::from_str(value.as_ref()).unwrap());
    }

    pub fn set_content_type(&mut self, mime: mime::Mime) {
        self.res.headers_mut().insert(header::CONTENT_TYPE, mime.to_string().parse().unwrap());
    }

    pub fn redirect<S: AsRef<str>>(&mut self, location: S, code: StatusCode) {
        *self.res.status_mut() = code;
        self.set_header(header::LOCATION, location);
    }

    pub fn set_cookie(&mut self, cookie: Cookie) {
        self.res.headers_mut().append(header::SET_COOKIE, cookie.encoded().to_string().parse().unwrap());
    }

    pub fn delete_cookie(&mut self, name: &str) {
        let mut cookie = Cookie::new(name, "");
        cookie.set_max_age(Duration::seconds(0));
        cookie.set_expires(OffsetDateTime::now_utc() - Duration::days(365));
        self.set_cookie(cookie);
    }
}