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:
David Pedersen
2022-11-18 11:02:58 +00:00
committed by GitHub
parent ba8e9c1b21
commit 64960bb19c
62 changed files with 675 additions and 736 deletions
+7 -7
View File
@@ -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