Request

Struct Request 

Source
#[non_exhaustive]
pub struct Request { /* private fields */ }
Expand description

HTTP Request wrapper providing convenient access to request data.

Created by the routes! macro from raw request-data. Provides:

  • Path parameters extracted from route patterns (e.g., /users/{id})
  • Query string parsing
  • Header access (case-insensitive)
  • Body access (raw bytes, text, or parsed via external JSON)

§Example

fn get_user(req: &Request) -> Response {
    let id = req.param("id").unwrap_or("0");
    let page = req.query("page").unwrap_or("1");
    let auth = req.header("authorization");
    // ...
}

§Implementation Notes

This struct stores headers with an index-based lookup optimization:

  • headers: Original header pairs for headers() iteration
  • header_index: Maps lowercase keys to indices in headers for O(1) lookups

This avoids cloning header values while providing:

  • O(1) header lookups via header() and header_all()
  • Original header iteration via headers()

Implementations§

Source§

impl Request

Source

pub const fn method(&self) -> Method

HTTP method (GET, POST, etc.).

Source

pub fn path(&self) -> &str

Full request path including query string (e.g., “/users/123?page=1”).

Source

pub fn path_without_query(&self) -> &str

Just the path portion without query string (e.g., “/users/123”).

Source

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

Get a path parameter extracted from the route pattern.

For route /users/{id} matching path /users/123, param("id") returns Some("123").

Source

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

Get the first query parameter value from the URL.

For path /users?page=2&limit=10, query("page") returns Some("2"). For multiple values with same key, use query_all().

Source

pub fn query_all(&self, name: &str) -> &[String]

Get all query parameter values for a key.

HTTP allows multiple query params with the same name (e.g., ?ids=1&ids=2&ids=3). This returns all values for such parameters.

// For URL: /search?tag=rust&tag=wasm&tag=http
let tags = req.query_all("tag");
assert_eq!(tags, &["rust", "wasm", "http"]);
Source

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

Get the first header value by name (case-insensitive).

Uses pre-normalized HashMap for O(1) lookup. Avoids allocation when the header name is already lowercase (common case). For headers with multiple values (e.g., Set-Cookie), use header_all().

let content_type = req.header("content-type");
let auth = req.header("Authorization"); // Same as "authorization"
Source

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

Get the trace ID from the incoming request.

Returns the value of the x-trace-id header if present. Use this with ClientRequest::with_trace_id() to propagate trace context to outgoing HTTP calls.

let response = fetch!(GET "https://api.example.com/data")
    .with_trace_id(req.trace_id())
    .send_with(&handler)?;
Source

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

Get all values for a header (case-insensitive).

HTTP allows multiple headers with the same name (e.g., Set-Cookie, Accept). This returns all values for such headers.

let cookies = req.header_all("set-cookie");
for cookie in &cookies {
    println!("Cookie: {}", cookie);
}
Source

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

Get all headers as name-value pairs.

Returns headers in their original form (before normalization).

Source

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

Raw request body bytes.

Returns the raw bytes of the request body, or None if no body was provided.

§Returns
  • Some(&[u8]) - The raw body bytes
  • None - No body in request
Source

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

Request body as UTF-8 text.

§Returns
  • Some(&str) - Body successfully decoded as UTF-8
  • None - No body, or body is not valid UTF-8
Source

pub fn has_body(&self) -> bool

Check if request has a body.

Source

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

Content-Type header value.

§Returns
  • Some(&str) - The Content-Type header value
  • None - No Content-Type header present
Source

pub fn is_json(&self) -> bool

Check if Content-Type is JSON (case-insensitive).

Source

pub fn is_form(&self) -> bool

Check if Content-Type is form-urlencoded (case-insensitive).

Source

pub fn is_html(&self) -> bool

Check if Content-Type is HTML (case-insensitive).

Source

pub fn accepts(&self, mime: &str) -> bool

Check if client accepts a content type (via Accept header).

Performs a simple case-insensitive substring match against the Accept header. Does not parse q-values; returns true if the MIME type is present at all.

// Accept: text/html, application/json
req.accepts("json")  // true
req.accepts("html")  // true
req.accepts("xml")   // false
Source

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

Get the first form field value from a form-urlencoded body.

Parses application/x-www-form-urlencoded body data. For multiple values with same key, use form_all().

§Returns
  • Some(&str) - The decoded field value
  • None - Field not present, no body, or body is not valid UTF-8
§Examples
// Body: name=Alice&email=alice%40example.com
let name = req.form("name");  // Some("Alice")
let email = req.form("email"); // Some("alice@example.com")
Source

pub fn form_all(&self, name: &str) -> &[String]

Get all form field values for a key from a form-urlencoded body.

// Body: tags=rust&tags=wasm&tags=http
let tags = req.form_all("tags"); // &["rust", "wasm", "http"]
Source

pub fn json_with<T>(&self, parse: impl FnOnce(&[u8]) -> Option<T>) -> Option<T>

Parse request body as JSON using the provided parser.

§Returns
  • Some(T) - Body successfully parsed by the provided function
  • None - No body, or parser returned None
§Examples
let body = req.json_with(json::try_parse)?;
let name = body.get("name").str_or("");
Source

pub fn json(&self) -> Option<JsonValue>

Parse request body as JSON.

Uses the built-in JSON parser. For custom parsers, use json_with.

§Returns
  • Some(JsonValue) - Body successfully parsed as JSON
  • None - No body, or body is not valid JSON
§Examples
let body = req.json()?;
let name = body.path_str(&["user", "name"]).unwrap_or("anonymous");

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