diff options
author | Martin Fischer <martin@push-f.com> | 2021-01-18 10:03:50 +0100 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2021-01-18 10:17:10 +0100 |
commit | 9b2d39933f3403245f97247166818bef609a0125 (patch) | |
tree | e5819cf6314e357b7b37e23ae277cd2fea165afc /src/response.rs | |
parent | c27c5b3109e2b4fd8cdbe312f4925edc238a25e9 (diff) |
split Request wrapper into Parts & Bodyv0.2.0
Originally the into_ functions actually consumed the request but I
changed that to make request information like URI and method still
accessible after the request has been read.
Not consuming the Request however allows e.g. into_form() to be called
twice, which results in a panic since the body can only be read once.
This commit splits the Request wrapper into two wrappers Parts & Body,
allowing the borrow checker to guarantee that the body is only consumed
once, while keeping the other request information accessible after the
body has been consumed.
Version bumped to 0.2.0.
Diffstat (limited to 'src/response.rs')
-rw-r--r-- | src/response.rs | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/response.rs b/src/response.rs new file mode 100644 index 0000000..39e6c98 --- /dev/null +++ b/src/response.rs @@ -0,0 +1,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); + } +}
\ No newline at end of file |