make Router:state private

This commit is contained in:
David Pedersen
2022-07-03 16:29:53 +02:00
parent 90e9b34736
commit 4b6c18145d
11 changed files with 78 additions and 108 deletions
+2 -2
View File
@@ -159,7 +159,7 @@ mod tests {
let (tx, rx) = tokio::sync::oneshot::channel(); let (tx, rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move { tokio::spawn(async move {
let app = Router::new().route("/", get(handler)).state(()); let app = Router::without_state().route("/", get(handler));
let server = Server::from_tcp(listener) let server = Server::from_tcp(listener)
.unwrap() .unwrap()
.serve(app.into_make_service_with_connect_info::<SocketAddr>()); .serve(app.into_make_service_with_connect_info::<SocketAddr>());
@@ -199,7 +199,7 @@ mod tests {
let (tx, rx) = tokio::sync::oneshot::channel(); let (tx, rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move { tokio::spawn(async move {
let app = Router::new().route("/", get(handler)).state(()); let app = Router::without_state().route("/", get(handler));
let server = Server::from_tcp(listener) let server = Server::from_tcp(listener)
.unwrap() .unwrap()
.serve(app.into_make_service_with_connect_info::<MyConnectInfo>()); .serve(app.into_make_service_with_connect_info::<MyConnectInfo>());
+10 -15
View File
@@ -116,12 +116,10 @@ mod tests {
const LIMIT: u64 = 8; const LIMIT: u64 = 8;
let app = Router::new() let app = Router::without_state().route(
.route( "/",
"/", post(|_body: ContentLengthLimit<Bytes, LIMIT>| async {}),
post(|_body: ContentLengthLimit<Bytes, LIMIT>| async {}), );
)
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
let res = client let res = client
@@ -157,9 +155,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn get_request_without_content_length_is_accepted() { async fn get_request_without_content_length_is_accepted() {
let app = Router::new() let app = Router::without_state()
.route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {})) .route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -169,9 +166,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn get_request_with_content_length_is_rejected() { async fn get_request_with_content_length_is_rejected() {
let app = Router::new() let app = Router::without_state()
.route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {})) .route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -186,9 +182,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn get_request_with_chunked_encoding_is_rejected() { async fn get_request_with_chunked_encoding_is_rejected() {
let app = Router::new() let app = Router::without_state()
.route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {})) .route("/", get(|_body: ContentLengthLimit<Bytes, 1337>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
+1 -1
View File
@@ -85,7 +85,7 @@ mod tests {
host host
} }
TestClient::new(Router::new().route("/", get(host_as_body)).state(())) TestClient::new(Router::without_state().route("/", get(host_as_body)))
} }
#[tokio::test] #[tokio::test]
+9 -14
View File
@@ -140,7 +140,7 @@ mod tests {
) )
} }
let app = Router::new() let app = Router::without_state()
.route( .route(
"/:key", "/:key",
get(|path: MatchedPath| async move { path.as_str().to_owned() }), get(|path: MatchedPath| async move { path.as_str().to_owned() }),
@@ -151,8 +151,7 @@ mod tests {
Router::new().route("/assets/*path", get(handler)), Router::new().route("/assets/*path", get(handler)),
) )
.nest_service("/foo", handler.into_service(())) .nest_service("/foo", handler.into_service(()))
.layer(tower::layer::layer_fn(SetMatchedPathExtension)) .layer(tower::layer::layer_fn(SetMatchedPathExtension));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -183,17 +182,13 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn nested_opaque_routers_append_to_matched_path() { async fn nested_opaque_routers_append_to_matched_path() {
let app = Router::new() let app = Router::without_state().nest_service(
.nest_service( "/:a",
"/:a", Router::without_state().route(
Router::new() "/:b",
.route( get(|path: MatchedPath| async move { path.as_str().to_owned() }),
"/:b", ),
get(|path: MatchedPath| async move { path.as_str().to_owned() }), );
)
.state(()),
)
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
+1 -3
View File
@@ -105,9 +105,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn consume_body() { async fn consume_body() {
let app = Router::new() let app = Router::without_state().route("/", get(|body: String| async { body }));
.route("/", get(|body: String| async { body }))
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
let res = client.get("/").body("foo").send().await; let res = client.get("/").body("foo").send().await;
+1 -1
View File
@@ -258,7 +258,7 @@ mod tests {
assert!(multipart.next_field().await.unwrap().is_none()); assert!(multipart.next_field().await.unwrap().is_none());
} }
let app = Router::new().route("/", post(handle)).state(()); let app = Router::without_state().route("/", post(handle));
let client = TestClient::new(app); let client = TestClient::new(app);
+38 -50
View File
@@ -419,17 +419,15 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn extracting_url_params() { async fn extracting_url_params() {
let app = Router::new() let app = Router::without_state().route(
.route( "/users/:id",
"/users/:id", get(|Path(id): Path<i32>| async move {
get(|Path(id): Path<i32>| async move { assert_eq!(id, 42);
assert_eq!(id, 42); })
}) .post(|Path(params_map): Path<HashMap<String, i32>>| async move {
.post(|Path(params_map): Path<HashMap<String, i32>>| async move { assert_eq!(params_map.get("id").unwrap(), &1337);
assert_eq!(params_map.get("id").unwrap(), &1337); }),
}), );
)
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -442,9 +440,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn extracting_url_params_multiple_times() { async fn extracting_url_params_multiple_times() {
let app = Router::new() let app = Router::without_state()
.route("/users/:id", get(|_: Path<i32>, _: Path<String>| async {})) .route("/users/:id", get(|_: Path<i32>, _: Path<String>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -454,12 +451,10 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn percent_decoding() { async fn percent_decoding() {
let app = Router::new() let app = Router::without_state().route(
.route( "/:key",
"/:key", get(|Path(param): Path<String>| async move { param }),
get(|Path(param): Path<String>| async move { param }), );
)
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -470,7 +465,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn supports_128_bit_numbers() { async fn supports_128_bit_numbers() {
let app = Router::new() let app = Router::without_state()
.route( .route(
"/i/:key", "/i/:key",
get(|Path(param): Path<i128>| async move { param.to_string() }), get(|Path(param): Path<i128>| async move { param.to_string() }),
@@ -478,8 +473,7 @@ mod tests {
.route( .route(
"/u/:key", "/u/:key",
get(|Path(param): Path<u128>| async move { param.to_string() }), get(|Path(param): Path<u128>| async move { param.to_string() }),
) );
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -492,7 +486,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn wildcard() { async fn wildcard() {
let app = Router::new() let app = Router::without_state()
.route( .route(
"/foo/*rest", "/foo/*rest",
get(|Path(param): Path<String>| async move { param }), get(|Path(param): Path<String>| async move { param }),
@@ -502,8 +496,7 @@ mod tests {
get(|Path(params): Path<HashMap<String, String>>| async move { get(|Path(params): Path<HashMap<String, String>>| async move {
params.get("rest").unwrap().clone() params.get("rest").unwrap().clone()
}), }),
) );
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -516,7 +509,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn captures_dont_match_empty_segments() { async fn captures_dont_match_empty_segments() {
let app = Router::new().route("/:key", get(|| async {})).state(()); let app = Router::without_state().route("/:key", get(|| async {}));
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -529,9 +522,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn when_extensions_are_missing() { async fn when_extensions_are_missing() {
let app = Router::new() let app = Router::without_state()
.route("/:key", get(|_: Request<Body>, _: Path<String>| async {})) .route("/:key", get(|_: Request<Body>, _: Path<String>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -556,9 +548,8 @@ mod tests {
} }
} }
let app = Router::new() let app = Router::without_state()
.route("/:key", get(|param: Path<Param>| async move { param.0 .0 })) .route("/:key", get(|param: Path<Param>| async move { param.0 .0 }));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -572,9 +563,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn two_path_extractors() { async fn two_path_extractors() {
let app = Router::new() let app = Router::without_state()
.route("/:a/:b", get(|_: Path<String>, _: Path<String>| async {})) .route("/:a/:b", get(|_: Path<String>, _: Path<String>| async {}));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -589,20 +579,18 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn deserialize_into_vec_of_tuples() { async fn deserialize_into_vec_of_tuples() {
let app = Router::new() let app = Router::without_state().route(
.route( "/:a/:b",
"/:a/:b", get(|Path(params): Path<Vec<(String, String)>>| async move {
get(|Path(params): Path<Vec<(String, String)>>| async move { assert_eq!(
assert_eq!( params,
params, vec![
vec![ ("a".to_owned(), "foo".to_owned()),
("a".to_owned(), "foo".to_owned()), ("b".to_owned(), "bar".to_owned())
("b".to_owned(), "bar".to_owned()) ]
] );
); }),
}), );
)
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
+4 -5
View File
@@ -226,7 +226,7 @@ mod tests {
async fn multiple_request_extractors() { async fn multiple_request_extractors() {
async fn handler(_: Request<Body>, _: Request<Body>) {} async fn handler(_: Request<Body>, _: Request<Body>) {}
let app = Router::new().route("/", post(handler)).state(()); let app = Router::without_state().route("/", post(handler));
let client = TestClient::new(app); let client = TestClient::new(app);
@@ -252,10 +252,9 @@ mod tests {
} }
let client = TestClient::new( let client = TestClient::new(
Router::new() Router::without_state()
.route("/", get(handler)) .route("/", get(handler))
.layer(Extension(Ext)) .layer(Extension(Ext)),
.state(()),
); );
let res = client.get("/").header("x-foo", "123").send().await; let res = client.get("/").header("x-foo", "123").send().await;
@@ -271,7 +270,7 @@ mod tests {
assert_eq!(body, "foo"); assert_eq!(body, "foo");
} }
let client = TestClient::new(Router::new().route("/", get(handler)).state(())); let client = TestClient::new(Router::without_state().route("/", get(handler)));
let res = client.get("/").body("foo").send().await; let res = client.get("/").body("foo").send().await;
assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.status(), StatusCode::OK);
+6 -12
View File
@@ -222,9 +222,8 @@ mod tests {
foo: String, foo: String,
} }
let app = Router::new() let app =
.route("/", post(|input: Json<Input>| async { input.0.foo })) Router::without_state().route("/", post(|input: Json<Input>| async { input.0.foo }));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
let res = client.post("/").json(&json!({ "foo": "bar" })).send().await; let res = client.post("/").json(&json!({ "foo": "bar" })).send().await;
@@ -240,9 +239,8 @@ mod tests {
foo: String, foo: String,
} }
let app = Router::new() let app =
.route("/", post(|input: Json<Input>| async { input.0.foo })) Router::without_state().route("/", post(|input: Json<Input>| async { input.0.foo }));
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
let res = client.post("/").body(r#"{ "foo": "bar" }"#).send().await; let res = client.post("/").body(r#"{ "foo": "bar" }"#).send().await;
@@ -258,9 +256,7 @@ mod tests {
async fn valid_json_content_type(content_type: &str) -> bool { async fn valid_json_content_type(content_type: &str) -> bool {
println!("testing {:?}", content_type); println!("testing {:?}", content_type);
let app = Router::new() let app = Router::without_state().route("/", post(|Json(_): Json<Value>| async {}));
.route("/", post(|Json(_): Json<Value>| async {}))
.state(());
let res = TestClient::new(app) let res = TestClient::new(app)
.post("/") .post("/")
@@ -281,9 +277,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn invalid_json_syntax() { async fn invalid_json_syntax() {
let app = Router::new() let app = Router::without_state().route("/", post(|_: Json<serde_json::Value>| async {}));
.route("/", post(|_: Json<serde_json::Value>| async {}))
.state(());
let client = TestClient::new(app); let client = TestClient::new(app);
let res = client let res = client
+5 -4
View File
@@ -141,8 +141,7 @@ where
} }
} }
/// TODO(david): docs fn state(self, state: S) -> Router<S, B, WithState>
pub fn state(self, state: S) -> Router<S, B, WithState>
where where
S: Clone, S: Clone,
{ {
@@ -151,8 +150,10 @@ where
.into_iter() .into_iter()
.map(|(id, endpoint)| { .map(|(id, endpoint)| {
let endpoint = match endpoint { let endpoint = match endpoint {
Endpoint::MethodRouter(router) => { Endpoint::MethodRouter(method_router) => {
Endpoint::MethodRouter(router.state(state.clone())) // the state will be provided later in `<Router as Service>::call`, so its safe to
// ignore that it hasn't been provided yet
Endpoint::MethodRouter(method_router.change_state_marker())
} }
Endpoint::Route(route) => Endpoint::Route(route), Endpoint::Route(route) => Endpoint::Route(route),
}; };
+1 -1
View File
@@ -178,7 +178,7 @@ mod tests {
user_agent.to_string() user_agent.to_string()
} }
let app = Router::new().route("/", get(handle)).state(()); let app = Router::without_state().route("/", get(handle));
let client = TestClient::new(app); let client = TestClient::new(app);