Struct Request

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

HTTP request wrapper that provides convenient access to request data.

The Request struct encapsulates all the information about an incoming HTTP request, including the method, URI, headers, body, and extracted path parameters. It provides a high-level API for accessing this data in handlers.

§Examples

§Basic Usage in Handlers

use torch_web::{App, Request, Response};

let app = App::new()
    .get("/", |req: Request| async move {
        println!("Method: {}", req.method());
        println!("Path: {}", req.path());
        Response::ok().body("Hello!")
    });

§Accessing Headers

use torch_web::{App, Request, Response};

let app = App::new()
    .post("/api/data", |req: Request| async move {
        if let Some(content_type) = req.header("content-type") {
            println!("Content-Type: {}", content_type);
        }

        if let Some(auth) = req.header("authorization") {
            println!("Authorization: {}", auth);
        }

        Response::ok().body("Received")
    });

§Working with Request Body

use torch_web::{App, Request, Response};

let app = App::new()
    .post("/upload", |req: Request| async move {
        let body_bytes = req.body();
        println!("Received {} bytes", body_bytes.len());

        if let Ok(body_text) = req.body_string() {
            println!("Body: {}", body_text);
        }

        Response::ok().body("Upload complete")
    });

§Path Parameters

use torch_web::{App, Request, Response};

let app = App::new()
    .get("/users/:id/posts/:post_id", |req: Request| async move {
        let user_id = req.param("id").unwrap_or("unknown");
        let post_id = req.param("post_id").unwrap_or("unknown");

        Response::ok().body(format!("User {} Post {}", user_id, post_id))
    });

Implementations§

Source§

impl Request

Source

pub fn new() -> Self

Creates a new empty request with default values.

This is primarily used for testing and internal purposes. In normal operation, requests are created from incoming HTTP requests via from_hyper.

§Examples
use torch_web::Request;

let req = Request::new();
assert_eq!(req.path(), "/");
assert_eq!(req.method().as_str(), "GET");
Source

pub async fn from_hyper( parts: Parts, body: Incoming, ) -> Result<Self, Box<dyn Error + Send + Sync>>

Creates a new Request from Hyper’s request parts and body.

This is an internal method used by the framework to convert incoming Hyper requests into Torch Request objects. It reads the entire request body into memory and parses query parameters.

§Parameters
  • parts - The HTTP request parts (method, URI, headers, etc.)
  • body - The request body stream
§Returns

Returns a Result containing the constructed Request or an error if the body cannot be read or the request is malformed.

§Examples
use torch_web::Request;
use hyper::body::Incoming;
use http::request::Parts;

async fn handle_hyper_request(parts: Parts, body: Incoming) {
    match Request::from_hyper(parts, body).await {
        Ok(req) => {
            println!("Received request to {}", req.path());
        }
        Err(e) => {
            eprintln!("Failed to parse request: {}", e);
        }
    }
}
Source

pub fn method(&self) -> &Method

Returns the HTTP method of the request.

§Examples
use torch_web::{App, Request, Response, Method};

let app = App::new()
    .route(Method::POST, "/api/data", |req: Request| async move {
        match req.method() {
            &Method::POST => Response::ok().body("POST request"),
            &Method::GET => Response::ok().body("GET request"),
            _ => Response::method_not_allowed().body("Method not allowed"),
        }
    });
Source

pub fn uri(&self) -> &Uri

Returns the complete URI of the request.

This includes the path, query string, and fragment (if present).

§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .get("/debug", |req: Request| async move {
        let uri = req.uri();
        Response::ok().body(format!("Full URI: {}", uri))
    });
Source

pub fn path(&self) -> &str

Returns the path portion of the request URI.

This excludes the query string and fragment, returning only the path component.

§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .get("/users/:id", |req: Request| async move {
        println!("Request path: {}", req.path()); // "/users/123"
        Response::ok().body("User page")
    });
Source

pub fn version(&self) -> Version

Returns the HTTP version of the request.

§Examples
use torch_web::{App, Request, Response};
use http::Version;

let app = App::new()
    .get("/version", |req: Request| async move {
        let version = match req.version() {
            Version::HTTP_09 => "HTTP/0.9",
            Version::HTTP_10 => "HTTP/1.0",
            Version::HTTP_11 => "HTTP/1.1",
            Version::HTTP_2 => "HTTP/2.0",
            Version::HTTP_3 => "HTTP/3.0",
            _ => "Unknown",
        };
        Response::ok().body(format!("HTTP Version: {}", version))
    });
Source

pub fn headers(&self) -> &HeaderMap

Returns a reference to the request headers.

§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .post("/api/data", |req: Request| async move {
        let headers = req.headers();

        for (name, value) in headers.iter() {
            println!("{}: {:?}", name, value);
        }

        Response::ok().body("Headers logged")
    });
Source

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

Returns the value of a specific header.

This is a convenience method that looks up a header by name and converts it to a string. Returns None if the header doesn’t exist or contains invalid UTF-8.

§Parameters
  • name - The header name to look up (case-insensitive)
§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .post("/api/upload", |req: Request| async move {
        if let Some(content_type) = req.header("content-type") {
            println!("Content-Type: {}", content_type);

            if content_type.starts_with("application/json") {
                return Response::ok().body("JSON data received");
            }
        }

        Response::bad_request().body("Content-Type required")
    });
Source

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

Returns the request body as a byte slice.

The entire request body is read into memory when the request is created, so this method provides immediate access to the raw bytes.

§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .post("/upload", |req: Request| async move {
        let body_bytes = req.body();
        println!("Received {} bytes", body_bytes.len());

        // Process binary data
        if body_bytes.starts_with(b"PNG") {
            Response::ok().body("PNG image received")
        } else {
            Response::ok().body("Data received")
        }
    });
Source

pub fn body_string(&self) -> Result<String, FromUtf8Error>

Returns the request body as a UTF-8 string.

This method attempts to convert the request body bytes into a valid UTF-8 string. Returns an error if the body contains invalid UTF-8 sequences.

§Returns

Returns Ok(String) if the body is valid UTF-8, or Err(FromUtf8Error) otherwise.

§Examples
use torch_web::{App, Request, Response};

let app = App::new()
    .post("/text", |req: Request| async move {
        match req.body_string() {
            Ok(text) => {
                println!("Received text: {}", text);
                Response::ok().body(format!("Echo: {}", text))
            }
            Err(_) => {
                Response::bad_request().body("Invalid UTF-8 in request body")
            }
        }
    });
Source

pub async fn json<T>(&self) -> Result<T, Error>

Parse the request body as JSON (requires “json” feature)

Source

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

Get a path parameter by name

Source

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

Get all path parameters

Source

pub fn path_params(&self) -> &HashMap<String, String>

Get all path parameters (for extractors)

Source

pub fn extensions(&self) -> &HashMap<TypeId, Box<dyn Any + Send + Sync>>

Get a reference to the request extensions

Source

pub fn extensions_mut( &mut self, ) -> &mut HashMap<TypeId, Box<dyn Any + Send + Sync>>

Get a mutable reference to the request extensions

Source

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

Insert a value into the request extensions

Source

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

Get a value from the request extensions

Source

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

Get a query parameter by name

Source

pub fn query_params(&self) -> &HashMap<String, String>

Get all query parameters

Source

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

Get the raw query string

Source

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

Get the request body as bytes (for extractors)

Source

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

Get mutable access to headers (for extractors)

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 RequestDatabaseExt for Request

Source§

fn db_pool(&self) -> Option<()>

Source§

impl RequestStateExt for Request

Implementation of RequestStateExt for Request

Source§

fn get_state(&self, type_id: TypeId) -> Option<&Arc<dyn Any + Send + Sync>>

Get state by TypeId
Source§

fn set_state_map(&mut self, state_map: StateMap)

Set the state map for this request
Source§

fn state_map(&self) -> Option<&StateMap>

Get a reference to the state map

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, 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<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