Skip to main content

Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

An incoming request, already parsed and matched against a route.

Implementations§

Source§

impl Request

Source

pub fn flash(&self) -> Option<&Arc<dyn Flash>>

The flash store for this request, when something registered one.

Source

pub fn errors(&self) -> Json

The validation messages from the request that redirected here, as {"email": ["…"]} — empty when the last request did not fail.

Hand it to a template and read one field with a dotted path:

req.view("posts/create", &ViewContext::new()
    .with("errors", req.errors())
    .with("old", req.old()))
@if(errors.title)<p class="error">{{ errors.title.0 }}</p>@endif
<input name="title" value="{{ old.title }}">
Source

pub fn old(&self) -> Json

The input the failed request submitted, so a form can refill itself.

Never contains a password: old_input_of leaves those out, because re-filling a password field means putting the password back into HTML that ends up in caches, in history and in screenshots.

Source

pub fn old_field(&self, name: &str) -> String

One field of the old input, as a string. Empty when there is none.

Source

pub fn has_errors(&self) -> bool

Whether the last request left validation messages behind.

Source

pub fn previous_url(&self) -> String

Where a failed form should send the browser back to.

The page the session last recorded, then the Referer, then /. Both candidates are checked to be a path on this site: a full URL here would be an open redirect, which is how a phishing link borrows a real domain.

Source§

impl Request

Source

pub fn new(method: Method, target: impl Into<String>) -> Self

Build a request directly. This is what the test client and the server parser both go through.

Source

pub fn method(&self) -> Method

Source

pub fn path(&self) -> &str

The path with no query string: /users/7.

Source

pub fn target(&self) -> &str

The raw request target, query string included.

Source

pub fn route(&self) -> Option<&str>

The pattern this request matched: /users/{id}. Useful for metrics that must not explode into one series per id.

Source

pub fn headers(&self) -> &Headers

Source

pub fn headers_mut(&mut self) -> &mut Headers

Source

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

Source

pub fn body(&self) -> &[u8]

Source

pub fn body_string(&self) -> String

Source

pub fn context(&self) -> &Context

Source

pub fn config(&self) -> &Config

Source

pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>

A service for this request: req.state::<Database>().

This request’s own copy first, then the application’s. Middleware can put a T on the request with extend, and every handler that asks for a T from then on gets that one instead of the application-wide one. Nothing else changes: a request that was given nothing gets what main.rs registered, which is every request in an application that has no such middleware.

The case this exists for is one connection per tenant. An application serving a holding company and its subsidiaries resolves the tenant from the host or the signed-in user, opens or reuses that tenant’s Database, and calls req.extend(db). Every controller underneath goes on saying req.state::<Database>() and is talking to the right database without knowing that tenants exist. The alternative — threading a tenant::db(&req).await? through every handler — is the same program written five hundred more times, and it only takes one missed call site to read another company’s data.

This is a lookup order, not discovery. The rule against runtime magic is about things that happen with no line you can find: reflection, auto-registration, a scan of a directory. The middleware that overrides a service is an ordinary explicit line in main.rs, and the rule here is one sentence long. What it must not become is a way for a value to appear from nowhere.

Source

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

Source

pub fn ip(&self) -> Option<String>

The client IP, honouring X-Forwarded-For when behind a proxy. The client’s address.

The address that opened the socket, unless TrustProxies ran and the connection came from a proxy on its list — then it is the client address that proxy reported.

It deliberately does not read X-Forwarded-For on its own. A header is something any client can send, so believing one unconditionally does not reveal the client’s address, it lets the client choose one — and everything keyed on this, the rate limiter included, would be defeated by a header.

Source

pub fn scheme(&self) -> &str

https when a trusted proxy said the client used TLS, or the connection itself did; http otherwise.

A proxy that terminates TLS forwards a plain request, so without this an application behind one would build http:// links for a site that is entirely https://.

Source

pub fn is_secure(&self) -> bool

Source

pub fn forwarded_host(&self) -> Option<&str>

The Host a trusted proxy said the client asked for.

Source

pub fn forwarded_port(&self) -> Option<u16>

The port a trusted proxy said the client connected to.

Source

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

A route parameter: for /users/{id} matching /users/7, param("id") is "7".

Source

pub fn param_as<T: FromStr>(&self, name: &str) -> Option<T>

A route parameter parsed into a type, so a handler can ask for an id as a number without unwrapping twice.

Source

pub fn params(&self) -> &BTreeMap<String, String>

Source

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

Source

pub fn query_all(&self, name: &str) -> Vec<&str>

Every value for a repeated query key: ?tag=a&tag=b.

Source

pub fn query_pairs(&self) -> &[(String, String)]

Source

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

Source

pub fn is_json(&self) -> bool

Source

pub fn wants_json(&self) -> bool

Whether the client wants JSON back — an API client or a fetch() call.

Source

pub fn json(&mut self) -> Option<&Json>

The body parsed as JSON, or None if it is absent or malformed.

Source

pub fn input(&mut self, name: &str) -> Option<String>

One input value, looked up in the JSON body, then the form body, then the query string — the resolution order of Laravel’s $request->input().

Source

pub fn inputs(&mut self, name: &str) -> Vec<String>

All decoded form fields of a application/x-www-form-urlencoded body. Every value submitted under one name.

A form with several checkboxes sharing a name — roles[], which is how PHP and every HTML tutorial spell it — sends the name once per ticked box. Request::input returns only the first, which for a checkbox group silently means “whichever happened to come first”.

A trailing [] is optional here: inputs("roles") and inputs("roles[]") both find them, because which one a form used is a detail of the markup rather than a decision the handler should have to track.

Source

pub fn form(&mut self) -> &[(String, String)]

Source

pub fn cookies(&self) -> BTreeMap<String, String>

Source

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

Source

pub fn extend<T: Send + Sync + 'static>(&mut self, value: T)

Attach a value for later middleware or the handler to read.

Source

pub fn api_version(&self) -> Option<&str>

The API version this request is for — from the route’s Router::version group, or from the VersionHeader middleware.

Source

pub fn request_id(&self) -> Option<&str>

The identifier the RequestId middleware assigned, for log lines and error reports.

Source

pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T>

Read a value attached by earlier middleware.

Source

pub fn with_peer(self, peer: SocketAddr) -> Self

Set the address the request arrived from, as the server does.

Source

pub fn with_header(self, name: &str, value: impl Into<String>) -> Self

Source

pub fn with_body(self, body: impl Into<Vec<u8>>) -> Self

Source

pub fn with_json(self, value: Json) -> Self

Source

pub fn with_form(self, fields: &[(&str, &str)]) -> Self

Source

pub fn with_context(self, context: Context) -> Self

Trait Implementations§

Source§

impl Debug for Request

Source§

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

Formats the value using the given formatter. 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, 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 = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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.