mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-24 00:00:16 +02:00
Replace route with Router::new().route() (#215)
This way there is now only one way to create a router:
```rust
use axum::{Router, handler::get};
let app = Router::new()
.route("/foo", get(handler))
.route("/foo", get(handler));
```
`nest` was changed in the same way:
```rust
use axum::Router;
let app = Router::new().nest("/foo", service);
```
This commit is contained in:
@@ -3,7 +3,7 @@ mod starwars;
|
||||
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
|
||||
use async_graphql::{EmptyMutation, EmptySubscription, Request, Response, Schema};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{extract::Extension, handler::get, response::Html, route, AddExtensionLayer, Json};
|
||||
use axum::{extract::Extension, handler::get, response::Html, AddExtensionLayer, Json, Router};
|
||||
use starwars::{QueryRoot, StarWars, StarWarsSchema};
|
||||
|
||||
async fn graphql_handler(schema: Extension<StarWarsSchema>, req: Json<Request>) -> Json<Response> {
|
||||
@@ -20,7 +20,8 @@ async fn main() {
|
||||
.data(StarWars::new())
|
||||
.finish();
|
||||
|
||||
let app = route("/", get(graphql_playground).post(graphql_handler))
|
||||
let app = Router::new()
|
||||
.route("/", get(graphql_playground).post(graphql_handler))
|
||||
.layer(AddExtensionLayer::new(schema));
|
||||
|
||||
println!("Playground: http://localhost:3000");
|
||||
|
||||
@@ -10,8 +10,8 @@ use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::Extension;
|
||||
use axum::handler::get;
|
||||
use axum::response::{Html, IntoResponse};
|
||||
use axum::route;
|
||||
use axum::AddExtensionLayer;
|
||||
use axum::Router;
|
||||
use futures::{sink::SinkExt, stream::StreamExt};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
@@ -31,7 +31,8 @@ async fn main() {
|
||||
|
||||
let app_state = Arc::new(AppState { user_set, tx });
|
||||
|
||||
let app = route("/", get(index))
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/websocket", get(websocket_handler))
|
||||
.layer(AddExtensionLayer::new(app_state));
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ use axum::{
|
||||
handler::{get, post},
|
||||
http::{Response, StatusCode},
|
||||
response::IntoResponse,
|
||||
route, AddExtensionLayer, Json,
|
||||
AddExtensionLayer, Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
@@ -37,7 +37,8 @@ async fn main() {
|
||||
let user_repo = Arc::new(ExampleUserRepo) as DynUserRepo;
|
||||
|
||||
// Build our application with some routes
|
||||
let app = route("/users/:id", get(users_show))
|
||||
let app = Router::new()
|
||||
.route("/users/:id", get(users_show))
|
||||
.route("/users", post(users_create))
|
||||
// Add our `user_repo` to all request's extensions so handlers can access
|
||||
// it.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! cargo run -p example-form
|
||||
//! ```
|
||||
|
||||
use axum::{extract::Form, handler::get, response::Html, route};
|
||||
use axum::{extract::Form, handler::get, response::Html, Router};
|
||||
use serde::Deserialize;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
@@ -17,7 +17,7 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = route("/", get(show_form).post(accept_form));
|
||||
let app = Router::new().route("/", get(show_form).post(accept_form));
|
||||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::{Response, StatusCode},
|
||||
response::Html,
|
||||
route,
|
||||
Router,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use tower::util::MapResponseLayer;
|
||||
@@ -23,7 +23,8 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with a route
|
||||
let app = route("/", get(handler))
|
||||
let app = Router::new()
|
||||
.route("/", get(handler))
|
||||
// make sure this is added as the very last thing
|
||||
.layer(MapResponseLayer::new(map_404));
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
//! cargo run -p example-hello-world
|
||||
//! ```
|
||||
|
||||
use axum::{handler::get, route};
|
||||
use axum::{handler::get, Router};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// build our application with a route
|
||||
let app = route("/foo", get(handler));
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
@@ -12,8 +12,8 @@ use axum::{
|
||||
handler::{delete, get, Handler},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
route,
|
||||
routing::{BoxRoute, Router},
|
||||
routing::BoxRoute,
|
||||
Router,
|
||||
};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
@@ -38,29 +38,30 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Build our application by composing routes
|
||||
let app = route(
|
||||
"/:key",
|
||||
// Add compression to `kv_get`
|
||||
get(kv_get.layer(CompressionLayer::new()))
|
||||
// But don't compress `kv_set`
|
||||
.post(kv_set),
|
||||
)
|
||||
.route("/keys", get(list_keys))
|
||||
// Nest our admin routes under `/admin`
|
||||
.nest("/admin", admin_routes())
|
||||
// Add middleware to all routes
|
||||
.layer(
|
||||
ServiceBuilder::new()
|
||||
.load_shed()
|
||||
.concurrency_limit(1024)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(AddExtensionLayer::new(SharedState::default()))
|
||||
.into_inner(),
|
||||
)
|
||||
// Handle errors from middleware
|
||||
.handle_error(handle_error)
|
||||
.check_infallible();
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/:key",
|
||||
// Add compression to `kv_get`
|
||||
get(kv_get.layer(CompressionLayer::new()))
|
||||
// But don't compress `kv_set`
|
||||
.post(kv_set),
|
||||
)
|
||||
.route("/keys", get(list_keys))
|
||||
// Nest our admin routes under `/admin`
|
||||
.nest("/admin", admin_routes())
|
||||
// Add middleware to all routes
|
||||
.layer(
|
||||
ServiceBuilder::new()
|
||||
.load_shed()
|
||||
.concurrency_limit(1024)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(AddExtensionLayer::new(SharedState::default()))
|
||||
.into_inner(),
|
||||
)
|
||||
// Handle errors from middleware
|
||||
.handle_error(handle_error)
|
||||
.check_infallible();
|
||||
|
||||
// Run our app with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
@@ -117,7 +118,8 @@ fn admin_routes() -> Router<BoxRoute> {
|
||||
state.write().unwrap().db.remove(&key);
|
||||
}
|
||||
|
||||
route("/keys", delete(delete_all_keys))
|
||||
Router::new()
|
||||
.route("/keys", delete(delete_all_keys))
|
||||
.route("/key/:key", delete(remove_key))
|
||||
// Require bearer auth for all admin routes
|
||||
.layer(RequireAuthorizationLayer::bearer("secret-token"))
|
||||
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
extract::{ContentLengthLimit, Multipart},
|
||||
handler::get,
|
||||
response::Html,
|
||||
route,
|
||||
Router,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
@@ -21,7 +21,8 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = route("/", get(show_form).post(accept_form))
|
||||
let app = Router::new()
|
||||
.route("/", get(show_form).post(accept_form))
|
||||
.layer(tower_http::trace::TraceLayer::new_for_http());
|
||||
|
||||
// run it with hyper
|
||||
|
||||
@@ -14,7 +14,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::{header::SET_COOKIE, HeaderMap, Response},
|
||||
response::{IntoResponse, Redirect},
|
||||
route, AddExtensionLayer,
|
||||
AddExtensionLayer, Router,
|
||||
};
|
||||
use oauth2::{
|
||||
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
|
||||
@@ -42,8 +42,11 @@ async fn main() {
|
||||
|
||||
// `MemoryStore` just used as an example. Don't use this in production.
|
||||
let store = MemoryStore::new();
|
||||
|
||||
let oauth_client = oauth_client();
|
||||
let app = route("/", get(index))
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/auth/discord", get(discord_auth))
|
||||
.route("/auth/authorized", get(login_authorized))
|
||||
.route("/protected", get(protected))
|
||||
|
||||
@@ -15,7 +15,7 @@ use axum::{
|
||||
StatusCode,
|
||||
},
|
||||
response::IntoResponse,
|
||||
route, AddExtensionLayer,
|
||||
AddExtensionLayer, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
@@ -32,7 +32,9 @@ async fn main() {
|
||||
// `MemoryStore` just used as an example. Don't use this in production.
|
||||
let store = MemoryStore::new();
|
||||
|
||||
let app = route("/", get(handler)).layer(AddExtensionLayer::new(store));
|
||||
let app = Router::new()
|
||||
.route("/", get(handler))
|
||||
.layer(AddExtensionLayer::new(store));
|
||||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::StatusCode,
|
||||
response::sse::{sse, Event, Sse},
|
||||
routing::nest,
|
||||
Router,
|
||||
};
|
||||
use futures::stream::{self, Stream};
|
||||
use std::{convert::Infallible, net::SocketAddr, time::Duration};
|
||||
@@ -35,7 +35,8 @@ async fn main() {
|
||||
});
|
||||
|
||||
// build our application with a route
|
||||
let app = nest("/", static_files_service)
|
||||
let app = Router::new()
|
||||
.nest("/", static_files_service)
|
||||
.route("/sse", get(sse_handler))
|
||||
.layer(TraceLayer::new_for_http());
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! cargo run -p example-static-file-server
|
||||
//! ```
|
||||
|
||||
use axum::{http::StatusCode, routing::nest};
|
||||
use std::net::SocketAddr;
|
||||
use axum::{http::StatusCode, service, Router};
|
||||
use std::{convert::Infallible, net::SocketAddr};
|
||||
use tower_http::{services::ServeDir, trace::TraceLayer};
|
||||
|
||||
#[tokio::main]
|
||||
@@ -19,16 +19,17 @@ async fn main() {
|
||||
}
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let app = nest(
|
||||
"/static",
|
||||
axum::service::get(ServeDir::new(".")).handle_error(|error: std::io::Error| {
|
||||
Ok::<_, std::convert::Infallible>((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
))
|
||||
}),
|
||||
)
|
||||
.layer(TraceLayer::new_for_http());
|
||||
let app = Router::new()
|
||||
.nest(
|
||||
"/static",
|
||||
service::get(ServeDir::new(".")).handle_error(|error: std::io::Error| {
|
||||
Ok::<_, Infallible>((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
))
|
||||
}),
|
||||
)
|
||||
.layer(TraceLayer::new_for_http());
|
||||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
|
||||
@@ -11,7 +11,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::{Response, StatusCode},
|
||||
response::{Html, IntoResponse},
|
||||
route,
|
||||
Router,
|
||||
};
|
||||
use std::{convert::Infallible, net::SocketAddr};
|
||||
|
||||
@@ -24,7 +24,7 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = route("/greet/:name", get(greet));
|
||||
let app = Router::new().route("/greet/:name", get(greet));
|
||||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
|
||||
use axum::{
|
||||
handler::{get, post},
|
||||
route,
|
||||
routing::{BoxRoute, Router},
|
||||
Json,
|
||||
routing::BoxRoute,
|
||||
Json, Router,
|
||||
};
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
@@ -34,7 +33,8 @@ async fn main() {
|
||||
/// without having to create an HTTP server.
|
||||
#[allow(dead_code)]
|
||||
fn app() -> Router<BoxRoute> {
|
||||
route("/", get(|| async { "Hello, World!" }))
|
||||
Router::new()
|
||||
.route("/", get(|| async { "Hello, World!" }))
|
||||
.route(
|
||||
"/json",
|
||||
post(|payload: Json<serde_json::Value>| async move {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! cargo run -p example-tls-rustls
|
||||
//! ```
|
||||
|
||||
use axum::{handler::get, route};
|
||||
use axum::{handler::get, Router};
|
||||
use hyper::server::conn::Http;
|
||||
use std::{fs::File, io::BufReader, sync::Arc};
|
||||
use tokio::net::TcpListener;
|
||||
@@ -31,7 +31,7 @@ async fn main() {
|
||||
let acceptor = TlsAcceptor::from(rustls_config);
|
||||
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
|
||||
|
||||
let app = route("/", get(handler));
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
loop {
|
||||
let (stream, _addr) = listener.accept().await.unwrap();
|
||||
|
||||
@@ -18,7 +18,7 @@ use axum::{
|
||||
handler::{get, patch},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
route, Json,
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
@@ -43,7 +43,8 @@ async fn main() {
|
||||
let db = Db::default();
|
||||
|
||||
// Compose the routes
|
||||
let app = route("/todos", get(todos_index).post(todos_create))
|
||||
let app = Router::new()
|
||||
.route("/todos", get(todos_index).post(todos_create))
|
||||
.route("/todos/:id", patch(todos_update).delete(todos_delete))
|
||||
// Add middleware to all routes
|
||||
.layer(
|
||||
@@ -53,7 +54,6 @@ async fn main() {
|
||||
.layer(AddExtensionLayer::new(db))
|
||||
.into_inner(),
|
||||
)
|
||||
// If the timeout fails, map the error to a response
|
||||
.handle_error(|error: BoxError| {
|
||||
let result = if error.is::<tower::timeout::error::Elapsed>() {
|
||||
Ok(StatusCode::REQUEST_TIMEOUT)
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
extract::{Extension, FromRequest, RequestParts},
|
||||
handler::get,
|
||||
http::StatusCode,
|
||||
route, AddExtensionLayer,
|
||||
AddExtensionLayer, Router,
|
||||
};
|
||||
use bb8::{Pool, PooledConnection};
|
||||
use bb8_postgres::PostgresConnectionManager;
|
||||
@@ -31,11 +31,12 @@ async fn main() {
|
||||
let pool = Pool::builder().build(manager).await.unwrap();
|
||||
|
||||
// build our application with some routes
|
||||
let app = route(
|
||||
"/",
|
||||
get(using_connection_pool_extractor).post(using_connection_extractor),
|
||||
)
|
||||
.layer(AddExtensionLayer::new(pool));
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/",
|
||||
get(using_connection_pool_extractor).post(using_connection_extractor),
|
||||
)
|
||||
.layer(AddExtensionLayer::new(pool));
|
||||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! cargo run -p example-tracing-aka-logging
|
||||
//! ```
|
||||
|
||||
use axum::{handler::get, response::Html, route};
|
||||
use axum::{handler::get, response::Html, Router};
|
||||
use std::net::SocketAddr;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
@@ -20,7 +20,8 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with a route
|
||||
let app = route("/", get(handler))
|
||||
let app = Router::new()
|
||||
.route("/", get(handler))
|
||||
// `TraceLayer` is provided by tower-http so you have to add that as a dependency.
|
||||
// It provides good defaults but is also very customizable.
|
||||
// See https://docs.rs/tower-http/0.1.1/tower_http/trace/index.html for more details.
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
extract::connect_info::{self, ConnectInfo},
|
||||
handler::get,
|
||||
http::{Method, Request, StatusCode, Uri},
|
||||
route,
|
||||
Router,
|
||||
};
|
||||
use futures::ready;
|
||||
use hyper::{
|
||||
@@ -53,7 +53,7 @@ async fn main() {
|
||||
|
||||
let uds = UnixListener::bind(path.clone()).unwrap();
|
||||
tokio::spawn(async {
|
||||
let app = route("/", get(handler));
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
axum::Server::builder(ServerAccept { uds })
|
||||
.serve(app.into_make_service_with_connect_info::<UdsConnectInfo, _>())
|
||||
|
||||
@@ -11,7 +11,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::{Response, StatusCode},
|
||||
response::IntoResponse,
|
||||
route,
|
||||
Router,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
@@ -25,7 +25,7 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = route("/:version/foo", get(handler));
|
||||
let app = Router::new().route("/:version/foo", get(handler));
|
||||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
@@ -14,7 +14,7 @@ use axum::{
|
||||
handler::get,
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::nest,
|
||||
Router,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use tower_http::{
|
||||
@@ -31,25 +31,27 @@ async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = nest(
|
||||
"/",
|
||||
axum::service::get(
|
||||
ServeDir::new("examples/websockets/assets").append_index_html_on_directories(true),
|
||||
let app = Router::new()
|
||||
.nest(
|
||||
"/",
|
||||
axum::service::get(
|
||||
ServeDir::new("examples/websockets/assets").append_index_html_on_directories(true),
|
||||
)
|
||||
.handle_error(|error: std::io::Error| {
|
||||
Ok::<_, std::convert::Infallible>((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
))
|
||||
}),
|
||||
)
|
||||
.handle_error(|error: std::io::Error| {
|
||||
Ok::<_, std::convert::Infallible>((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
))
|
||||
}),
|
||||
)
|
||||
// routes are matched from bottom to top, so we have to put `nest` at the
|
||||
// top since it matches all routes
|
||||
.route("/ws", get(ws_handler))
|
||||
// logging so we can see whats going on
|
||||
.layer(
|
||||
TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default().include_headers(true)),
|
||||
);
|
||||
// routes are matched from bottom to top, so we have to put `nest` at the
|
||||
// top since it matches all routes
|
||||
.route("/ws", get(ws_handler))
|
||||
// logging so we can see whats going on
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
.make_span_with(DefaultMakeSpan::default().include_headers(true)),
|
||||
);
|
||||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
Reference in New Issue
Block a user