mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-21 00:00:14 +02:00
Type safe state inheritance (#1532)
* Make state type safe * fix examples * remove unnecessary `#[track_caller]`s * Router::into_service -> Router::with_state * fixup docs * macro docs * add missing docs * fix examples * format * changelog * Update trybuild tests * Make sure fallbacks are still inherited for opaque services (#1540) * Document nesting routers with different state * fix leftover conflicts
This commit is contained in:
@@ -43,7 +43,7 @@ async fn main() {
|
||||
let shared_state = SharedState::default();
|
||||
|
||||
// Build our application by composing routes
|
||||
let app = Router::with_state(Arc::clone(&shared_state))
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/:key",
|
||||
// Add compression to `kv_get`
|
||||
@@ -60,7 +60,7 @@ async fn main() {
|
||||
)
|
||||
.route("/keys", get(list_keys))
|
||||
// Nest our admin routes under `/admin`
|
||||
.nest("/admin", admin_routes(shared_state))
|
||||
.nest("/admin", admin_routes())
|
||||
// Add middleware to all routes
|
||||
.layer(
|
||||
ServiceBuilder::new()
|
||||
@@ -69,9 +69,9 @@ async fn main() {
|
||||
.load_shed()
|
||||
.concurrency_limit(1024)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.into_inner(),
|
||||
);
|
||||
.layer(TraceLayer::new_for_http()),
|
||||
)
|
||||
.with_state(Arc::clone(&shared_state));
|
||||
|
||||
// Run our app with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
@@ -115,7 +115,7 @@ async fn list_keys(State(state): State<SharedState>) -> String {
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn admin_routes(state: SharedState) -> Router<SharedState> {
|
||||
fn admin_routes() -> Router<SharedState> {
|
||||
async fn delete_all_keys(State(state): State<SharedState>) {
|
||||
state.write().unwrap().db.clear();
|
||||
}
|
||||
@@ -124,7 +124,7 @@ fn admin_routes(state: SharedState) -> Router<SharedState> {
|
||||
state.write().unwrap().db.remove(&key);
|
||||
}
|
||||
|
||||
Router::with_state(state)
|
||||
Router::new()
|
||||
.route("/keys", delete(delete_all_keys))
|
||||
.route("/key/:key", delete(remove_key))
|
||||
// Require bearer auth for all admin routes
|
||||
|
||||
Reference in New Issue
Block a user