Skip to main content

Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

Incoming HTTP request with an attached per-request Context.

Implementations§

Source§

impl Request

Source

pub fn ctx(&self) -> &Context

Read-only access to the per-request Context.

Examples found in repository?
examples/homepage.rs (line 27)
24async fn logger(req: Request, next: Next) -> Result<Response, Error> {
25    let method = req.method().clone();
26    let path = req.uri().path().to_owned();
27    let id = req.ctx().get::<RequestId>().map(|r| r.0);
28    let user = rustio_core::auth::identity(req.ctx()).map(|i| i.user_id.clone());
29    let started = Instant::now();
30    let result = next.run(req).await;
31    let status = match &result {
32        Ok(resp) => resp.status().as_u16(),
33        Err(err) => err.status(),
34    };
35    let id_display = id.map(|i| format!("req-{i}")).unwrap_or_else(|| "-".into());
36    let user_display = user.unwrap_or_else(|| "-".into());
37    eprintln!(
38        "[{:>3}] {:>4} {} id={} user={} ({:?})",
39        status,
40        method,
41        path,
42        id_display,
43        user_display,
44        started.elapsed()
45    );
46    result
47}
48
49#[tokio::main]
50async fn main() -> std::io::Result<()> {
51    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
52    let router = with_defaults(Router::new())
53        .get("/whoami", |req, _params| async move {
54            let id = req
55                .ctx()
56                .get::<RequestId>()
57                .map(|r| r.0.to_string())
58                .unwrap_or_else(|| "unknown".into());
59            Ok::<Response, Error>(text(format!("your request id is req-{id}\n")))
60        })
61        .get("/me", |req, _params| async move {
62            let id = require_auth(req.ctx())?;
63            Ok::<Response, Error>(text(format!("hello {}\n", id.user_id)))
64        })
65        .get("/admin-only", |req, _params| async move {
66            let id = require_admin(req.ctx())?;
67            Ok::<Response, Error>(text(format!("hello admin {}\n", id.user_id)))
68        })
69        .get("/crash", |_req, _params| async {
70            Err::<Response, Error>(Error::Internal("simulated failure".into()))
71        })
72        .get("/unauth", |_req, _params| async {
73            Err::<Response, Error>(Error::Unauthorized)
74        })
75        .wrap(request_id)
76        .wrap(authenticate)
77        .wrap(logger);
78    Server::bind(addr).serve_router(router).await
79}
Source

pub fn ctx_mut(&mut self) -> &mut Context

Mutable access to the per-request Context.

Examples found in repository?
examples/homepage.rs (line 16)
14async fn request_id(mut req: Request, next: Next) -> Result<Response, Error> {
15    let id = REQUEST_COUNTER.fetch_add(1, Ordering::Relaxed);
16    req.ctx_mut().insert(RequestId(id));
17    let mut resp = resolve(next.run(req).await);
18    if let Ok(header) = format!("req-{id}").parse() {
19        resp.headers_mut().insert("x-request-id", header);
20    }
21    Ok(resp)
22}
Source

pub fn query(&self) -> FormData

Parse the URL query string into a FormData.

Returns an empty FormData when the request has no query string.

Source

pub fn into_parts(self) -> (Parts, Incoming, Context)

Consume this request, returning the underlying hyper parts, body, and the attached context.

Methods from Deref<Target = Request<Incoming>>§

Source

pub fn method(&self) -> &Method

Returns a reference to the associated HTTP method.

§Examples
let request: Request<()> = Request::default();
assert_eq!(*request.method(), Method::GET);
Examples found in repository?
examples/homepage.rs (line 25)
24async fn logger(req: Request, next: Next) -> Result<Response, Error> {
25    let method = req.method().clone();
26    let path = req.uri().path().to_owned();
27    let id = req.ctx().get::<RequestId>().map(|r| r.0);
28    let user = rustio_core::auth::identity(req.ctx()).map(|i| i.user_id.clone());
29    let started = Instant::now();
30    let result = next.run(req).await;
31    let status = match &result {
32        Ok(resp) => resp.status().as_u16(),
33        Err(err) => err.status(),
34    };
35    let id_display = id.map(|i| format!("req-{i}")).unwrap_or_else(|| "-".into());
36    let user_display = user.unwrap_or_else(|| "-".into());
37    eprintln!(
38        "[{:>3}] {:>4} {} id={} user={} ({:?})",
39        status,
40        method,
41        path,
42        id_display,
43        user_display,
44        started.elapsed()
45    );
46    result
47}
Source

pub fn method_mut(&mut self) -> &mut Method

Returns a mutable reference to the associated HTTP method.

§Examples
let mut request: Request<()> = Request::default();
*request.method_mut() = Method::PUT;
assert_eq!(*request.method(), Method::PUT);
Source

pub fn uri(&self) -> &Uri

Returns a reference to the associated URI.

§Examples
let request: Request<()> = Request::default();
assert_eq!(*request.uri(), *"/");
Examples found in repository?
examples/homepage.rs (line 26)
24async fn logger(req: Request, next: Next) -> Result<Response, Error> {
25    let method = req.method().clone();
26    let path = req.uri().path().to_owned();
27    let id = req.ctx().get::<RequestId>().map(|r| r.0);
28    let user = rustio_core::auth::identity(req.ctx()).map(|i| i.user_id.clone());
29    let started = Instant::now();
30    let result = next.run(req).await;
31    let status = match &result {
32        Ok(resp) => resp.status().as_u16(),
33        Err(err) => err.status(),
34    };
35    let id_display = id.map(|i| format!("req-{i}")).unwrap_or_else(|| "-".into());
36    let user_display = user.unwrap_or_else(|| "-".into());
37    eprintln!(
38        "[{:>3}] {:>4} {} id={} user={} ({:?})",
39        status,
40        method,
41        path,
42        id_display,
43        user_display,
44        started.elapsed()
45    );
46    result
47}
Source

pub fn uri_mut(&mut self) -> &mut Uri

Returns a mutable reference to the associated URI.

§Examples
let mut request: Request<()> = Request::default();
*request.uri_mut() = "/hello".parse().unwrap();
assert_eq!(*request.uri(), *"/hello");
Source

pub fn version(&self) -> Version

Returns the associated version.

§Examples
let request: Request<()> = Request::default();
assert_eq!(request.version(), Version::HTTP_11);
Source

pub fn version_mut(&mut self) -> &mut Version

Returns a mutable reference to the associated version.

§Examples
let mut request: Request<()> = Request::default();
*request.version_mut() = Version::HTTP_2;
assert_eq!(request.version(), Version::HTTP_2);
Source

pub fn headers(&self) -> &HeaderMap

Returns a reference to the associated header field map.

§Examples
let request: Request<()> = Request::default();
assert!(request.headers().is_empty());
Source

pub fn headers_mut(&mut self) -> &mut HeaderMap

Returns a mutable reference to the associated header field map.

§Examples
let mut request: Request<()> = Request::default();
request.headers_mut().insert(HOST, HeaderValue::from_static("world"));
assert!(!request.headers().is_empty());
Source

pub fn extensions(&self) -> &Extensions

Returns a reference to the associated extensions.

§Examples
let request: Request<()> = Request::default();
assert!(request.extensions().get::<i32>().is_none());
Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Returns a mutable reference to the associated extensions.

§Examples
let mut request: Request<()> = Request::default();
request.extensions_mut().insert("hello");
assert_eq!(request.extensions().get(), Some(&"hello"));
Source

pub fn body(&self) -> &T

Returns a reference to the associated HTTP body.

§Examples
let request: Request<String> = Request::default();
assert!(request.body().is_empty());
Source

pub fn body_mut(&mut self) -> &mut T

Returns a mutable reference to the associated HTTP body.

§Examples
let mut request: Request<String> = Request::default();
request.body_mut().push_str("hello world");
assert!(!request.body().is_empty());

Trait Implementations§

Source§

impl Deref for Request

Source§

type Target = Request<Incoming>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Request

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more