Struct Router

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

Routes HTTP requests within a Spin component.

Routes may contain wildcards:

  • :name is a single segment wildcard. The handler can retrieve it using Params::get().
  • * is a trailing wildcard (matches anything). The handler can retrieve it using Params::wildcard().

If a request matches more than one route, the match is selected according to the follow criteria:

  • An exact route takes priority over any wildcard.
  • A single segment wildcard takes priority over a trailing wildcard.

(This is the same logic as overlapping routes in the Spin manifest.)

§Examples

Handle GET requests to a path with a wildcard, falling back to “not found”:

fn handle_route(req: Request) -> Response {
    let mut router = Router::new();
    router.get("/hello/:planet", hello_planet);
    router.any("/*", not_found);
    router.handle(req)
}

fn hello_planet(req: Request, params: Params) -> anyhow::Result<Response> {
    let planet = params.get("planet").unwrap_or("world");
    Ok(Response::new(200, format!("hello, {planet}")))
}

fn not_found(req: Request, params: Params) -> anyhow::Result<Response> {
    Ok(Response::new(404, "not found"))
}

Handle requests using a mix of synchronous and asynchronous handlers:

fn handle_route(req: Request) -> Response {
    let mut router = Router::new();
    router.get("/hello/:planet", hello_planet);
    router.get_async("/goodbye/:planet", goodbye_planet);
    router.handle(req)
}

fn hello_planet(req: Request, params: Params) -> anyhow::Result<Response> {
    todo!()
}

async fn goodbye_planet(req: Request, params: Params) -> anyhow::Result<Response> {
    todo!()
}

Route differently according to HTTP method:

fn handle_route(req: Request) -> Response {
    let mut router = Router::new();
    router.get("/user", list_users);
    router.post("/user", create_user);
    router.get("/user/:id", get_user);
    router.put("/user/:id", update_user);
    router.delete("/user/:id", delete_user);
    router.any("/user", method_not_allowed);
    router.any("/user/:id", method_not_allowed);
    router.handle(req)
}

Run the handler asynchronously:

async fn handle_route(req: Request) -> Response {
    let mut router = Router::new();
    router.get_async("/user", list_users);
    router.post_async("/user", create_user);
    router.handle_async(req).await
}

Priority when routes overlap:

fn handle_route(req: Request) -> Response {
    let mut router = Router::new();
    router.any("/*", handle_any);
    router.any("/:seg", handle_single_segment);
    router.any("/fie", handle_exact);

    // '/fie' is routed to `handle_exact`
    // '/zounds' is routed to `handle_single_segment`
    // '/zounds/fie' is routed to `handle_any`
    router.handle(req)
}

Route based on the trailing segment of a Spin wildcard route, instead of on the full path

// spin.toml
//
// [[trigger.http]]
// route = "/shop/..."

// component
fn handle_route(req: Request) -> Response {
    let mut router = Router::suffix();
    router.any("/users/*", handle_users);
    router.any("/products/*", handle_products);
    router.handle(req)
}

// '/shop/users/1' is routed to `handle_users`
// '/shop/products/1' is routed to `handle_products`

Implementations§

Source§

impl Router

Source

pub fn handle<R>(&self, request: R) -> Response

Synchronously dispatches a request to the appropriate handler along with the URI parameters.

Source

pub async fn handle_async<R>(&self, request: R) -> Response

Asynchronously dispatches a request to the appropriate handler along with the URI parameters.

Source

pub fn any<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for all methods.

Source

pub fn any_async<F, Fut, I, O>(&mut self, path: &str, handler: F)
where F: Fn(I, Params) -> Fut + 'static, Fut: Future<Output = O> + 'static, I: TryFromRequest + 'static, I::Error: IntoResponse + 'static, O: IntoResponse + 'static,

Register an async handler at the path for all methods.

Source

pub fn add<F, Req, Resp>(&mut self, path: &str, method: Method, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the specified HTTP method.

Source

pub fn add_async<F, Fut, I, O>( &mut self, path: &str, method: Method, handler: F, )
where F: Fn(I, Params) -> Fut + 'static, Fut: Future<Output = O> + 'static, I: TryFromRequest + 'static, I::Error: IntoResponse + 'static, O: IntoResponse + 'static,

Register an async handler at the path for the specified HTTP method.

Source

pub fn get<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP GET method.

Source

pub fn get_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP GET method.

Source

pub fn head<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP HEAD method.

Source

pub fn head_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP HEAD method.

Source

pub fn post<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP POST method.

Source

pub fn post_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP POST method.

Source

pub fn delete<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP DELETE method.

Source

pub fn delete_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP DELETE method.

Source

pub fn put<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP PUT method.

Source

pub fn put_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP PUT method.

Source

pub fn patch<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP PATCH method.

Source

pub fn patch_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP PATCH method.

Source

pub fn options<F, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Resp + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register a handler at the path for the HTTP OPTIONS method.

Source

pub fn options_async<F, Fut, Req, Resp>(&mut self, path: &str, handler: F)
where F: Fn(Req, Params) -> Fut + 'static, Fut: Future<Output = Resp> + 'static, Req: TryFromRequest + 'static, Req::Error: IntoResponse + 'static, Resp: IntoResponse + 'static,

Register an async handler at the path for the HTTP OPTIONS method.

Source

pub fn new() -> Self

Construct a new Router that matches on the full path.

Source

pub fn suffix() -> Self

Construct a new Router that matches on the trailing wildcard component of the route.

Trait Implementations§

Source§

impl Default for Router

Source§

fn default() -> Router

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§

§

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