pub struct Request { /* private fields */ }Expand description
Incoming HTTP request with an attached per-request Context.
Implementations§
Source§impl Request
impl Request
Sourcepub fn ctx(&self) -> &Context
pub fn ctx(&self) -> &Context
Read-only access to the per-request Context.
Examples found in repository?
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}Sourcepub fn query(&self) -> FormData
pub fn query(&self) -> FormData
Parse the URL query string into a FormData.
Returns an empty FormData when the request has no query string.
Look up a single cookie value by name.
Returns None if the request has no Cookie header, the header is
not valid UTF-8, or no cookie with this name is present. The value
is returned as-is (not URL-decoded).
Sourcepub fn into_parts(self) -> (Parts, Incoming, Context)
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>>§
Sourcepub fn method(&self) -> &Method
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?
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}Sourcepub fn method_mut(&mut self) -> &mut Method
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);Sourcepub fn uri(&self) -> &Uri
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?
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}Sourcepub fn uri_mut(&mut self) -> &mut Uri
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");Sourcepub fn version(&self) -> Version
pub fn version(&self) -> Version
Returns the associated version.
§Examples
let request: Request<()> = Request::default();
assert_eq!(request.version(), Version::HTTP_11);Sourcepub fn version_mut(&mut self) -> &mut Version
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);Sourcepub fn headers(&self) -> &HeaderMap
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());Sourcepub fn headers_mut(&mut self) -> &mut HeaderMap
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());Sourcepub fn extensions(&self) -> &Extensions
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());Sourcepub fn extensions_mut(&mut self) -> &mut Extensions
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"));Trait Implementations§
Auto Trait Implementations§
impl !Freeze for Request
impl !RefUnwindSafe for Request
impl Send for Request
impl Sync for Request
impl Unpin for Request
impl UnsafeUnpin for Request
impl !UnwindSafe for Request
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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