fibers_http_server/
request.rs

1use crate::{Error, ErrorKind, Result};
2use httpcodec::{Header, HttpVersion, Request};
3use std::fmt;
4use url::Url;
5
6/// HTTP request.
7#[derive(Debug)]
8pub struct Req<T> {
9    inner: Request<T>,
10    url: Url,
11}
12impl<T> Req<T> {
13    /// Returns the method of the request.
14    pub fn method(&self) -> &str {
15        self.inner.method().as_str()
16    }
17
18    /// Returns the URL of the request.
19    ///
20    /// Note that the peer address of the client socket is used as the host and port of the URL.
21    pub fn url(&self) -> &Url {
22        &self.url
23    }
24
25    /// Returns the HTTP version of the request.
26    pub fn version(&self) -> HttpVersion {
27        self.inner.http_version()
28    }
29
30    /// Returns the header of the response.
31    pub fn header(&self) -> Header {
32        self.inner.header()
33    }
34
35    /// Returns a reference to the body of the response.
36    pub fn body(&self) -> &T {
37        self.inner.body()
38    }
39
40    /// Takes ownership of the request, and returns its body.
41    pub fn into_body(self) -> T {
42        self.inner.into_body()
43    }
44
45    /// Splits the head part and the body part of the request.
46    pub fn take_body(self) -> (Req<()>, T) {
47        let (inner, body) = self.inner.take_body();
48        let req = Req {
49            inner,
50            url: self.url,
51        };
52        (req, body)
53    }
54
55    pub(crate) fn map_body<U, F>(self, f: F) -> Req<U>
56    where
57        F: FnOnce(T) -> U,
58    {
59        let inner = self.inner.map_body(f);
60        Req {
61            inner,
62            url: self.url,
63        }
64    }
65
66    pub(crate) fn new(inner: Request<T>, base_url: &Url) -> Result<Self> {
67        track_assert!(
68            inner.request_target().as_str().starts_with('/'),
69            ErrorKind::InvalidInput,
70            "path={:?}",
71            inner.request_target()
72        );
73        let url = track!(
74            Url::options()
75                .base_url(Some(base_url))
76                .parse(inner.request_target().as_str())
77                .map_err(Error::from),
78            "path={:?}",
79            inner.request_target()
80        )?;
81        Ok(Req { inner, url })
82    }
83}
84impl<T: fmt::Display> fmt::Display for Req<T> {
85    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86        self.inner.fmt(f)
87    }
88}