Struct rocket::Request[][src]

pub struct Request<'r> { /* fields omitted */ }
Expand description

The type of an incoming web request.

This should be used sparingly in Rocket applications. In particular, it should likely only be used when writing FromRequest implementations. It contains all of the information for a given web request except for the body data. This includes the HTTP method, URI, cookies, headers, and more.

Implementations

impl<'r> Request<'r>[src]

pub fn method(&self) -> Method[src]

Retrieve the method from self.

Example

use rocket::http::Method;

assert_eq!(get("/").method(), Method::Get);
assert_eq!(post("/").method(), Method::Post);

pub fn set_method(&mut self, method: Method)[src]

Set the method of self to method.

Example

use rocket::http::Method;

assert_eq!(request.method(), Method::Get);

request.set_method(Method::Post);
assert_eq!(request.method(), Method::Post);

pub fn uri(&self) -> &Origin<'r>[src]

Borrow the Origin URI from self.

Example

assert_eq!(get("/hello/rocketeer").uri().path(), "/hello/rocketeer");
assert_eq!(get("/hello").uri().query(), None);

pub fn set_uri(&mut self, uri: Origin<'r>)[src]

Set the URI in self to uri.

Example

use rocket::http::uri::Origin;

let uri = Origin::parse("/hello/Sergio?type=greeting").unwrap();
request.set_uri(uri);
assert_eq!(request.uri().path(), "/hello/Sergio");
assert_eq!(request.uri().query().unwrap(), "type=greeting");

let new_uri = request.uri().map_path(|p| format!("/foo{}", p)).unwrap();
request.set_uri(new_uri);
assert_eq!(request.uri().path(), "/foo/hello/Sergio");
assert_eq!(request.uri().query().unwrap(), "type=greeting");

pub fn remote(&self) -> Option<SocketAddr>[src]

Returns the raw address of the remote connection that initiated this request if the address is known. If the address is not known, None is returned.

Because it is common for proxies to forward connections for clients, the remote address may contain information about the proxy instead of the client. For this reason, proxies typically set the “X-Real-IP” header with the client’s true IP. To extract this IP from the request, use the real_ip() or client_ip() methods.

Example

use std::net::{SocketAddrV4, Ipv4Addr};

assert_eq!(request.remote(), None);

let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
request.set_remote(localhost);
assert_eq!(request.remote(), Some(localhost));

pub fn set_remote(&mut self, address: SocketAddr)[src]

Sets the remote address of self to address.

Example

Set the remote address to be 127.0.0.1:8000:

use std::net::{SocketAddrV4, Ipv4Addr};

assert_eq!(request.remote(), None);

let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
request.set_remote(localhost);
assert_eq!(request.remote(), Some(localhost));

pub fn real_ip(&self) -> Option<IpAddr>[src]

Returns the IP address in the “X-Real-IP” header of the request if such a header exists and contains a valid IP address.

Example

use std::net::Ipv4Addr;
use rocket::http::Header;

assert_eq!(req.real_ip(), None);

let req = req.header(Header::new("X-Real-IP", "127.0.0.1"));
assert_eq!(req.real_ip(), Some(Ipv4Addr::LOCALHOST.into()));

pub fn client_ip(&self) -> Option<IpAddr>[src]

Attempts to return the client’s IP address by first inspecting the “X-Real-IP” header and then using the remote connection’s IP address.

If the “X-Real-IP” header exists and contains a valid IP address, that address is returned. Otherwise, if the address of the remote connection is known, that address is returned. Otherwise, None is returned.

Example


// starting without an "X-Real-IP" header or remote addresss
assert!(request.client_ip().is_none());

// add a remote address; this is done by Rocket automatically
request.set_remote("127.0.0.1:8000".parse().unwrap());
assert_eq!(request.client_ip(), Some("127.0.0.1".parse().unwrap()));

// now with an X-Real-IP header
request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
assert_eq!(request.client_ip(), Some("8.8.8.8".parse().unwrap()));

pub fn cookies(&self) -> &CookieJar<'r>[src]

Returns a wrapped borrow to the cookies in self.

CookieJar implements internal mutability, so this method allows you to get and add/remove cookies in self.

Example

Add a new cookie to a request’s cookies:

use rocket::http::Cookie;

req.cookies().add(Cookie::new("key", "val"));
req.cookies().add(Cookie::new("ans", format!("life: {}", 38 + 4)));

assert_eq!(req.cookies().get_pending("key").unwrap().value(), "val");
assert_eq!(req.cookies().get_pending("ans").unwrap().value(), "life: 42");

pub fn headers(&self) -> &HeaderMap<'r>[src]

Returns a HeaderMap of all of the headers in self.

Example

use rocket::http::{Accept, ContentType};

assert!(get("/").headers().is_empty());

let req = get("/").header(Accept::HTML).header(ContentType::HTML);
assert_eq!(req.headers().len(), 2);

pub fn add_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)[src]

Add header to self’s headers. The type of header can be any type that implements the Into<Header> trait. This includes common types such as ContentType and Accept.

Example

use rocket::http::ContentType;

assert!(request.headers().is_empty());

request.add_header(ContentType::HTML);
assert!(request.headers().contains("Content-Type"));
assert_eq!(request.headers().len(), 1);

pub fn replace_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)[src]

Replaces the value of the header with name header.name with header.value. If no such header exists, header is added as a header to self.

Example

use rocket::http::ContentType;

assert!(request.headers().is_empty());

request.add_header(ContentType::Any);
assert_eq!(request.headers().get_one("Content-Type"), Some("*/*"));
assert_eq!(request.content_type(), Some(&ContentType::Any));

request.replace_header(ContentType::PNG);
assert_eq!(request.headers().get_one("Content-Type"), Some("image/png"));
assert_eq!(request.content_type(), Some(&ContentType::PNG));

pub fn content_type(&self) -> Option<&ContentType>[src]

Returns the Content-Type header of self. If the header is not present, returns None.

Example

use rocket::http::ContentType;

assert_eq!(get("/").content_type(), None);

let req = get("/").header(ContentType::JSON);
assert_eq!(req.content_type(), Some(&ContentType::JSON));

pub fn accept(&self) -> Option<&Accept>[src]

Returns the Accept header of self. If the header is not present, returns None.

Example

use rocket::http::Accept;

assert_eq!(get("/").accept(), None);
assert_eq!(get("/").header(Accept::JSON).accept(), Some(&Accept::JSON));

pub fn format(&self) -> Option<&MediaType>[src]

Returns the media type “format” of the request.

The “format” of a request is either the Content-Type, if the request methods indicates support for a payload, or the preferred media type in the Accept header otherwise. If the method indicates no payload and no Accept header is specified, a media type of Any is returned.

The media type returned from this method is used to match against the format route attribute.

Example

use rocket::http::{Accept, ContentType, MediaType};

// Non-payload-bearing: format is accept header.
let req = get("/").header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));

let req = get("/").header(ContentType::JSON).header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));

// Payload: format is content-type header.
let req = post("/").header(ContentType::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));

let req = post("/").header(ContentType::JSON).header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::JSON));

// Non-payload-bearing method and no accept header: `Any`.
assert_eq!(get("/").format(), Some(&MediaType::Any));

pub fn rocket(&self) -> &'r Rocket<Orbit>[src]

Returns the Rocket instance that is handling this request.

Example

// Retrieve the application config via `Rocket::config()`.
let config = request.rocket().config();

// Retrieve managed state via `Rocket::state()`.
let state = request.rocket().state::<Pool>();

// Get a list of all of the registered routes and catchers.
let routes = request.rocket().routes();
let catchers = request.rocket().catchers();

pub fn limits(&self) -> &'r Limits[src]

Returns the configured application data limits.

This is convenience function equivalent to:

&request.rocket().config().limits

Example

use rocket::data::ToByteUnit;

// This is the default `form` limit.
assert_eq!(request.limits().get("form"), Some(32.kibibytes()));

// Retrieve the limit for files with extension `.pdf`; etails to 1MiB.
assert_eq!(request.limits().get("file/pdf"), Some(1.mebibytes()));

pub fn route(&self) -> Option<&'r Route>[src]

Get the presently matched route, if any.

This method returns Some any time a handler or its guards are being invoked. This method returns None before routing has commenced; this includes during request fairing callbacks.

Example

let route = request.route();

pub fn guard<'z, 'a, T>(&'a self) -> BoxFuture<'z, Outcome<T, T::Error>> where
    T: FromRequest<'a> + 'z,
    'a: 'z,
    'r: 'z, 
[src]

Invokes the request guard implementation for T, returning its outcome.

Example

Assuming a User request guard exists, invoke it:

let outcome = request.guard::<User>().await;

pub fn local_cache<T, F>(&self, f: F) -> &T where
    F: FnOnce() -> T,
    T: Send + Sync + 'static, 
[src]

Retrieves the cached value for type T from the request-local cached state of self. If no such value has previously been cached for this request, f is called to produce the value which is subsequently returned.

Different values of the same type cannot be cached without using a proxy, wrapper type. To avoid the need to write these manually, or for libraries wishing to store values of public types, use the local_cache! macro to generate a locally anonymous wrapper type, store, and retrieve the wrapped value from request-local cache.

Example

// The first store into local cache for a given type wins.
let value = request.local_cache(|| "hello");
assert_eq!(*request.local_cache(|| "hello"), "hello");

// The following return the cached, previously stored value for the type.
assert_eq!(*request.local_cache(|| "goodbye"), "hello");

pub async fn local_cache_async<'a, T, F>(&'a self, fut: F) -> &'a T where
    F: Future<Output = T>,
    T: Send + Sync + 'static, 
[src]

Retrieves the cached value for type T from the request-local cached state of self. If no such value has previously been cached for this request, fut is awaited to produce the value which is subsequently returned.

Example

async fn current_user<'r>(request: &Request<'r>) -> User {
    // validate request for a given user, load from database, etc
}

let current_user = request.local_cache_async(async {
    current_user(&request).await
}).await;

pub fn param<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>> where
    T: FromParam<'a>, 
[src]

Retrieves and parses into T the 0-indexed nth non-empty segment from the routed request, that is, the nth segment after the mount point. If the request has not been routed, then this is simply the nth non-empty request URI segment.

Returns None if n is greater than the number of non-empty segments. Returns Some(Err(T::Error)) if the parameter type T failed to be parsed from the nth dynamic parameter.

This method exists only to be used by manual routing. To retrieve parameters from a request, use Rocket’s code generation facilities.

Example

assert_eq!(get("/a/b/c").param(0), Some(Ok("a")));
assert_eq!(get("/a/b/c").param(1), Some(Ok("b")));
assert_eq!(get("/a/b/c").param(2), Some(Ok("c")));
assert_eq!(get("/a/b/c").param::<&str>(3), None);

assert_eq!(get("/1/b/3").param(0), Some(Ok(1)));
assert!(get("/1/b/3").param::<usize>(1).unwrap().is_err());
assert_eq!(get("/1/b/3").param(2), Some(Ok(3)));

assert_eq!(get("/").param::<&str>(0), None);

pub fn segments<'a, T>(&'a self, n: RangeFrom<usize>) -> Result<T, T::Error> where
    T: FromSegments<'a>, 
[src]

Retrieves and parses into T all of the path segments in the request URI beginning and including the 0-indexed nth non-empty segment after the mount point.,that is, the nth segment after the mount point. If the request has not been routed, then this is simply the nth non-empty request URI segment.

T must implement FromSegments, which is used to parse the segments. If there are no non-empty segments, the Segments iterator will be empty.

This method exists only to be used by manual routing. To retrieve segments from a request, use Rocket’s code generation facilities.

Example

use std::path::PathBuf;

assert_eq!(get("/").segments(0..), Ok(PathBuf::new()));
assert_eq!(get("/").segments(2..), Ok(PathBuf::new()));

// Empty segments are skipped.
assert_eq!(get("///").segments(2..), Ok(PathBuf::new()));
assert_eq!(get("/a/b/c").segments(0..), Ok(PathBuf::from("a/b/c")));
assert_eq!(get("/a/b/c").segments(1..), Ok(PathBuf::from("b/c")));
assert_eq!(get("/a/b/c").segments(2..), Ok(PathBuf::from("c")));
assert_eq!(get("/a/b/c").segments(3..), Ok(PathBuf::new()));
assert_eq!(get("/a/b/c").segments(4..), Ok(PathBuf::new()));

pub fn query_value<'a, T>(&'a self, name: &str) -> Option<Result<'a, T>> where
    T: FromForm<'a>, 
[src]

Retrieves and parses into T the query value with field name name. T must implement FromForm, which is used to parse the query’s value. Key matching is performed case-sensitively.

Warning

This method exists only to be used by manual routing and should never be used in a regular Rocket application. It is much more expensive to use this method than to retrieve query parameters via Rocket’s codegen. To retrieve query values from a request, always prefer to use Rocket’s code generation facilities.

Error

If a query segment with name name isn’t present, returns None. If parsing the value fails, returns Some(Err(_)).

Example

use rocket::form::FromForm;

#[derive(Debug, PartialEq, FromForm)]
struct Dog<'r> {
    name: &'r str,
    age: usize
}

let req = get("/?a=apple&z=zebra&a=aardvark");
assert_eq!(req.query_value::<&str>("a").unwrap(), Ok("apple"));
assert_eq!(req.query_value::<&str>("z").unwrap(), Ok("zebra"));
assert_eq!(req.query_value::<&str>("b"), None);

let a_seq = req.query_value::<Vec<&str>>("a");
assert_eq!(a_seq.unwrap().unwrap(), ["apple", "aardvark"]);

let req = get("/?dog.name=Max+Fido&dog.age=3");
let dog = req.query_value::<Dog>("dog");
assert_eq!(dog.unwrap().unwrap(), Dog { name: "Max Fido", age: 3 });

Trait Implementations

impl Debug for Request<'_>[src]

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

Formats the value using the given formatter. Read more

impl Display for Request<'_>[src]

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

Pretty prints a Request. This is primarily used by Rocket’s logging infrastructure.

Auto Trait Implementations

impl<'r> !RefUnwindSafe for Request<'r>

impl<'r> Send for Request<'r>

impl<'r> Sync for Request<'r>

impl<'r> Unpin for Request<'r>

impl<'r> !UnwindSafe for Request<'r>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T> Instrument for T[src]

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

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

fn in_current_span(self) -> Instrumented<Self>[src]

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

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> IntoCollection<T> for T

pub fn into_collection<A>(self) -> SmallVec<A> where
    A: Array<Item = T>, 

Converts self into a collection.

pub fn mapped<U, F, A>(self, f: F) -> SmallVec<A> where
    F: FnMut(T) -> U,
    A: Array<Item = U>, 

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> ToString for T where
    T: Display + ?Sized
[src]

pub default fn to_string(&self) -> String[src]

Converts the given value to a String. Read more

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>, 

pub fn vzip(self) -> V