Struct rocket::Request

source ·
pub struct Request<'r> { /* private fields */ }
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§

source§

impl<'r> Request<'r>

source

pub fn method(&self) -> Method

Retrieve the method from self.

§Example
use rocket::http::Method;

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

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

Set the method of self.

§Example
use rocket::http::Method;

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

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

pub fn uri(&self) -> &Origin<'_>

Borrow the Origin URI from self.

§Example
assert_eq!(request.uri().path(), "/uri");
source

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

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(), Some("type=greeting"));
source

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

Returns the 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
assert!(request.remote().is_none());
source

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

Sets the remote address of self to address.

§Example

Set the remote address to be 127.0.0.1:8000:

use std::net::{SocketAddr, IpAddr, Ipv4Addr};

let (ip, port) = (IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8000);
let localhost = SocketAddr::new(ip, port);
request.set_remote(localhost);

assert_eq!(request.remote(), Some(localhost));
source

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

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

request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
assert_eq!(request.real_ip(), Some("8.8.8.8".parse().unwrap()));
source

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

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

pub fn cookies(&self) -> Cookies<'_>

Returns a wrapped borrow to the cookies in self.

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

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

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

Returns a HeaderMap of all of the headers in self.

§Example
let header_map = request.headers();
assert!(header_map.is_empty());
source

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

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

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

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("*/*"));

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

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

Returns the Content-Type header of self. If the header is not present, returns None. The Content-Type header is cached after the first call to this function. As a result, subsequent calls will always return the same value.

§Example
use rocket::http::ContentType;

request.add_header(ContentType::JSON);
assert_eq!(request.content_type(), Some(&ContentType::JSON));

// The header is cached; it cannot be replaced after first access.
request.replace_header(ContentType::HTML);
assert_eq!(request.content_type(), Some(&ContentType::JSON));
source

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

Returns the Accept header of self. If the header is not present, returns None. The Accept header is cached after the first call to this function. As a result, subsequent calls will always return the same value.

§Example
use rocket::http::Accept;

request.add_header(Accept::JSON);
assert_eq!(request.accept(), Some(&Accept::JSON));

// The header is cached; it cannot be replaced after first access.
request.replace_header(Accept::HTML);
assert_eq!(request.accept(), Some(&Accept::JSON));
source

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

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::{Method, Accept, ContentType, MediaType};

request.add_header(ContentType::JSON);
request.add_header(Accept::HTML);

request.set_method(Method::Get);
assert_eq!(request.format(), Some(&MediaType::HTML));

request.set_method(Method::Post);
assert_eq!(request.format(), Some(&MediaType::JSON));
source

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

Returns the configured application receive limits.

§Example
let json_limit = request.limits().get("json");
source

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

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

pub fn guard<'a, T: FromRequest<'a, 'r>>(&'a self) -> Outcome<T, T::Error>

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

§Example

Assuming a User request guard exists, invoke it:

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

Retrieve managed state inside of a guard implementation:

use rocket::State;

let pool = request.guard::<State<Pool>>();
source

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

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.

§Example
fn current_user(request: &Request) -> User {
    // Validate request for a given user, load from database, etc.
}

let user = request.local_cache(|| current_user(request));
source

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

Retrieves and parses into T the 0-indexed nth segment from the request. Returns None if n is greater than the number of 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
use rocket::http::{RawStr, uri::Origin};

fn string<'s>(req: &'s mut Request, uri: &'static str, n: usize) -> &'s RawStr {
    req.set_uri(Origin::parse(uri).unwrap());

    req.get_param(n)
        .and_then(|r| r.ok())
        .unwrap_or("unnamed".into())
}

assert_eq!(string(req, "/", 0).as_str(), "unnamed");
assert_eq!(string(req, "/a/b/this_one", 0).as_str(), "a");
assert_eq!(string(req, "/a/b/this_one", 1).as_str(), "b");
assert_eq!(string(req, "/a/b/this_one", 2).as_str(), "this_one");
assert_eq!(string(req, "/a/b/this_one", 3).as_str(), "unnamed");
assert_eq!(string(req, "/a/b/c/d/e/f/g/h", 7).as_str(), "h");
source

pub fn get_segments<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>
where T: FromSegments<'a>,

Retrieves and parses into T all of the path segments in the request URI beginning and including the 0-indexed nth non-empty segment. T must implement FromSegments, which is used to parse the segments.

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

§Error

If there are fewer than n non-empty segments, returns None. If parsing the segments failed, returns Some(Err(T:Error)).

§Example
use std::path::PathBuf;

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

fn path<'s>(req: &'s mut Request, uri: &'static str, n: usize) -> PathBuf {
    req.set_uri(Origin::parse(uri).unwrap());

    req.get_segments(n)
        .and_then(|r| r.ok())
        .unwrap_or_else(|| "whoops".into())
}

assert_eq!(path(req, "/", 0), PathBuf::from("whoops"));
assert_eq!(path(req, "/a/", 0), PathBuf::from("a"));
assert_eq!(path(req, "/a/b/c", 0), PathBuf::from("a/b/c"));
assert_eq!(path(req, "/a/b/c", 1), PathBuf::from("b/c"));
assert_eq!(path(req, "/a/b/c", 2), PathBuf::from("c"));
assert_eq!(path(req, "/a/b/c", 6), PathBuf::from("whoops"));
source

pub fn get_query_value<'a, T>( &'a self, key: &str ) -> Option<Result<T, T::Error>>
where T: FromFormValue<'a>,

Retrieves and parses into T the query value with key key. T must implement FromFormValue, which is used to parse the query’s value. Key matching is performed case-sensitively. If there are multiple pairs with key key, the last one is returned.

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

§Error

If a query segment with key key isn’t present, returns None. If parsing the value fails, returns Some(Err(T:Error)).

§Example
use std::path::PathBuf;
use rocket::http::{RawStr, uri::Origin};

fn value<'s>(req: &'s mut Request, uri: &'static str, key: &str) -> &'s RawStr {
    req.set_uri(Origin::parse(uri).unwrap());

    req.get_query_value(key)
        .and_then(|r| r.ok())
        .unwrap_or("n/a".into())
}

assert_eq!(value(req, "/?a=apple&z=zebra", "a").as_str(), "apple");
assert_eq!(value(req, "/?a=apple&z=zebra", "z").as_str(), "zebra");
assert_eq!(value(req, "/?a=apple&z=zebra", "A").as_str(), "n/a");
assert_eq!(value(req, "/?a=apple&z=zebra&a=argon", "a").as_str(), "argon");
assert_eq!(value(req, "/?a=1&a=2&a=3&b=4", "a").as_str(), "3");
assert_eq!(value(req, "/?a=apple&z=zebra", "apple").as_str(), "n/a");

Trait Implementations§

source§

impl<'r> Clone for Request<'r>

source§

fn clone(&self) -> Request<'r>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'r> Debug for Request<'r>

source§

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

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

impl<'r> Display for Request<'r>

source§

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

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

Auto Trait Implementations§

§

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

§

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§

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, I> AsResult<T, I> for T
where I: Input,

source§

fn as_result(self) -> Result<T, ParseErr<I>>

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, 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.

§

impl<T> IntoCollection<T> for T

§

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

Converts self into a collection.
§

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

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

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>,

§

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<T> Typeable for T
where T: Any,

source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
source§

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

source§

fn vzip(self) -> V