pub struct Request(_);Expand description
Represents an HTTP request.
An HTTP Request consists of a head (a version, a method, a path, and some headers), and a body (which may be empty). This type offers convenient helpers for constructing HTTP request for you for common use-cases.
The request also contains an “extensions” type map, which is used by under for containing routing information. It can also be used to insert state into the request for endpoints.
Examples
async fn respond_to(request: Request) -> Result<Response, anyhow::Error> {
if request.uri() != "/foo" {
return Ok(Response::empty_404());
}
Ok(Response::empty_204())
}Implementations§
source§impl Request
impl Request
sourcepub fn get<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn get<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the GET method and the given URI.
Examples
let request = Request::get("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::GET);sourcepub fn post<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn post<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the POST method and the given URI.
Examples
let request = Request::post("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::POST);sourcepub fn put<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn put<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the PUT method and the given URI.
Examples
let request = Request::put("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::PUT);sourcepub fn delete<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn delete<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the DELETE method and the given URI.
Examples
let request = Request::delete("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::DELETE);sourcepub fn head<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn head<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the HEAD method and the given URI.
Examples
let request = Request::head("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::HEAD);sourcepub fn trace<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn trace<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the TRACE method and the given URI.
Examples
let request = Request::trace("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::TRACE);sourcepub fn connect<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn connect<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the CONNECT method and the given URI.
Examples
let request = Request::connect("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::CONNECT);sourcepub fn patch<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn patch<U>(uri: U) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the PATCH method and the given URI.
Examples
let request = Request::patch("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::PATCH);sourcepub fn from_method<U>(uri: U, method: Method) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
pub fn from_method<U>(uri: U, method: Method) -> Result<Self, Error>where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<Error>,
Creates a new request initialized with the provided method and the given URI.
Errors
This method will return an error if the provided URI is invalid, or if the provided method is not a valid HTTP method.
Examples
let method = http::Method::from_bytes(b"TEST").unwrap();
let request = Request::from_method("https://example.com/a", method.clone()).unwrap();
assert_eq!(request.method(), method);sourcepub fn fragment<I: FromStr, K: FragmentSelect>(&self, key: K) -> Option<I>
pub fn fragment<I: FromStr, K: FragmentSelect>(&self, key: K) -> Option<I>
Retrieves a path fragment from the request, then attempts to parse it. The key can either be a number, or a string.
Examples
async fn point(request: Request) -> Response {
let target: u32 = request.fragment("amount").unwrap();
Response::text(format!("you bought {} coconuts", target))
}
let mut http = under::http();
http.at("/buy/{amount:uint}").get(point);
http.prepare();
let mut response = http.handle(Request::get("/buy/3")?).await?;
assert_eq!(response.status(), http::StatusCode::OK);
let body = response.data(512).into_text().await?;
assert_eq!(body, "you bought 3 coconuts");sourcepub fn fragment_str<K: FragmentSelect>(&self, key: K) -> Option<&str>
pub fn fragment_str<K: FragmentSelect>(&self, key: K) -> Option<&str>
Retrieves a path fragment from the request. The key can either be a number, or a string.
Examples
async fn point(request: Request) -> Response {
let target = request.fragment_str("target").unwrap();
Response::text(format!("hello, {}", target))
}
let mut http = under::http();
http.at("/hello/{target}").get(point);
http.prepare();
let mut response = http.handle(Request::get("/hello/foo")?).await?;
assert_eq!(response.status(), http::StatusCode::OK);
let body = response.data(512).into_text().await?;
assert_eq!(body, "hello, foo");sourcepub fn query<'q, S: Deserialize<'q>>(&'q self) -> Option<S>
Available on crate feature serde only.
pub fn query<'q, S: Deserialize<'q>>(&'q self) -> Option<S>
serde only.Parses the query string from the request into the provided type. If
there is no query string, then None is returned; or, if the query
string cannot be parsed into the given type, then None is also
returned.
Examples
let request = Request::get("/users?id=1").unwrap();
#[derive(serde::Deserialize)]
struct User { id: u32 }
let user: User = request.query().unwrap();
assert_eq!(user.id, 1);sourcepub fn peer_addr(&self) -> Option<SocketAddr>
pub fn peer_addr(&self) -> Option<SocketAddr>
Attempts to load the peer address of the request. This is only
available if loaded through the hyper service stack (i.e. the request
originates from crate::Router::listen), and so cannot garunteed
to be present.
Examples
async fn handle(request: Request) -> Response {
let peer = request.peer_addr();
match request.peer_addr() {
Some(addr) => Response::text(format!("{}", addr)),
None => Response::text("no peer address")
}
}
let mut http = under::http();
http.at("/").get(handle);
http.listen("0.0.0.0:8080").await?;sourcepub fn with_local_addr(self) -> Self
pub fn with_local_addr(self) -> Self
Sets the peer address of this request to a localhost address. This is only useful for testing, and should not be used in production. This allows you to test the request handling without having to bind to a port.
Examples
use std::net::SocketAddr;
let request = Request::get("/").unwrap()
.with_local_addr();
assert_eq!(request.peer_addr(), Some(SocketAddr::from(([127, 0, 0, 1], 0))));sourcepub fn remote(&self) -> Option<IpAddr>
👎Deprecated: use remote_address instead
pub fn remote(&self) -> Option<IpAddr>
Attempts to load the “remote” address for this request. This is determined in the following priority:
- The [
Forwardedheader]forkey, if present; - The first item of the first
X-Forwarded-Forheader, if present; - The peer address, if loaded through the hyper service stack (see
Self::peer_addr).
Note
The client may (maliciously) include either the Forwarded header
or the X-Forwarded-For header, if your reverse proxy does not filter
either. Be wary of this when configuring your reverse proxy to provide
the correct address.
Examples
use std::net::IpAddr;
let request = Request::get("/").unwrap()
.with_header("Forwarded", "for=10.0.0.3").unwrap();
assert_eq!(request.remote(), Some(IpAddr::from([10, 0, 0, 3])));use std::net::IpAddr;
let request = Request::get("/").unwrap()
.with_header("X-Forwarded-For", "10.0.0.3").unwrap();
assert_eq!(request.remote(), Some(IpAddr::from([10, 0, 0, 3])));use std::net::IpAddr;
let request = Request::get("/").unwrap()
.with_local_addr();
assert_eq!(request.remote(), Some(IpAddr::from([127, 0, 0, 1])));sourcepub fn remote_address(&self) -> RemoteAddress<'_>
pub fn remote_address(&self) -> RemoteAddress<'_>
Returns a builder that can be used to configure how to extract the
client’s IP address from the request. See RemoteAddress for more
information.
request.set_header("X-Forwarded-For", "1.1.1.1, 2.2.2.2, 3.3.3.3");
let ip = request.remote_address()
.trust_cloudflare_header()
.trust_forwarded_for(-1)
.trust_peer_address()
.apply();
assert_eq!(ip, Some(IpAddr::from([3, 3, 3, 3])));sourcepub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>
Returns state information provided by the
crate::middleware::StateMiddleware middleware. This is a
shortcut to retrieving the crate::middleware::State
extension from the request.
Examples
use under::middleware::State;
let mut request = Request::get("/").unwrap();
request.extensions_mut().insert(State(123u32));
assert_eq!(request.state::<u32>(), Some(&123u32));sourcepub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T>
Retrieves a specific extension from the extensions map. This is
the same as calling Self::extensions.get wit the given
type parameter.
Examples
let mut request = Request::get("/").unwrap();
assert_eq!(request.ext::<u32>(), None);sourcepub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
pub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
Retrieves a mutable reference to the specific extension from the
extensions map. This is the same as calling
Self::extensions_mut.get_mut with the given type
parameter.
Examples
let mut request = Request::get("/").unwrap();
assert_eq!(request.ext_mut::<u32>(), None);sourcepub fn set_ext<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self
pub fn set_ext<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self
Sets the value of the specific extension in the extensions map.
This is the same as calling Self::extensions_mut.insert
with the given parameter.
Examples
let mut request = Request::get("/").unwrap();
request.set_ext(123u32);
assert_eq!(request.ext::<u32>(), Some(&123u32));sourcepub fn with_ext<T: Send + Sync + 'static>(self, value: T) -> Self
pub fn with_ext<T: Send + Sync + 'static>(self, value: T) -> Self
Sets the value of the specific extension in the extensions map,
consuming self, and then returning the new value. This is
the same as calling Self::set_ext, but it consumes self.
Examples
let request = Request::get("/").unwrap();
let request = request.with_ext(123u32);
assert_eq!(request.ext::<u32>(), Some(&123u32));sourcepub fn remove_ext<T: Send + Sync + 'static>(&mut self) -> Option<T>
pub fn remove_ext<T: Send + Sync + 'static>(&mut self) -> Option<T>
Removes the specific extension from the extensions map. This is
the same as calling Self::extensions_mut.remove with the
given type parameter.
Examples
let mut request = Request::get("/").unwrap()
.with_ext(123u32);
assert_eq!(request.ext::<u32>(), Some(&123u32));
request.remove_ext::<u32>();
assert_eq!(request.ext::<u32>(), None);sourcepub fn without_ext<T: Send + Sync + 'static>(self) -> Self
pub fn without_ext<T: Send + Sync + 'static>(self) -> Self
Removes the specific extension from the extensions map,
consuming self, and then returning the removed value. This
is the same as calling Self::remove_ext, but it consumes
self.
Examples
let request = Request::get("/").unwrap()
.with_ext(123u32);
assert_eq!(request.ext::<u32>(), Some(&123u32));
let request = request.without_ext::<u32>();
assert_eq!(request.ext::<u32>(), None);sourcepub fn uri(&self) -> &Uri
pub fn uri(&self) -> &Uri
Returns a reference to the associated URI.
Examples
let request: Request = Request::get("/").unwrap();
assert_eq!(&*request.uri(), "/");sourcepub fn method(&self) -> &Method
pub fn method(&self) -> &Method
Returns a reference to the associated HTTP method.
Examples
let request: Request = Request::get("/").unwrap();
assert_eq!(*request.method(), http::Method::GET);sourcepub fn extensions(&self) -> &Extensions
pub fn extensions(&self) -> &Extensions
Returns a reference to the associated extensions.
Examples
let request: Request = Request::get("/").unwrap();
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::get("/").unwrap();
request.extensions_mut().insert("hello");
assert_eq!(request.extensions().get(), Some(&"hello"));Trait Implementations§
source§impl CookieExt for Request
impl CookieExt for Request
CookieMiddleware was not used), then this will return
None. Read moreCookieMiddleware was not used), then this will return
an empty cookie jar. Read moreself with the given cookie jar. This replaces (and drops)
the current cookie jar, if one exists. Read moreNone; if no cookie with the given name exists,
it returns None; otherwise, it returns its value. Read moreSelf::add_cookie.source§impl HttpEntity for Request
impl HttpEntity for Request
source§fn body_mut(&mut self) -> &mut Body
fn body_mut(&mut self) -> &mut Body
HasBody. Read moresource§fn headers(&self) -> &HeaderMap
fn headers(&self) -> &HeaderMap
source§fn headers_mut(&mut self) -> &mut HeaderMap
fn headers_mut(&mut self) -> &mut HeaderMap
source§fn set_body<I: Into<Body>>(&mut self, body: I) -> &mut Self
fn set_body<I: Into<Body>>(&mut self, body: I) -> &mut Self
source§fn with_body<I: Into<Body>>(self, body: I) -> Self
fn with_body<I: Into<Body>>(self, body: I) -> Self
self. This causes the previous body to be dropped in place. Read moresource§fn take_body(&mut self) -> Body
fn take_body(&mut self) -> Body
source§fn set_json<V: Serialize>(&mut self, new_body: &V) -> Result<&mut Self, Error>
fn set_json<V: Serialize>(&mut self, new_body: &V) -> Result<&mut Self, Error>
json only.source§fn with_json<V: Serialize>(self, new_body: &V) -> Result<Self, Error>
fn with_json<V: Serialize>(self, new_body: &V) -> Result<Self, Error>
json only.self. Note that this does not update the
Content-Type; the caller is responsible for that. Read moresource§fn data(&mut self, limit: u64) -> DataStream
fn data(&mut self, limit: u64) -> DataStream
source§fn header<H: AsHeaderName>(&self, key: H) -> Option<&HeaderValue>
fn header<H: AsHeaderName>(&self, key: H) -> Option<&HeaderValue>
source§fn header_all<H: AsHeaderName>(&self, key: H) -> GetAll<'_, HeaderValue>
fn header_all<H: AsHeaderName>(&self, key: H) -> GetAll<'_, HeaderValue>
source§fn set_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn set_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
source§fn with_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn with_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
self and returning a new version
with the given header. This can be useful for builder patterns.
Otherwise, this acts the same as Self::set_header.source§fn add_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn add_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
source§fn with_add_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn with_add_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
self and returning a new version
with the given header. This can be useful for builder patterns.
Otherwise, this acts the same as Self::add_header.source§fn content_type(&self) -> Option<Mime>
fn content_type(&self) -> Option<Mime>
Content-Type header of the request, and parsed into
a mime; if the header does not exist, or is not a proper mime type,
this will return None. Read moresource§fn as_sniff<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned,
Self: Send + 'async_trait,
'life0: 'async_trait,
fn as_sniff<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned,
Self: Send + 'async_trait,
'life0: 'async_trait,
serde only.json,
cbor, msgpack). If the content-type is one of those, it forwards
the call to the respective functions (DataStream::into_json,
[DataStream::into_cbor], [DataStream::into_msgpack]), thereby
consuming the body. If it cannot find the content type, or the content
type is not one of those, it will return an error. Read moresource§fn as_sniff_form<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned + FromForm,
Self: Send + 'async_trait,
'life0: 'async_trait,
fn as_sniff_form<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned + FromForm,
Self: Send + 'async_trait,
'life0: 'async_trait,
json,
cbor, msgpack), or x-www-form-urlencoded. If the content-type is
one of those, it forwards the call to the respective functions
(DataStream::into_json, [DataStream::into_cbor],
[DataStream::into_msgpack], DataStream::into_form), thereby
consuming the body. If it cannot find the content type, or the content
type is not one of those, it will return an error. Read more