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()andpayload_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 bypayload(), 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:
set_global_secure_max_size()- Set the global default limitSecureMaxSizemiddleware - Set per-route limitsset_secure_max_size()- Set per-request limits
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
impl Request
Sourcepub fn from_hyper<B>(req: Request<B>, scheme: Scheme) -> Self
pub fn from_hyper<B>(req: Request<B>, scheme: Scheme) -> Self
Creates a new Request from hyper::Request.
Sourcepub fn uri(&self) -> &Uri
pub fn uri(&self) -> &Uri
Returns a reference to the associated URI.
§Examples
let req = Request::default();
assert_eq!(*req.uri(), *"/");Sourcepub fn uri_mut(&mut self) -> &mut Uri
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");Sourcepub fn set_uri(&mut self, uri: Uri)
pub fn set_uri(&mut self, uri: Uri)
Set the associated URI. queries will be reset.
Notice: params will not reset.
Sourcepub fn method(&self) -> &Method
pub fn method(&self) -> &Method
Returns a reference to the associated HTTP method.
§Examples
let req = Request::default();
assert_eq!(*req.method(), Method::GET);Sourcepub fn method_mut(&mut self) -> &mut Method
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);Sourcepub fn version(&self) -> Version
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.
Sourcepub fn version_mut(&mut self) -> &mut Version
pub fn version_mut(&mut self) -> &mut Version
Returns a mutable reference to the HTTP version.
Sourcepub fn scheme_mut(&mut self) -> &mut Scheme
pub fn scheme_mut(&mut self) -> &mut Scheme
Returns a mutable reference to the URI scheme.
Sourcepub fn remote_addr(&self) -> &SocketAddr
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.
Sourcepub fn remote_addr_mut(&mut self) -> &mut SocketAddr
pub fn remote_addr_mut(&mut self) -> &mut SocketAddr
Returns a mutable reference to the remote socket address.
Sourcepub fn local_addr(&self) -> &SocketAddr
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.
Sourcepub fn local_addr_mut(&mut self) -> &mut SocketAddr
pub fn local_addr_mut(&mut self) -> &mut SocketAddr
Returns a mutable reference to the local socket address.
Sourcepub fn matched_path(&self) -> &str
Available on crate feature matched-path only.
pub fn matched_path(&self) -> &str
matched-path only.Get matched path.
Sourcepub fn matched_path_mut(&mut self) -> &mut String
Available on crate feature matched-path only.
pub fn matched_path_mut(&mut self) -> &mut String
matched-path only.Get mutable matched path.
Sourcepub fn headers(&self) -> &HeaderMap
pub fn headers(&self) -> &HeaderMap
Returns a reference to the associated header field map.
§Examples
let req = Request::default();
assert!(req.headers().is_empty());Sourcepub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>
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());Sourcepub fn header<'de, T>(&'de self, key: impl AsHeaderName) -> Option<T>where
T: Deserialize<'de>,
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.
Sourcepub fn try_header<'de, T>(&'de self, key: impl AsHeaderName) -> ParseResult<T>where
T: Deserialize<'de>,
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’.
Sourcepub fn add_header<N, V>(
&mut self,
name: N,
value: V,
overwrite: bool,
) -> Result<&mut Self>
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.
Sourcepub fn body(&self) -> &ReqBody
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.
Sourcepub fn body_mut(&mut self) -> &mut ReqBody
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.
Sourcepub fn replace_body(&mut self, body: ReqBody) -> ReqBody
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.
Sourcepub fn take_body(&mut self) -> ReqBody
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.
Sourcepub fn extensions(&self) -> &Extensions
pub fn extensions(&self) -> &Extensions
Returns a reference to the associated extensions.
§Examples
let req = Request::default();
assert!(req.extensions().get::<i32>().is_none());Sourcepub fn set_secure_max_size(&mut self, size: usize)
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.
Sourcepub fn secure_max_size(&self) -> usize
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).
Sourcepub async fn web_transport_mut(
&mut self,
) -> Result<&mut WebTransportSession<Connection, Bytes>, Error>
Available on crate feature quinn only.
pub async fn web_transport_mut( &mut self, ) -> Result<&mut WebTransportSession<Connection, Bytes>, Error>
quinn only.Try to get a WebTransport session from the request.
Sourcepub fn extensions_mut(&mut self) -> &mut Extensions
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"));Sourcepub fn accept(&self) -> Vec<Mime>
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]Sourcepub fn first_accept(&self) -> Option<Mime>
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.
Sourcepub fn content_type(&self) -> Option<Mime>
pub fn content_type(&self) -> Option<Mime>
Available on crate feature cookie only.
cookie only.Get CookieJar reference.
Available on crate feature cookie only.
cookie only.Get CookieJar mutable reference.
Available on crate feature cookie only.
cookie only.Get Cookie from cookies.
Sourcepub fn params(&self) -> &PathParams
pub fn params(&self) -> &PathParams
Get params reference.
Sourcepub fn params_mut(&mut self) -> &mut PathParams
pub fn params_mut(&mut self) -> &mut PathParams
Get params mutable reference.
Sourcepub fn param<'de, T>(&'de self, key: &str) -> Option<T>where
T: Deserialize<'de>,
pub fn param<'de, T>(&'de self, key: &str) -> Option<T>where
T: Deserialize<'de>,
Get param value from params.
Sourcepub fn try_param<'de, T>(&'de self, key: &str) -> ParseResult<T>where
T: Deserialize<'de>,
pub fn try_param<'de, T>(&'de self, key: &str) -> ParseResult<T>where
T: Deserialize<'de>,
Try to get param value from params.
Sourcepub fn queries_mut(&mut self) -> &mut MultiMap<String, String>
pub fn queries_mut(&mut self) -> &mut MultiMap<String, String>
Get mutable queries reference.
Sourcepub fn query<'de, T>(&'de self, key: &str) -> Option<T>where
T: Deserialize<'de>,
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();Sourcepub fn try_query<'de, T>(&'de self, key: &str) -> ParseResult<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn form<'de, T>(&'de mut self, key: &str) -> Option<T>where
T: Deserialize<'de>,
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();Sourcepub async fn try_form<'de, T>(&'de mut self, key: &str) -> ParseResult<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn form_or_query<'de, T>(&'de mut self, key: &str) -> Option<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn try_form_or_query<'de, T>(
&'de mut self,
key: &str,
) -> ParseResult<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn query_or_form<'de, T>(&'de mut self, key: &str) -> Option<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn try_query_or_form<'de, T>(
&'de mut self,
key: &str,
) -> ParseResult<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn try_file(&mut self, key: &str) -> ParseResult<Option<&FilePart>>
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.
Sourcepub async fn first_file(&mut self) -> Option<&FilePart>
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.
Sourcepub async fn try_first_file(&mut self) -> ParseResult<Option<&FilePart>>
pub async fn try_first_file(&mut self) -> ParseResult<Option<&FilePart>>
Tries to get the first uploaded file from the request.
Sourcepub async fn files(&mut self, key: &str) -> Option<&Vec<FilePart>>
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.
Sourcepub async fn try_files(
&mut self,
key: &str,
) -> ParseResult<Option<&Vec<FilePart>>>
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.
Sourcepub async fn all_files(&mut self) -> Vec<&FilePart>
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.
Sourcepub async fn try_all_files(&mut self) -> ParseResult<Vec<&FilePart>>
pub async fn try_all_files(&mut self) -> ParseResult<Vec<&FilePart>>
Tries to get all uploaded files from the request.
Sourcepub async fn payload(&mut self) -> ParseResult<&Bytes>
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());Sourcepub async fn payload_with_max_size(
&mut self,
max_size: usize,
) -> ParseResult<&Bytes>
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?;Sourcepub async fn form_data(&mut self) -> ParseResult<&FormData>
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
FormDatais 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-urlencodedmultipart/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");Sourcepub async fn form_data_max_size(
&mut self,
max_size: usize,
) -> ParseResult<&FormData>
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");Sourcepub async fn extract<'de, T>(
&'de mut self,
depot: &'de mut Depot,
) -> ParseResult<T>
pub async fn extract<'de, T>( &'de mut self, depot: &'de mut Depot, ) -> ParseResult<T>
Extract request as type T from request’s different parts.
Sourcepub async fn extract_with_metadata<'de, T>(
&'de mut self,
depot: &'de mut Depot,
metadata: &'de Metadata,
) -> ParseResult<T>where
T: Deserialize<'de> + Send,
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.
Sourcepub fn parse_params<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
pub fn parse_params<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
Parse url params as type T from request.
Sourcepub fn parse_queries<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
pub fn parse_queries<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
Parse queries as type T from request.
Sourcepub fn parse_headers<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
pub fn parse_headers<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
Parse headers as type T from request.
Available on crate feature cookie only.
cookie only.Parse cookies as type T from request.
Sourcepub async fn parse_json<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
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?;Sourcepub async fn parse_json_with_max_size<'de, T>(
&'de mut self,
max_size: usize,
) -> ParseResult<T>where
T: Deserialize<'de>,
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.
Sourcepub async fn parse_form<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
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?;Sourcepub async fn parse_body<'de, T>(&'de mut self) -> ParseResult<T>where
T: Deserialize<'de>,
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 JSONapplication/x-www-form-urlencodedormultipart/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?;Sourcepub async fn parse_body_with_max_size<'de, T>(
&'de mut self,
max_size: usize,
) -> ParseResult<T>where
T: Deserialize<'de>,
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.