1Add another route to the router that calls a [`Service`].
2
3# Example
4
5```rust,no_run
6use axum::{
7    Router,
8    body::Body,
9    routing::{any_service, get_service},
10    http::{Request, StatusCode},
11    error_handling::HandleErrorLayer,
12};
13use tower_http::services::ServeFile;
14use http::Response;
15use std::{convert::Infallible, io};
16use tower::service_fn;
17
18let app = Router::new()
19    .route(
20        // Any request to `/` goes to a service
21        "/",
22        // Services whose response body is not `axum::body::BoxBody`
23        // can be wrapped in `axum::routing::any_service` (or one of the other routing filters)
24        // to have the response body mapped
25        any_service(service_fn(|_: Request<Body>| async {
26            let res = Response::new(Body::from("Hi from `GET /`"));
27            Ok::<_, Infallible>(res)
28        }))
29    )
30    .route_service(
31        "/foo",
32        // This service's response body is `axum::body::BoxBody` so
33        // it can be routed to directly.
34        service_fn(|req: Request<Body>| async move {
35            let body = Body::from(format!("Hi from `{} /foo`", req.method()));
36            let body = axum::body::boxed(body);
37            let res = Response::new(body);
38            Ok::<_, Infallible>(res)
39        })
40    )
41    .route_service(
42        // GET `/static/Cargo.toml` goes to a service from tower-http
43        "/static/Cargo.toml",
44        ServeFile::new("Cargo.toml"),
45    );
46# async {
47# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
48# };
49```
50
51Routing to arbitrary services in this way has complications for backpressure
52([`Service::poll_ready`]). See the [Routing to services and backpressure] module
53for more details.
54
55# Panics
56
57Panics for the same reasons as [`Router::route`] or if you attempt to route to a
58`Router`:
59
60```rust,should_panic
61use axum::{routing::get, Router};
62
63let app = Router::new().route_service(
64    "/",
65    Router::new().route("/foo", get(|| async {})),
66);
67# async {
68# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
69# };
70```
71
72Use [`Router::nest`] instead.
73
74[Routing to services and backpressure]: middleware/index.html#routing-to-servicesmiddleware-and-backpressure
75