Struct Router

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

A fast, lightweight HTTP router that matches requests to handlers.

The router supports:

  • Path parameters (:name syntax)
  • Wildcard matching (* syntax)
  • Multiple HTTP methods
  • Custom 404 handlers
  • Efficient O(1) method lookup with linear path matching

§Examples

§Basic Usage

use torch_web::{Router, Request, Response, Method};

let mut router = Router::new();

router.get("/", |_req: Request| async {
    Response::ok().body("Home page")
});

router.get("/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("User: {}", id))
});

§With Parameters and Wildcards

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

let mut router = Router::new();

// Path parameters
router.get("/users/:id/posts/:post_id", |req: Request| async move {
    let user_id = req.param("id").unwrap();
    let post_id = req.param("post_id").unwrap();
    Response::ok().body(format!("User {} Post {}", user_id, post_id))
});

// Wildcard for static files
router.get("/static/*", |req: Request| async move {
    let path = req.path();
    Response::ok().body(format!("Serving static file: {}", path))
});

Implementations§

Source§

impl Router

Source

pub fn new() -> Self

Creates a new empty router.

The router starts with no routes registered and uses the default 404 handler for unmatched requests.

§Examples
use torch_web::Router;

let router = Router::new();
Source

pub fn route(&mut self, method: Method, path: &str, handler: HandlerFn)

Registers a route for the specified HTTP method and path pattern.

This is the core method for route registration. All other route methods (get, post, etc.) delegate to this method.

§Parameters
  • method - The HTTP method to match (GET, POST, PUT, DELETE, etc.)
  • path - The path pattern to match, supporting parameters and wildcards
  • handler - The handler function to execute when the route matches
§Path Pattern Syntax
  • Static segments: /users, /api/v1
  • Parameters: /users/:id, /posts/:id/comments/:comment_id
  • Wildcards: /static/* (matches any remaining path)
§Examples
use torch_web::{Router, Request, Response, Method};

let mut router = Router::new();

router.route(Method::GET, "/", |_req: Request| async {
    Response::ok().body("Home")
});

router.route(Method::POST, "/users", |_req: Request| async {
    Response::created().body("User created")
});

router.route(Method::GET, "/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("User: {}", id))
});
Source

pub fn get(&mut self, path: &str, handler: HandlerFn)

Registers a GET route handler.

Convenience method for registering GET routes. GET requests should be idempotent and safe (no side effects).

§Parameters
  • path - The path pattern to match
  • handler - The handler function to execute
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.get("/", |_req: Request| async {
    Response::ok().body("Welcome!")
});

router.get("/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("User: {}", id))
});
Source

pub fn post(&mut self, path: &str, handler: HandlerFn)

Registers a POST route handler.

Convenience method for registering POST routes. POST requests are typically used for creating resources or submitting data.

§Parameters
  • path - The path pattern to match
  • handler - The handler function to execute
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.post("/users", |_req: Request| async {
    Response::created().body("User created")
});

router.post("/login", |_req: Request| async {
    Response::ok().body("Login successful")
});
Source

pub fn put(&mut self, path: &str, handler: HandlerFn)

Registers a PUT route handler.

Convenience method for registering PUT routes. PUT requests are typically used for updating entire resources or creating resources with specific IDs.

§Parameters
  • path - The path pattern to match
  • handler - The handler function to execute
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.put("/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("Updated user: {}", id))
});
Source

pub fn delete(&mut self, path: &str, handler: HandlerFn)

Registers a DELETE route handler.

Convenience method for registering DELETE routes. DELETE requests are used for removing resources.

§Parameters
  • path - The path pattern to match
  • handler - The handler function to execute
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.delete("/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("Deleted user: {}", id))
});
Source

pub fn patch(&mut self, path: &str, handler: HandlerFn)

Registers a PATCH route handler.

Convenience method for registering PATCH routes. PATCH requests are used for partial updates to resources.

§Parameters
  • path - The path pattern to match
  • handler - The handler function to execute
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.patch("/users/:id", |req: Request| async move {
    let id = req.param("id").unwrap();
    Response::ok().body(format!("Patched user: {}", id))
});
Source

pub fn not_found(&mut self, handler: HandlerFn)

Sets a custom handler for requests that don’t match any registered route.

By default, unmatched requests return a 404 Not Found response. This method allows you to customize that behavior.

§Parameters
  • handler - The handler function to execute for unmatched routes
§Examples
use torch_web::{Router, Request, Response};

let mut router = Router::new();

router.not_found(|req: Request| async move {
    Response::not_found()
        .body(format!("Sorry, {} was not found", req.path()))
});
Source

pub async fn route_request(&self, req: Request) -> Response

Route a request to the appropriate handler

Trait Implementations§

Source§

impl Clone for Router

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Default for Router

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Router

§

impl !RefUnwindSafe for Router

§

impl Send for Router

§

impl Sync for Router

§

impl Unpin for Router

§

impl !UnwindSafe for Router

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