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
|
//! Provides the [`SputnikBuilder`] trait.
use cookie::Cookie;
use hyper::{StatusCode, header::{self, HeaderValue}, http};
use time::{Duration, OffsetDateTime};
use hyper::http::response::Builder;
pub trait SputnikBuilder {
/// Adds a Set-Cookie header.
fn set_cookie(&mut self, cookie: Cookie);
/// Adds a Set-Cookie header to delete a cookie.
fn delete_cookie(&mut self, name: &str);
/// Sets the Content-Type.
fn content_type(self, mime: mime::Mime) -> Builder;
}
pub fn redirect(location: &str, code: StatusCode) -> Builder {
Builder::new().status(code).header(header::LOCATION, location)
}
impl SputnikBuilder for Builder {
fn set_cookie(&mut self, cookie: Cookie) {
self.headers_mut().unwrap().insert(header::SET_COOKIE, HeaderValue::from_str(&cookie.encoded().to_string()).unwrap());
}
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);
}
fn content_type(self, mime: mime::Mime) -> Self {
self.header(header::CONTENT_TYPE, mime.to_string())
}
}
pub trait EmptyBuilder<B> {
/// Consume the builder with an empty body.
fn empty(self) -> http::Result<http::response::Response<B>>;
}
impl EmptyBuilder<hyper::Body> for Builder {
fn empty(self) -> http::Result<http::response::Response<hyper::Body>> {
self.body(hyper::Body::empty())
}
}
|