Skip to main content

HttpRequest

Struct HttpRequest 

Source
pub struct HttpRequest {
    pub method: Method,
    pub path: ByteStr,
    pub headers: HeaderMap,
    pub body: Bytes,
    pub path_params: RouteParams,
    pub extensions: Extensions,
    /* private fields */
}
Expand description

HTTP request wrapper

The path and body are Bytes-backed, so cloning a request is a handful of refcount bumps rather than a deep copy of the target and payload.

Fields§

§method: Method

The request method.

Was a String. An unrecognized token is carried as Method::Other rather than rejected here; routing answers it with 404 (crate::Error::RouteNotFound) since no route can match the token.

§path: ByteStr

The raw request target, query string included.

Was a String. A ByteStr so it can be a slice of the connection read buffer once the serve path moves onto armature-h1; Deref<Target = str> keeps &req.path working wherever a &str is wanted.

§headers: HeaderMap

Request headers stored in a SmallVec-backed HeaderMap.

For typical requests (<12 headers) this is stored inline on the stack, avoiding the per-request HashMap heap allocation on the read path. The API is HashMap-compatible (get/insert/iter/contains_key/…), with case-insensitive header name lookup.

§body: Bytes

The request body.

Was a Vec<u8> shadowed by an optional Bytes that could disagree with it. One field, always authoritative.

§path_params: RouteParams§extensions: Extensions

Type-safe extensions for storing application state.

Use this to pass typed data to handlers without DI container lookups. Access via the State<T> extractor for zero-cost state retrieval.

Implementations§

Source§

impl HttpRequest

Extension methods for HttpRequest to support content negotiation.

Source

pub fn accept(&self) -> Accept

Get the Accept header parsed into media types.

Source

pub fn accept_language(&self) -> AcceptLanguage

Get the Accept-Language header parsed into language tags.

Source

pub fn accept_encoding(&self) -> AcceptEncoding

Get the Accept-Encoding header parsed into encodings.

Source

pub fn accept_charset(&self) -> AcceptCharset

Get the Accept-Charset header parsed into charsets.

Source

pub fn accepts(&self, media_type: &MediaType) -> bool

Check if the client accepts a specific media type.

Source

pub fn prefers_json(&self) -> bool

Check if the client prefers JSON over HTML.

Source

pub fn prefers_html(&self) -> bool

Check if the client prefers HTML over JSON.

Source

pub fn negotiate_media_type<'a>( &self, available: &'a [MediaType], ) -> Option<&'a MediaType>

Negotiate the best media type from available options.

Source

pub fn negotiate_language<'a>( &self, available: &'a [LanguageTag], ) -> Option<&'a LanguageTag>

Negotiate the best language from available options.

Source

pub fn negotiate_encoding(&self, available: &[Encoding]) -> Option<Encoding>

Negotiate the best encoding from available options.

Source§

impl HttpRequest

Source

pub fn new(method: impl Into<Method>, path: impl Into<ByteStr>) -> Self

Create a request.

Generic in the method so every existing HttpRequest::new("GET", …) call site compiles unchanged.

Source

pub fn with_extensions_capacity( method: impl Into<Method>, path: impl Into<ByteStr>, capacity: usize, ) -> Self

Create a new request with pre-allocated extensions capacity.

Source

pub fn with_bytes_body( method: impl Into<Method>, path: impl Into<ByteStr>, body: Bytes, ) -> Self

Create a new request with a Bytes body (zero-copy).

This is the most efficient way to create a request from Hyper’s body, as it avoids copying the body data.

Source

pub fn set_body_bytes(&mut self, bytes: Bytes)

Set the body (zero-copy).

Source

pub fn body_bytes(&self) -> Bytes

The body as Bytes. A refcount bump, not a copy.

Source

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

The body as a byte slice.

Source

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

The body as a byte slice.

Source

pub fn path_str(&self) -> &str

The request target as a string, query string included.

Source

pub fn path_only(&self) -> &str

The request target with any query string removed.

This is what routing matches on, and what most callers mean when they say “the path” — path/path_str are the raw target, which is what the query is parsed out of.

Source

pub fn request_body(&self) -> RequestBody

Get the body as a RequestBody (zero-copy wrapper).

Source

pub fn has_bytes_body(&self) -> bool

Whether the body holds anything.

Kept for call-site compatibility from when the body could live in either of two fields; it is always Bytes now.

Source

pub fn method_str(&self) -> &str

The method as a string, for logging and for code that compares tokens.

Source

pub fn set_body(&mut self, body: Vec<u8>)

Set the body from a Vec<u8>, taking over its allocation.

Source

pub fn from_parts( method: impl Into<Method>, path: impl Into<ByteStr>, headers: HashMap<String, String>, body: Vec<u8>, path_params: HashMap<String, String>, query_params: HashMap<String, String>, ) -> Self

Create a request from all parts (for compatibility in tests).

Source

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

Insert a typed value into request extensions.

Use this to pass application state to handlers.

§Example
let mut request = HttpRequest::new("GET", "/");
request.insert_extension(app_state);
Source

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

Insert an Arc-wrapped value into request extensions.

This is more efficient when you already have an Arc.

Source

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

Get a reference to a typed extension.

Returns None if no value of this type exists.

Source

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

Get an Arc reference to a typed extension.

Source

pub fn json<T: for<'de> Deserialize<'de>>(&self) -> Result<T, Error>

Parse the request body as JSON.

With the simd-json feature enabled, this uses SIMD-accelerated parsing which can be 2-3x faster on modern x86_64 CPUs.

§Example
let user: CreateUser = request.json()?;
Source

pub fn form<T: for<'de> Deserialize<'de>>(&self) -> Result<T, Error>

Parse URL-encoded form data

Source

pub fn form_map(&self) -> Result<HashMap<String, String>, Error>

Parse URL-encoded form data into a HashMap

Source

pub fn multipart(&self) -> Result<Vec<FormField>, Error>

Parse multipart form data

Source

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

A captured route parameter, as UTF-8.

Source

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

A captured route parameter, raw.

Source

pub fn push_param(&mut self, name: &str, value: impl Into<Bytes>)

Add one captured route parameter, interning its name.

The router uses HttpRequest::set_params with names already interned at registration; this is for callers assembling a request by hand. The interner is hard-capped (crate::param_intern::MAX_INTERNED), so feeding this a request-derived name cannot grow the process without bound — past the cap the name resolves to crate::param_intern::OVERFLOW_NAME and the parameter is no longer retrievable by its own name.

Source

pub fn set_params(&mut self, params: RouteParams)

Replace the captured parameters. Called by the router.

Source

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

The raw query string, without the ?.

Source

pub fn query(&self) -> QueryView<'_>

A parsed view of the query string.

Parses on the first call and memoizes; a handler that never calls this pays nothing. Note the shape change: this used to take a name and return one value — that accessor is now HttpRequest::query_param.

Source

pub fn push_query_param( &mut self, name: impl AsRef<str>, value: impl AsRef<str>, )

Append a query parameter to the target, percent-encoding both sides.

The query lives in path now, so this is how a caller adds one without hand-assembling the target. Any memoized parse is discarded, since the target it was parsed from no longer describes this request.

Source

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

The first query value for name.

Source§

impl HttpRequest

Extension methods for HttpRequest related to caching.

Source

pub fn cache_control(&self) -> Option<CacheControl>

Get the Cache-Control header from the request.

Source

pub fn allows_cached(&self) -> bool

Check if the request allows cached responses.

Source

pub fn max_stale(&self) -> Option<u64>

Get the max-stale tolerance from the request.

Source

pub fn cache_key(&self) -> CacheKey

Generate a cache key for this request.

Source

pub fn cache_key_with_vary(&self, vary_headers: &[&str]) -> CacheKey

Generate a cache key with Vary headers.

Trait Implementations§

Source§

impl Clone for HttpRequest

Source§

fn clone(&self) -> HttpRequest

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl ConditionalRequest for HttpRequest

Source§

fn conditional_headers(&self) -> ConditionalHeaders

Get parsed conditional headers from the request.
Source§

fn if_none_match(&self) -> Option<ETagList>

Get the If-None-Match header as an ETag list.
Source§

fn if_match(&self) -> Option<ETagList>

Get the If-Match header as an ETag list.
Source§

fn if_modified_since(&self) -> Option<SystemTime>

Get the If-Modified-Since header as a SystemTime.
Source§

fn if_unmodified_since(&self) -> Option<SystemTime>

Get the If-Unmodified-Since header as a SystemTime.
Source§

fn if_none_match_matches(&self, etag: &ETag) -> bool

Check if If-None-Match contains a matching ETag (weak comparison). Read more
Source§

fn if_match_matches(&self, etag: &ETag) -> bool

Check if If-Match contains a matching ETag (strong comparison). Read more
Source§

fn not_modified_since(&self, last_modified: SystemTime) -> bool

Check if If-Modified-Since indicates the resource hasn’t changed.
Source§

fn modified_since_precondition(&self, last_modified: SystemTime) -> bool

Check if If-Unmodified-Since precondition fails.
Source§

fn evaluate_conditionals( &self, etag: Option<&ETag>, last_modified: Option<SystemTime>, ) -> Option<u16>

Evaluate all conditional headers and return the appropriate response. Read more
Source§

impl CorrelatedRequest for HttpRequest

Source§

fn correlation_context(&self) -> CorrelationContext

Get the correlation context from the request.
Source§

fn correlation_id(&self) -> Option<String>

Get the correlation ID.
Source§

fn request_id(&self) -> Option<String>

Get the request ID.
Source§

fn trace_id(&self) -> Option<String>

Get the trace ID.
Source§

fn span_id(&self) -> Option<String>

Get the span ID.
Source§

impl Debug for HttpRequest

Source§

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

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

impl FromRequest for HttpRequest

Source§

fn from_request(request: &HttpRequest) -> Result<Self, Error>

Extract data from the request
Source§

impl<S> Service<HttpRequest> for LoggingService<S>
where S: Service<HttpRequest, Response = HttpResponse, Error = Error> + Clone + Send + Sync + 'static, S::Future: Send,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, req: HttpRequest) -> Self::Future

Process a request.
Source§

impl<S> Service<HttpRequest> for TimeoutService<S>
where S: Service<HttpRequest, Response = HttpResponse, Error = Error> + Clone + Send + Sync + 'static, S::Future: Send,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, req: HttpRequest) -> Self::Future

Process a request.
Source§

impl<S> Service<HttpRequest> for RequestIdService<S>
where S: Service<HttpRequest, Response = HttpResponse, Error = Error> + Clone + Send + Sync + 'static, S::Future: Send,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, req: HttpRequest) -> Self::Future

Process a request.
Source§

impl<H, Fut> Service<HttpRequest> for HandlerService<H, ()>
where H: Fn() -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = Result<HttpResponse, Error>> + Send + 'static,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, _req: HttpRequest) -> Self::Future

Process a request.
Source§

impl<H, Fut> Service<HttpRequest> for HandlerService<H, (HttpRequest,)>
where H: Fn(HttpRequest) -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = Result<HttpResponse, Error>> + Send + 'static,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, req: HttpRequest) -> Self::Future

Process a request.
Source§

impl<H, Fut, E1> Service<HttpRequest> for ExtractorHandlerService<H, (E1,)>
where H: Fn(E1) -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = Result<HttpResponse, Error>> + Send + 'static, E1: Extract + Send + 'static,

Source§

type Response = HttpResponse

Response type.
Source§

type Error = Error

Error type.
Source§

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>

Future type.
Source§

fn call(&self, req: HttpRequest) -> Self::Future

Process a request.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<R, D> DepsPresent<D> for R

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Injectable for T
where T: Send + Sync + 'static,

Source§

fn type_id_of() -> TypeId
where Self: Sized,

Returns the TypeId of this type (for internal use)
Source§

fn type_name_of() -> &'static str
where Self: Sized,

Returns the type name for debugging
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> Provider for T
where T: Injectable,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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, 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<R, D> VerifyDeps<D> for R

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