Request

Struct Request 

Source
pub struct Request(/* private fields */);
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

Source

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);
Source

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);
Source

pub fn options<U>(uri: U) -> Result<Self, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

Creates an ew request initialized with the OPTIONS metohd and the given URI.

§Examples
let request = Request::options("https://example.com/a").unwrap();
assert_eq!(request.method(), http::Method::OPTIONS);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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");
Source

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");
Source

pub fn query<'q, S: Deserialize<'q>>(&'q self) -> Option<S>

Available on crate feature 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);
Source

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?;
Source

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))));
Source

pub fn remote(&self) -> Option<IpAddr>

👎Deprecated: use remote_address instead

Attempts to load the “remote” address for this request. This is determined in the following priority:

  1. The [Forwarded header] for key, if present;
  2. The first item of the first X-Forwarded-For header, if present;
  3. 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])));
Source

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])));
Source

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));
Source

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);
Source

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);
Source

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));
Source

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));
Source

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);
Source

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);
Source

pub fn uri(&self) -> &Uri

Returns a reference to the associated URI.

§Examples
let request: Request = Request::get("/").unwrap();
assert_eq!(&*request.uri(), "/");
Source

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);
Source

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());
Source

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 Borrow<Request<Body>> for Request

Source§

fn borrow(&self) -> &Request<Body>

Immutably borrows from an owned value. Read more
Source§

impl BorrowMut<Request<Body>> for Request

Source§

fn borrow_mut(&mut self) -> &mut Request<Body>

Mutably borrows from an owned value. Read more
Source§

impl CookieExt for Request

Available on crate feature cookie only.
Source§

fn cookies(&self) -> Option<&CookieJar>

Returns the extracted cookie jar. If no cookie jar had been extracted (i.e., the CookieMiddleware was not used), then this will return None. Read more
Source§

fn cookies_mut(&mut self) -> &mut CookieJar

Returns the mutable cookie jar. If no cookie jar had been extracted (i.e. the CookieMiddleware was not used), then this will return an empty cookie jar. Read more
Source§

fn with_cookies(self, jar: CookieJar) -> Self

Returns self with the given cookie jar. This replaces (and drops) the current cookie jar, if one exists. Read more
Source§

fn cookie(&self, name: &str) -> Option<&str>

Returns the value for the cookie with the given name. If no cookie jar is set, it returns None; if no cookie with the given name exists, it returns None; otherwise, it returns its value. Read more
Adds the given cookie to the current cookie jar. This addition does add to the delta, and creates the cookie jar if it does not exist. Read more
Adds the given cookie to the cookie jar. This is essentially the same as Self::add_cookie.
Source§

impl Debug for Request

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Request<Body>> for Request

Source§

fn from(r: Request<Body>) -> Self

Converts to this type from the input type.
Source§

impl From<Request> for Request<Body>

Source§

fn from(r: Request) -> Self

Converts to this type from the input type.
Source§

impl HttpEntity for Request

Source§

fn body_mut(&mut self) -> &mut Body

Returns a mutable reference to the body of the request. This is used for all other methods in HttpEntity. Read more
Source§

fn headers(&self) -> &HeaderMap

Returns a reference to the associated header field map. This is used for all other methods in HttpEntity. Read more
Source§

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

Returns a mutable reference to the associated header field map. This is used for all other methods in HttpEntity. Read more
Source§

fn set_body<I: Into<Body>>(&mut self, body: I) -> &mut Self

Sets the body of the request to the given body. This causes the previous body to be dropped in place. Read more
Source§

fn with_body<I: Into<Body>>(self, body: I) -> Self

Sets the body of the request to the given body, consuming self. This causes the previous body to be dropped in place. Read more
Source§

fn take_body(&mut self) -> Body

Takes the body from this request, and replaces it with an empty body. The previous body is replaced with an empty body; thus, attempting to read the body more than once will cause successive attempts to fail. Read more
Source§

fn set_json<V: Serialize>(&mut self, new_body: &V) -> Result<&mut Self, Error>

Available on crate feature json only.
Replaces the contents of the body with the given JSON body. Note that this does not update the Content-Type; the caller is responsible for that. Read more
Source§

fn with_json<V: Serialize>(self, new_body: &V) -> Result<Self, Error>

Available on crate feature json only.
Replaces the contents of the body with the given JSON body, consuming self. Note that this does not update the Content-Type; the caller is responsible for that. Read more
Source§

fn data(&mut self, limit: u64) -> DataStream

Creates a data stream of the body. This consumes the body, and produces a stream that can then be read from. A limit must be provided, which is the maximum number of bytes that can be read from the stream. For most operations, exceeding this limit will cause an error. Read more
Source§

fn header<H: AsHeaderName>(&self, key: H) -> Option<&HeaderValue>

Retrieves the given header specified here. Read more
Source§

fn header_all<H: AsHeaderName>(&self, key: H) -> GetAll<'_, HeaderValue>

Retrieves all potential values for the given header specified here.
Source§

fn set_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>

Sets the given header to the given value. If there already was a header, it is replaced with the given value. Read more
Source§

fn with_header<H, V>(self, key: H, value: V) -> Result<Self, Error>

Sets the given header, consuming 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>

Sets the given header to the given value. If there already was a header, it is appended with the given value. Read more
Source§

fn with_add_header<H, V>(self, key: H, value: V) -> Result<Self, Error>

Sets the given header, consuming 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>

Retrieves the content type of the body. This is normally pulled from the 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 more
Source§

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,

Available on crate feature serde only.
Attempts to parse the body based off of the content-type header; currently, it can sniff any activated serde features (e.g. 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 more
Source§

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,

Available on crate features serde and from_form only.
Attempts to parse the body based off of the content type header; currently, it can sniff any activated serde features (e.g. 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

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, 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,