Struct under::Request

source ·
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§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns a reference to the associated URI.

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

Returns a reference to the associated HTTP method.

Examples
let request: Request = Request::get("/").unwrap();
assert_eq!(*request.method(), http::Method::GET);

Returns a reference to the associated extensions.

Examples
let request: Request = Request::get("/").unwrap();
assert!(request.extensions().get::<i32>().is_none());

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§

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
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
Returns self with the given cookie jar. This replaces (and drops) the current cookie jar, if one exists. Read more
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.
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Returns a mutable reference to the body of the request. This is used for all other methods in HasBody. Read more
Returns a reference to the associated header field map. Read more
Returns a mutable reference to the associated header field map. Read more
Sets the body of the request to the given body. This causes the previous body to be dropped in place. Read more
Sets the body of the request to the given body, consuming self. This causes the previous body to be dropped in place. Read more
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
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
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
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
Retrieves the given header specified here. Read more
Retrieves all potential values for the given header specified here.
Sets the given header to the given value. If there already was a header, it is replaced with the given value. Read more
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.
Sets the given header to the given value. If there already was a header, it is appended with the given value. Read more
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.
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
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
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§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more