Skip to main content

Router

Struct Router 

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

HTTP request router with path-parameter extraction and method-based dispatch.

Implementations§

Source§

impl Router

Source

pub fn new() -> Self

Create a new empty router.

Source

pub fn with_state<T: Clone + Send + Sync + 'static>(self, state: T) -> Self

Attach application state of type T to this router.

The state is wrapped in an Arc<T> and injected into every request’s extensions map just before the handler is invoked. Handlers retrieve it with req.state::<T>().

Nested routers that do not have their own state automatically inherit this router’s state during dispatch.

#[derive(Clone)]
struct AppState { db_url: String }

let state = AppState { db_url: "postgres://localhost/mydb".into() };
let router = Router::new()
    .with_state(state)
    .get("/", |req: Request| async move {
        let s = req.state::<AppState>().expect("state present");
        oxihttp_server::response::text_response(&s.db_url)
    });
Source

pub fn route<F, Fut>(self, method: Method, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a route for the given method and path pattern.

Path patterns support:

  • Literal segments: /users/list
  • Parameters: /users/:id
  • Wildcards: /static/*path
Source

pub fn get<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a GET route.

Source

pub fn post<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a POST route.

Source

pub fn put<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a PUT route.

Source

pub fn delete<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a DELETE route.

Source

pub fn patch<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a PATCH route.

Source

pub fn head<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Register a HEAD route.

Source

pub fn nest(self, prefix: &str, router: Router) -> Self

Nest a sub-router under the given prefix.

Source

pub fn host(self, host: &str, router: Router) -> Self

Route requests with the given Host header value to router.

The host value is matched case-insensitively against the bare hostname (port suffix stripped). When a match is found the request is forwarded to router without any path rewriting. Virtual-host dispatch happens before nested-prefix dispatch.

§Example
let api = Router::new().get("/v1", |_req| async {
    oxihttp_server::response::text_response("api")
});
let web = Router::new().get("/", |_req| async {
    oxihttp_server::response::text_response("web")
});
let router = Router::new()
    .host("api.example.com", api)
    .host("example.com", web);
Source

pub fn fallback<F, Fut>(self, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Set a fallback handler for routes that don’t match (custom 404).

Source

pub fn method_not_allowed<F, Fut>(self, handler: F) -> Self
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response<Full<Bytes>>, OxiHttpError>> + Send + 'static,

Set a handler for method-not-allowed (405) responses.

Source

pub fn health(self, path: &str) -> Self

A simple health-check route returning 200 OK.

Source

pub fn resolve( &self, method: &Method, path: &str, ) -> Option<HashMap<String, String>>

Match a request path against registered routes without dispatching.

Replicates the O(n) dispatch scan for use in benchmarks and introspection. Returns extracted path parameters on a successful match, None on no match.

When the path is found but the method is not registered the method returns Some(HashMap::new()) — an empty map — to signal a 405 situation without actually dispatching.

Source

pub fn dispatch(&self, req: Request<Incoming>) -> DispatchFuture<'_>

Dispatch an incoming request through the router.

Source

pub fn route_count(&self) -> usize

Return the number of registered routes (not including nested).

Trait Implementations§

Source§

impl Debug for Router

Source§

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

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

impl Default for Router

Source§

fn default() -> Self

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

impl Display for Router

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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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