Skip to main content

rustio_core/
http.rs

1use std::ops::{Deref, DerefMut};
2
3use bytes::Bytes;
4use http_body_util::Full;
5
6use crate::context::Context;
7
8pub type Response = hyper::Response<Full<Bytes>>;
9
10pub struct Request {
11    inner: hyper::Request<hyper::body::Incoming>,
12    ctx: Context,
13}
14
15impl Request {
16    pub(crate) fn new(inner: hyper::Request<hyper::body::Incoming>) -> Self {
17        Self {
18            inner,
19            ctx: Context::new(),
20        }
21    }
22
23    pub fn ctx(&self) -> &Context {
24        &self.ctx
25    }
26
27    pub fn ctx_mut(&mut self) -> &mut Context {
28        &mut self.ctx
29    }
30
31    pub fn into_parts(
32        self,
33    ) -> (
34        hyper::http::request::Parts,
35        hyper::body::Incoming,
36        Context,
37    ) {
38        let (parts, body) = self.inner.into_parts();
39        (parts, body, self.ctx)
40    }
41}
42
43impl Deref for Request {
44    type Target = hyper::Request<hyper::body::Incoming>;
45    fn deref(&self) -> &Self::Target {
46        &self.inner
47    }
48}
49
50impl DerefMut for Request {
51    fn deref_mut(&mut self) -> &mut Self::Target {
52        &mut self.inner
53    }
54}
55
56pub fn text(body: impl Into<String>) -> Response {
57    response(200, "text/plain; charset=utf-8", body.into().into_bytes())
58}
59
60pub fn html(body: impl Into<String>) -> Response {
61    response(200, "text/html; charset=utf-8", body.into().into_bytes())
62}
63
64pub fn status_text(status: u16, body: impl Into<String>) -> Response {
65    response(status, "text/plain; charset=utf-8", body.into().into_bytes())
66}
67
68fn response(status: u16, content_type: &'static str, body: Vec<u8>) -> Response {
69    hyper::Response::builder()
70        .status(status)
71        .header("content-type", content_type)
72        .body(Full::new(Bytes::from(body)))
73        .expect("valid response")
74}