aboutsummaryrefslogtreecommitdiff
path: root/src/response.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/response.rs')
-rw-r--r--src/response.rs60
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