Function axum::routing::nest [−][src]
pub fn nest<S, B>(description: &str, svc: S) -> Nested<S, EmptyRouter<S::Error>> where
S: Service<Request<B>> + Clone,
Expand description
Nest a group of routes (or a Service
) at some path.
This allows you to break your application into smaller pieces and compose them together. This will strip the matching prefix from the URL so the nested route will only see the part of URL:
use axum::{routing::nest, prelude::*}; use http::Uri; async fn users_get(uri: Uri) { // `users_get` doesn't see the whole URL. `nest` will strip the matching // `/api` prefix. assert_eq!(uri.path(), "/users"); } async fn users_post() {} async fn careers() {} let users_api = route("/users", get(users_get).post(users_post)); let app = nest("/api", users_api).route("/careers", get(careers));
Take care when using nest
together with dynamic routes as nesting also
captures from the outer routes:
use axum::{routing::nest, prelude::*}; async fn users_get(params: extract::UrlParamsMap) { // Both `version` and `id` were captured even though `users_api` only // explicitly captures `id`. let version = params.get("version"); let id = params.get("id"); } let users_api = route("/users/:id", get(users_get)); let app = nest("/:version/api", users_api);
nest
also accepts any Service
. This can for example be used with
tower_http::services::ServeDir
to serve static files from a directory:
use axum::{ routing::nest, service::{get, ServiceExt}, prelude::*, }; use tower_http::services::ServeDir; // Serves files inside the `public` directory at `GET /public/*` let serve_dir_service = ServeDir::new("public"); let app = nest("/public", get(serve_dir_service));
If necessary you can use RoutingDsl::boxed
to box a group of routes
making the type easier to name. This is sometimes useful when working with
nest
.