Router<S> means a router that is missing a state of type S to be able to handle requests. Thus, only Router<()> (i.e. without missing state) can be passed to serve. See Router::with_state for more details.
Constructor
Create a new
Router.Unless you add additional routes this will respond with 404 Not Found to all requests.Routing methods
Add a route to the router.The path can contain dynamic segments starting with
: or catch-all segments starting with *.Add a service as a route.Similar to
route but accepts any Service instead of a MethodRouter.Note: Cannot be used with Routers - use nest instead.Nest another router at a given path.All routes in the nested router will be prefixed with the given path. The path cannot be empty or
/ - use merge instead.Like
nest, but accepts an arbitrary Service.The path cannot be empty or /.Merge two routers into one.This is useful for combining multiple routers that have routes at the root level. Both routers cannot have a custom fallback.
Middleware methods
Apply a
tower::Layer to the router.The layer will be applied to all routes and the fallback.Apply a
tower::Layer to the router’s routes, but not the fallback.This is useful when you want middleware to only apply to matched routes.Fallback methods
Add a fallback handler for requests that don’t match any routes.
Add a fallback
Service for requests that don’t match any routes.Like fallback but accepts a Service instead of a handler.Set a custom handler for 405 Method Not Allowed responses.This handler is called when a route matches the path but not the HTTP method.
Reset the fallback to its default.Useful to merge two routers with fallbacks, as
merge doesn’t allow both routers to have an explicit fallback. Use this method to remove the one you want to discard before merging.State management
Provide the state for the router.This converts a
Router<S> (missing state of type S) into a Router<()> that can be served.Service conversion
Convert this router into a
MakeService.Only available for Router<()> (routers without missing state).Convert the router into a
MakeService which stores information about the incoming connection.Requires the tokio feature.Convert the router into a borrowed
Service with a fixed request body type.This is mainly used when calling Router in tests to aid type inference.Convert the router into an owned
Service with a fixed request body type.Similar to as_service but returns an owned Service.Utility methods
Returns
true if the router currently has at least one route added.