Skip to main content

Request

Struct Request 

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

Represents an HTTP request.

Stores all the properties of the client’s request including URI, headers, body, method, cookies, path parameters, query parameters, and form data.

§Body Consumption and Caching

The request body can only be read once from the underlying stream. However, Salvo provides automatic caching mechanisms to allow multiple accesses:

  • payload() and payload_with_max_size() read the body and cache it internally. Subsequent calls return the cached bytes.
  • form_data() parses form data and caches the result. If the body has already been consumed by payload(), it will use the cached bytes to parse the form.

§Size Limits

To prevent denial-of-service attacks, the request body size is limited by default to 64KB. This can be configured using:

Note: Size limits apply to request body reads and form parsing, including multipart file uploads. Increase the limit if you need to accept large uploads.

§Examples

use salvo_core::http::Request;

// Create a new request
let req = Request::new();
assert_eq!(*req.method(), salvo_core::http::Method::GET);

Implementations§

Source§

impl Request

Source

pub fn new() -> Self

Creates a new blank Request

Source

pub fn from_hyper<B>(req: Request<B>, scheme: Scheme) -> Self
where B: Into<ReqBody>,

Creates a new Request from hyper::Request.

Source

pub fn uri(&self) -> &Uri

Returns a reference to the associated URI.

§Examples
let req = Request::default();
assert_eq!(*req.uri(), *"/");
Source

pub fn uri_mut(&mut self) -> &mut Uri

Returns a mutable reference to the associated URI.

Notice: If you using this mutable reference to change the uri, you should change the params and queries manually.

§Examples
let mut req: Request = Request::default();
*req.uri_mut() = "/hello".parse().unwrap();
assert_eq!(*req.uri(), *"/hello");
Source

pub fn set_uri(&mut self, uri: Uri)

Set the associated URI. queries will be reset.

Notice: params will not reset.

Source

pub fn method(&self) -> &Method

Returns a reference to the associated HTTP method.

§Examples
let req = Request::default();
assert_eq!(*req.method(), Method::GET);
Source

pub fn method_mut(&mut self) -> &mut Method

Returns a mutable reference to the associated HTTP method.

§Examples
let mut request: Request = Request::default();
*request.method_mut() = Method::PUT;
assert_eq!(*request.method(), Method::PUT);
Source

pub fn version(&self) -> Version

Returns the HTTP version of the request.

Common values are HTTP/1.0, HTTP/1.1, HTTP/2.0, and HTTP/3.0.

Source

pub fn version_mut(&mut self) -> &mut Version

Returns a mutable reference to the HTTP version.

Source

pub fn scheme(&self) -> &Scheme

Returns the URI scheme of the request (e.g., http or https).

Source

pub fn scheme_mut(&mut self) -> &mut Scheme

Returns a mutable reference to the URI scheme.

Source

pub fn remote_addr(&self) -> &SocketAddr

Returns the remote (client) socket address.

This is the IP address and port of the client making the request. Note that if behind a reverse proxy, this may be the proxy’s address rather than the actual client’s address.

Source

pub fn remote_addr_mut(&mut self) -> &mut SocketAddr

Returns a mutable reference to the remote socket address.

Source

pub fn local_addr(&self) -> &SocketAddr

Returns the local (server) socket address.

This is the IP address and port that the server is listening on for this connection.

Source

pub fn local_addr_mut(&mut self) -> &mut SocketAddr

Returns a mutable reference to the local socket address.

Source

pub fn matched_path(&self) -> &str

Available on crate feature matched-path only.

Get matched path.

Source

pub fn matched_path_mut(&mut self) -> &mut String

Available on crate feature matched-path only.

Get mutable matched path.

Source

pub fn headers(&self) -> &HeaderMap

Returns a reference to the associated header field map.

§Examples
let req = Request::default();
assert!(req.headers().is_empty());
Source

pub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>

Returns a mutable reference to the associated header field map.

§Examples
let mut req: Request = Request::default();
req.headers_mut()
    .insert(HOST, HeaderValue::from_static("world"));
assert!(!req.headers().is_empty());
Source

pub fn header<'de, T>(&'de self, key: impl AsHeaderName) -> Option<T>
where T: Deserialize<'de>,

Get header with supplied name and try to parse to a ‘T’.

Returns None if failed or not found.

Source

pub fn try_header<'de, T>(&'de self, key: impl AsHeaderName) -> ParseResult<T>
where T: Deserialize<'de>,

Try to get header with supplied name and try to parse to a ‘T’.

Source

pub fn add_header<N, V>( &mut self, name: N, value: V, overwrite: bool, ) -> Result<&mut Self>

Modify a header for this request.

When overwrite is set to true, If the header is already present, the value will be replaced. When overwrite is set to false, The new header is always appended to the request, even if the header already exists.

Source

pub fn body(&self) -> &ReqBody

Returns a reference to the associated HTTP body.

§Note

The body can only be read once from the underlying stream. For most use cases, prefer using payload() or form_data() which handle caching automatically.

Source

pub fn body_mut(&mut self) -> &mut ReqBody

Returns a mutable reference to the associated HTTP body.

§Note

Modifying the body directly may interfere with methods like payload() and form_data(). Use with caution.

Source

pub fn replace_body(&mut self, body: ReqBody) -> ReqBody

Replaces the body with a new value and returns the old body.

This is useful when you need to transform or wrap the request body.

§Note

Replacing the body does not clear the cached payload or form data. If you’ve already called payload(), those cached values will still be returned on subsequent calls.

Source

pub fn take_body(&mut self) -> ReqBody

Takes the body from the request, leaving ReqBody::None in its place.

This consumes the body, making it unavailable for subsequent reads unless it was already cached via payload().

§When to Use
  • When forwarding the request body to another service
  • When you need ownership of the body stream
  • When implementing custom body processing
§Note

Methods like payload() and form_data() call this internally. If those methods have already been called successfully, the data is cached and can still be accessed.

Source

pub fn extensions(&self) -> &Extensions

Returns a reference to the associated extensions.

§Examples
let req = Request::default();
assert!(req.extensions().get::<i32>().is_none());
Source

pub fn set_secure_max_size(&mut self, size: usize)

Sets the maximum allowed body size for this request.

This overrides both the global default and any value set by the SecureMaxSize middleware for this specific request.

§Arguments
  • size - Maximum body size in bytes.
§Note

This limit applies to request body reads and form parsing, including multipart file uploads. Increase the limit if you need to accept large uploads.

Source

pub fn secure_max_size(&self) -> usize

Returns the maximum allowed body size for this request.

Returns the request-specific limit if set via set_secure_max_size() or SecureMaxSize middleware, otherwise returns the global default (64KB).

Source

pub async fn web_transport_mut( &mut self, ) -> Result<&mut WebTransportSession<Connection, Bytes>, Error>

Available on crate feature quinn only.

Try to get a WebTransport session from the request.

Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Returns a mutable reference to the associated extensions.

§Examples
let mut req = Request::default();
req.extensions_mut().insert("hello");
assert_eq!(req.extensions().get(), Some(&"hello"));
Source

pub fn accept(&self) -> Vec<Mime>

Returns all MIME types from the Accept header.

Parses the Accept header and returns a list of MIME types the client is willing to accept. Returns an empty vector if the header is missing or cannot be parsed.

§Examples
// For Accept: text/html, application/json
let types = req.accept();
// types = [text/html, application/json]
Source

pub fn first_accept(&self) -> Option<Mime>

Returns the first MIME type from the Accept header.

This is typically the client’s most preferred content type. Returns None if the Accept header is missing or empty.

Source

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

Returns the Content-Type header value as a Mime type.

Returns None if the header is missing or cannot be parsed.

§Examples
if let Some(ct) = req.content_type() {
    if ct.subtype() == mime::JSON {
        // Handle JSON request
    }
}
Source

pub fn cookies(&self) -> &CookieJar

Available on crate feature cookie only.

Get CookieJar reference.

Source

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

Available on crate feature cookie only.

Get CookieJar mutable reference.

Source

pub fn cookie<T>(&self, name: T) -> Option<&Cookie<'static>>
where T: AsRef<str>,

Available on crate feature cookie only.

Get Cookie from cookies.

Source

pub fn params(&self) -> &PathParams

Get params reference.

Source

pub fn params_mut(&mut self) -> &mut PathParams

Get params mutable reference.

Source

pub fn param<'de, T>(&'de self, key: &str) -> Option<T>
where T: Deserialize<'de>,

Get param value from params.

Source

pub fn try_param<'de, T>(&'de self, key: &str) -> ParseResult<T>
where T: Deserialize<'de>,

Try to get param value from params.

Source

pub fn queries(&self) -> &MultiMap<String, String>

Get queries reference.

Source

pub fn queries_mut(&mut self) -> &mut MultiMap<String, String>

Get mutable queries reference.

Source

pub fn query<'de, T>(&'de self, key: &str) -> Option<T>
where T: Deserialize<'de>,

Gets a query parameter value by key, deserializing it to type T.

Returns None if the key doesn’t exist or deserialization fails. For error details, use try_query() instead.

§Type Coercion

The value is deserialized from a string, so numeric types, booleans, and other Deserialize implementations are supported.

§Examples
// URL: /search?page=2&limit=10
let page: u32 = req.query("page").unwrap_or(1);
let tags: Vec<String> = req.query("tags").unwrap_or_default();
Source

pub fn try_query<'de, T>(&'de self, key: &str) -> ParseResult<T>
where T: Deserialize<'de>,

Tries to get a query parameter value by key.

Returns a ParseResult with either the deserialized value or an error indicating why parsing failed.

Source

pub async fn form<'de, T>(&'de mut self, key: &str) -> Option<T>
where T: Deserialize<'de>,

Gets a form field value by key, deserializing it to type T.

Returns None if the key doesn’t exist or deserialization fails. For error details, use try_form() instead.

This method parses the request body as form data on first call (see form_data() for caching behavior).

§Examples
let username: String = req.form("username").await.unwrap_or_default();
Source

pub async fn try_form<'de, T>(&'de mut self, key: &str) -> ParseResult<T>
where T: Deserialize<'de>,

Tries to get a form field value by key.

Returns a ParseResult with either the deserialized value or an error indicating why parsing failed.

Source

pub async fn form_or_query<'de, T>(&'de mut self, key: &str) -> Option<T>
where T: Deserialize<'de>,

Gets a value from form data first, falling back to query parameters.

Checks the form body for the key first. If not found, checks query parameters. Returns None if the key doesn’t exist in either location.

§Use Case

Useful when a parameter can come from either a form submission or URL query string, with form data taking precedence.

Source

pub async fn try_form_or_query<'de, T>( &'de mut self, key: &str, ) -> ParseResult<T>
where T: Deserialize<'de>,

Tries to get a value from form data first, falling back to query parameters.

Returns a ParseResult with either the deserialized value or an error.

Source

pub async fn query_or_form<'de, T>(&'de mut self, key: &str) -> Option<T>
where T: Deserialize<'de>,

Gets a value from query parameters first, falling back to form data.

Checks query parameters for the key first. If not found, checks the form body. Returns None if the key doesn’t exist in either location.

§Use Case

Useful when a parameter can come from either URL query string or form submission, with query parameters taking precedence.

Source

pub async fn try_query_or_form<'de, T>( &'de mut self, key: &str, ) -> ParseResult<T>
where T: Deserialize<'de>,

Tries to get a value from query parameters first, falling back to form data.

Returns a ParseResult with either the deserialized value or an error.

Source

pub async fn file(&mut self, key: &str) -> Option<&FilePart>

Gets an uploaded file by form field name.

Returns the first file uploaded with the given field name, or None if no file was uploaded with that name.

§Examples
if let Some(file) = req.file("avatar").await {
    let filename = file.name().unwrap_or("unknown");
    let content_type = file.content_type();
}
Source

pub async fn try_file(&mut self, key: &str) -> ParseResult<Option<&FilePart>>

Tries to get an uploaded file by form field name.

Returns a ParseResult containing Option<&FilePart>. The outer result indicates if form parsing succeeded; the inner option indicates if a file with that key exists.

Source

pub async fn first_file(&mut self) -> Option<&FilePart>

Gets the first uploaded file from the request.

Useful when you only expect a single file upload and don’t care about the field name. Returns None if no files were uploaded.

Source

pub async fn try_first_file(&mut self) -> ParseResult<Option<&FilePart>>

Tries to get the first uploaded file from the request.

Source

pub async fn files(&mut self, key: &str) -> Option<&Vec<FilePart>>

Gets all files uploaded with the given form field name.

HTML forms with <input type="file" name="docs" multiple> can upload multiple files under the same field name. This method returns all of them.

Returns None if no files were uploaded with that name.

Source

pub async fn try_files( &mut self, key: &str, ) -> ParseResult<Option<&Vec<FilePart>>>

Tries to get all files uploaded with the given form field name.

Source

pub async fn all_files(&mut self) -> Vec<&FilePart>

Gets all uploaded files from the request, regardless of field name.

Returns an empty vector if no files were uploaded.

Source

pub async fn try_all_files(&mut self) -> ParseResult<Vec<&FilePart>>

Tries to get all uploaded files from the request.

Source

pub async fn payload(&mut self) -> ParseResult<&Bytes>

Get request payload as raw bytes with the default size limit.

Reads the entire request body into memory and caches it. The default size limit is determined by secure_max_size() (64KB by default).

§Caching Behavior

The payload is cached after the first call, so subsequent calls return the cached bytes without re-reading the body. This allows both middleware and handlers to access the raw body data.

§Errors

Returns an error if the body exceeds the size limit or if reading fails.

§Examples
let bytes = req.payload().await?;
println!("Body length: {}", bytes.len());
Source

pub async fn payload_with_max_size( &mut self, max_size: usize, ) -> ParseResult<&Bytes>

Get request payload as raw bytes with a custom size limit.

Similar to payload(), but allows specifying a custom maximum size limit instead of using the default.

§Arguments
  • max_size - Maximum allowed body size in bytes. If the body exceeds this limit, an error is returned.
§Caching Behavior

The payload is cached after the first successful read. Once cached, the max_size parameter is ignored on subsequent calls since the data is already in memory.

§Examples
// Allow up to 1MB payload
let bytes = req.payload_with_max_size(1024 * 1024).await?;
Source

pub async fn form_data(&mut self) -> ParseResult<&FormData>

Get FormData reference from request with the default size limit.

Parses the request body as form data (either application/x-www-form-urlencoded or multipart/form-data) and caches the result for subsequent calls.

Uses the default size limit from secure_max_size() (64KB by default). For a custom size limit, use form_data_max_size().

§Body Handling

This method intelligently handles body consumption:

  • If the body hasn’t been consumed yet, it reads directly from the body stream.
  • If the body was already consumed by payload(), it reuses the cached payload bytes to parse the form data.
  • The parsed FormData is cached, so subsequent calls return the cached result.

This allows middleware to read the raw body via payload() while still allowing handlers to access parsed form data.

§Content Type Requirements

Returns ParseError::NotFormData if the Content-Type header is not:

  • application/x-www-form-urlencoded
  • multipart/form-data
§Note

For multipart form data, file uploads are written to temporary files but the overall request size is still subject to the secure max size limit.

§Examples
// Access form fields
let form_data = req.form_data().await?;
let username = form_data.fields.get("username");

// Access uploaded files
let file = form_data.files.get("avatar");
Source

pub async fn form_data_max_size( &mut self, max_size: usize, ) -> ParseResult<&FormData>

Get FormData reference from request with a custom size limit.

Similar to form_data(), but allows specifying a custom maximum size limit instead of using the default.

§Arguments
  • max_size - Maximum allowed body size in bytes. If the body exceeds this limit, an error is returned.
§Caching Behavior

The form data is cached after the first successful parse. Once cached, the max_size parameter is ignored on subsequent calls since the data is already in memory.

§Examples
// Allow up to 1MB form data
let form_data = req.form_data_max_size(1024 * 1024).await?;
let username = form_data.fields.get("username");
Source

pub async fn extract<'de, T>( &'de mut self, depot: &'de mut Depot, ) -> ParseResult<T>
where T: Extractible<'de> + Deserialize<'de> + Send,

Extract request as type T from request’s different parts.

Source

pub async fn extract_with_metadata<'de, T>( &'de mut self, depot: &'de mut Depot, metadata: &'de Metadata, ) -> ParseResult<T>
where T: Deserialize<'de> + Send,

Extract request as type T from request’s different parts.

Source

pub fn parse_params<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parse url params as type T from request.

Source

pub fn parse_queries<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parse queries as type T from request.

Source

pub fn parse_headers<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parse headers as type T from request.

Source

pub fn parse_cookies<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Available on crate feature cookie only.

Parse cookies as type T from request.

Source

pub async fn parse_json<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parses the JSON request body into type T.

Uses the default size limit from secure_max_size().

§Content Type

Requires Content-Type: application/json. Returns ParseError::InvalidContentType if the content type doesn’t match.

§Empty Body Handling

An empty body is treated as JSON null, allowing deserialization into Option<T>.

§Examples
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}

let user: CreateUser = req.parse_json().await?;
Source

pub async fn parse_json_with_max_size<'de, T>( &'de mut self, max_size: usize, ) -> ParseResult<T>
where T: Deserialize<'de>,

Parses the JSON request body into type T with a custom size limit.

See parse_json() for details.

Source

pub async fn parse_form<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parses the form request body into type T.

Deserializes form fields into the target type. Works with both application/x-www-form-urlencoded and multipart/form-data content types.

§Content Type

Requires Content-Type to be either application/x-www-form-urlencoded or multipart/form-data. Returns ParseError::InvalidContentType otherwise.

§Examples
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}

let form: LoginForm = req.parse_form().await?;
Source

pub async fn parse_body<'de, T>(&'de mut self) -> ParseResult<T>
where T: Deserialize<'de>,

Parses the request body as either JSON or form data into type T.

Automatically detects the content type and parses accordingly:

  • application/json → parses as JSON
  • application/x-www-form-urlencoded or multipart/form-data → parses as form

Uses the default size limit from secure_max_size().

§Use Case

Useful for APIs that accept both JSON and form submissions for the same endpoint.

§Examples
// Works with both JSON and form submissions
let data: MyStruct = req.parse_body().await?;
Source

pub async fn parse_body_with_max_size<'de, T>( &'de mut self, max_size: usize, ) -> ParseResult<T>
where T: Deserialize<'de>,

Parses the request body as either JSON or form data with a custom size limit.

See parse_body() for details.

Trait Implementations§

Source§

impl Debug for Request

Source§

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

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

impl Default for Request

Source§

fn default() -> Self

Returns the “default value” for a type. 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> Same for T

Source§

type Output = T

Should always be Self
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