{"repo":"axum","file":"axum/benches/benches.rs","line":15,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n if on_ci() {\n install_rewrk();\n } else {\n ensure_rewrk_is_installed();\n }\n\n benchmark(\"minimal\").run(Router::new);\n\n benchmark(\"basic\")\n .path(\"/a/b/c\")\n .run(|| Router::new().route(\"/a/b/c\", get(|| async { \"Hello, World!\" })));\n\n benchmark(\"basic-merge\").path(\"/a/b/c\").run(|| {\n let inner = Router::new().route(\"/a/b/c\", get(|| async { \"Hello, World!\" }));\n Router::new().merge(inner)\n });\n\n benchmark(\"basic-nest\").path(\"/a/b/c\").run(|| {\n let c = Router::new().route(\"/c\", get(|| async { \"Hello, World!\" }));\n let b = Router::new().nest(\"/b\", c);\n Router::new().nest(\"/a\", b)\n });\n\n benchmark(\"routing\").path(\"/foo/bar/baz\").run(|| {\n let mut app = Router::new();\n for a in 0..10 {\n for b in 0..10 {\n for c in 0..10 {\n app = app.route(&format!(\"/foo-{a}/bar-{b}/baz-{c}\"), get(|| async {}));\n }\n }\n }\n app.route(\"/foo/bar/baz\", get(|| async {}))\n });\n\n benchmark(\"receive-json\")\n .method(\"post\")\n .headers(&[(\"content-type\", \"application/json\")])\n .body(r#\"{\"n\": 1"} {"repo":"axum","file":"axum/benches/benches.rs","line":93,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n _string: String,\n _vec: Vec,\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":99,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {\n n: u32,\n s: String,\n b: bool,\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":105,"symbol":"benchmark","kind":"function","lang":"rust","code":"fn benchmark(name: &'static str) -> BenchmarkBuilder {\n BenchmarkBuilder {\n name,\n path: None,\n method: None,\n headers: None,\n body: None,\n }\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":115,"symbol":"BenchmarkBuilder","kind":"type","lang":"rust","code":"struct BenchmarkBuilder {\n name: &'static str,\n path: Option<&'static str>,\n method: Option<&'static str>,\n headers: Option<&'static [(&'static str, &'static str)]>,\n body: Option<&'static str>,\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":138,"symbol":"run","kind":"function","lang":"rust","code":"fn run(self, f: F)\n where\n F: FnOnce() -> Router<()>,\n {\n // support only running some benchmarks with\n // ```\n // cargo bench -- routing send-json\n // ```\n let args = std::env::args().collect::>();\n if args.len() != 1 {\n let names = &args[1..args.len() - 1];\n if !names.is_empty() && !names.contains(&self.name.to_owned()) {\n return;\n }\n }\n\n let app = f();\n\n let rt = tokio::runtime::Builder::new_multi_thread()\n .enable_all()\n .build()\n .unwrap();\n\n let listener = rt\n .block_on(tokio::net::TcpListener::bind(\"0.0.0.0:0\"))\n .unwrap();\n let addr = listener.local_addr().unwrap();\n\n #[allow(unreachable_code)] // buggy lint, fixed in nightly\n std::thread::spawn(move || {\n rt.block_on(axum::serve(listener, app).into_future());\n });\n\n let mut cmd = Command::new(\"rewrk\");\n cmd.stdout(Stdio::piped());\n\n cmd.arg(\"--host\");\n cmd.arg(format!(\"http://{addr}{}\", self.path.unwrap_or(\"\")));\n\n cmd.args([\"--connections\", \"10\"]);\n "} {"repo":"axum","file":"axum/benches/benches.rs","line":221,"symbol":"install_rewrk","kind":"function","lang":"rust","code":"fn install_rewrk() {\n println!(\"installing rewrk\");\n let mut cmd = Command::new(\"cargo\");\n cmd.args([\n \"install\",\n \"rewrk\",\n \"--git\",\n \"https://github.com/ChillFish8/rewrk.git\",\n ]);\n let status = cmd\n .status()\n .unwrap_or_else(|_| panic!(\"failed to install rewrk\"));\n if !status.success() {\n panic!(\"failed to install rewrk\");\n }\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":238,"symbol":"ensure_rewrk_is_installed","kind":"function","lang":"rust","code":"fn ensure_rewrk_is_installed() {\n let mut cmd = Command::new(\"rewrk\");\n cmd.arg(\"--help\");\n cmd.stdout(Stdio::null());\n cmd.stderr(Stdio::null());\n cmd.status().unwrap_or_else(|_| {\n panic!(\"rewrk is not installed. See https://github.com/lnx-search/rewrk\")\n });\n}"} {"repo":"axum","file":"axum/benches/benches.rs","line":248,"symbol":"on_ci","kind":"function","lang":"rust","code":"fn on_ci() -> bool {\n std::env::var(\"GITHUB_ACTIONS\").is_ok()\n}"} {"repo":"axum","file":"axum/src/body/mod.rs","line":48,"symbol":"to_bytes","kind":"function","lang":"rust","doc":"let source = std::error::Error::source(&err).unwrap(); assert!(source.is::()); } } # } ```","code":"pub async fn to_bytes(body: Body, limit: usize) -> Result {\n Limited::new(body, limit)\n .collect()\n .await\n .map(|col| col.to_bytes())\n .map_err(axum_core::Error::new)\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":12,"symbol":"BoxedIntoRoute","kind":"type","lang":"rust","code":"pub(crate) struct BoxedIntoRoute(Box>);"} {"repo":"axum","file":"axum/src/boxed.rs","line":18,"symbol":"from_handler","kind":"function","lang":"rust","code":"pub(crate) fn from_handler(handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n Self(Box::new(MakeErasedHandler {\n handler,\n into_route: |handler, state| Route::new(Handler::with_state(handler, state)),\n }))\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":31,"symbol":"map","kind":"function","lang":"rust","code":"pub(crate) fn map(self, f: F) -> BoxedIntoRoute\n where\n S: 'static,\n E: 'static,\n F: FnOnce(Route) -> Route + Clone + Send + Sync + 'static,\n E2: 'static,\n {\n BoxedIntoRoute(Box::new(Map {\n inner: self.0,\n layer: Box::new(f),\n }))\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":44,"symbol":"into_route","kind":"function","lang":"rust","code":"pub(crate) fn into_route(self, state: S) -> Route {\n self.0.into_route(state)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":50,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self(self.0.clone_box())\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":56,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_tuple(\"BoxedIntoRoute\").finish()\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":61,"symbol":"ErasedIntoRoute","kind":"type","lang":"rust","code":"pub(crate) trait ErasedIntoRoute: Send + Sync {\n fn clone_box(&self) -> Box>;\n\n fn into_route(self: Box, state: S) -> Route;\n\n #[allow(dead_code)]\n fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture;\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":62,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box>;"} {"repo":"axum","file":"axum/src/boxed.rs","line":64,"symbol":"into_route","kind":"function","lang":"rust","code":"fn into_route(self: Box, state: S) -> Route;"} {"repo":"axum","file":"axum/src/boxed.rs","line":67,"symbol":"call_with_state","kind":"function","lang":"rust","code":"fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture;"} {"repo":"axum","file":"axum/src/boxed.rs","line":70,"symbol":"MakeErasedHandler","kind":"type","lang":"rust","code":"pub(crate) struct MakeErasedHandler {\n pub(crate) handler: H,\n pub(crate) into_route: fn(H, S) -> Route,\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":80,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box> {\n Box::new(self.clone())\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":84,"symbol":"into_route","kind":"function","lang":"rust","code":"fn into_route(self: Box, state: S) -> Route {\n (self.into_route)(self.handler, state)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":88,"symbol":"call_with_state","kind":"function","lang":"rust","code":"fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture {\n self.into_route(state).call(request)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":97,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n handler: self.handler.clone(),\n into_route: self.into_route,\n }\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":106,"symbol":"MakeErasedRouter","kind":"type","lang":"rust","code":"pub(crate) struct MakeErasedRouter {\n pub(crate) router: Router,\n pub(crate) into_route: fn(Router, S) -> Route,\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":115,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box> {\n Box::new(self.clone())\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":119,"symbol":"into_route","kind":"function","lang":"rust","code":"fn into_route(self: Box, state: S) -> Route {\n (self.into_route)(self.router, state)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":123,"symbol":"call_with_state","kind":"function","lang":"rust","code":"fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture {\n self.router.call_with_state(request, state)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":132,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n router: self.router.clone(),\n into_route: self.into_route,\n }\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":140,"symbol":"Map","kind":"type","lang":"rust","code":"pub(crate) struct Map {\n pub(crate) inner: Box>,\n pub(crate) layer: Box>,\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":151,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box> {\n Box::new(Self {\n inner: self.inner.clone_box(),\n layer: self.layer.clone_box(),\n })\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":158,"symbol":"into_route","kind":"function","lang":"rust","code":"fn into_route(self: Box, state: S) -> Route {\n (self.layer)(self.inner.into_route(state))\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":162,"symbol":"call_with_state","kind":"function","lang":"rust","code":"fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture {\n (self.layer)(self.inner.into_route(state)).call(request)\n }"} {"repo":"axum","file":"axum/src/boxed.rs","line":167,"symbol":"LayerFn","kind":"type","lang":"rust","code":"pub(crate) trait LayerFn: FnOnce(Route) -> Route + Send + Sync {\n fn clone_box(&self) -> Box>;\n}"} {"repo":"axum","file":"axum/src/boxed.rs","line":168,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box>;"} {"repo":"axum","file":"axum/src/boxed.rs","line":175,"symbol":"clone_box","kind":"function","lang":"rust","code":"fn clone_box(&self) -> Box> {\n Box::new(self.clone())\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":23,"symbol":"HandleErrorLayer","kind":"type","lang":"rust","doc":"[`Layer`] that applies [`HandleError`] which is a [`Service`] adapter that handles errors by converting them into responses. See [module docs](self) for more details on axum's error handling model.","code":"pub struct HandleErrorLayer {\n f: F,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":30,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `HandleErrorLayer`.","code":"pub fn new(f: F) -> Self {\n Self {\n f,\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":42,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":51,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"HandleErrorLayer\")\n .field(\"f\", &format_args!(\"{}\", std::any::type_name::()))\n .finish()\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":64,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n HandleError::new(inner, self.f.clone())\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":72,"symbol":"HandleError","kind":"type","lang":"rust","doc":"A [`Service`] adapter that handles errors by converting them into responses. See [module docs](self) for more details on axum's error handling model.","code":"pub struct HandleError {\n inner: S,\n f: F,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":80,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `HandleError`.","code":"pub fn new(inner: S, f: F) -> Self {\n Self {\n inner,\n f,\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":94,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n inner: self.inner.clone(),\n f: self.f.clone(),\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":107,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"HandleError\")\n .field(\"inner\", &self.inner)\n .field(\"f\", &format_args!(\"{}\", std::any::type_name::()))\n .finish()\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":130,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":134,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n let f = self.f.clone();\n\n let clone = self.inner.clone();\n let inner = std::mem::replace(&mut self.inner, clone);\n\n let future = Box::pin(async move {\n match inner.oneshot(req).await {\n Ok(res) => Ok(res.into_response()),\n Err(err) => Ok(f(err).await.into_response()),\n }\n });\n\n future::HandleErrorFuture { future }\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":250,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n self.project().future.poll(cx)\n }"} {"repo":"axum","file":"axum/src/error_handling/mod.rs","line":257,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n\n assert_send::>();\n assert_sync::>();\n}"} {"repo":"axum","file":"axum/src/extension.rs","line":72,"symbol":"Extension","kind":"type","lang":"rust","doc":") } #[derive(Clone)] struct Foo(&'static str); ```","code":"pub struct Extension(pub T);"} {"repo":"axum","file":"axum/src/extension.rs","line":78,"symbol":"from_extensions","kind":"function","lang":"rust","code":"fn from_extensions(extensions: &Extensions) -> Option {\n extensions.get::().cloned().map(Extension)\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":90,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(req: &mut Parts, _state: &S) -> Result {\n Ok(Self::from_extensions(&req.extensions).ok_or_else(|| {\n MissingExtension::from_err(format!(\n \"Extension of type `{}` was not found. Perhaps you forgot to add it? See `axum::Extension`.\",\n std::any::type_name::()\n ))\n })?)\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":107,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n req: &mut Parts,\n _state: &S,\n ) -> Result, Self::Rejection> {\n Ok(Self::from_extensions(&req.extensions))\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":123,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n res.extensions_mut().insert(self.0);\n Ok(res)\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":133,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n res.extensions_mut().insert(self.0);\n res\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":146,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n AddExtension {\n inner,\n value: self.0.clone(),\n }\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":164,"symbol":"AddExtension","kind":"type","lang":"rust","doc":"for more details. [request extensions]: https://docs.rs/http/latest/http/struct.Extensions.html If you need a layer to add an extension to every request, use the [Layer](tower::Layer) implementation of [Extension].","code":"pub struct AddExtension {\n pub(crate) inner: S,\n pub(crate) value: T,\n}"} {"repo":"axum","file":"axum/src/extension.rs","line":179,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":183,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, mut req: Request) -> Self::Future {\n req.extensions_mut().insert(self.value.clone());\n self.inner.call(req)\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":198,"symbol":"Foo","kind":"type","lang":"rust","code":"struct Foo(String);"} {"repo":"axum","file":"axum/src/extension.rs","line":201,"symbol":"Bar","kind":"type","lang":"rust","code":"struct Bar(String);"} {"repo":"axum","file":"axum/src/extension.rs","line":204,"symbol":"extension_extractor","kind":"function","lang":"rust","code":"async fn extension_extractor() {\n async fn requires_foo(Extension(foo): Extension) -> String {\n foo.0\n }\n\n async fn optional_foo(extension: Option>) -> String {\n extension.map(|foo| foo.0 .0).unwrap_or(\"none\".to_owned())\n }\n\n async fn requires_bar(Extension(bar): Extension) -> String {\n bar.0\n }\n\n async fn optional_bar(extension: Option>) -> String {\n extension.map(|bar| bar.0 .0).unwrap_or(\"none\".to_owned())\n }\n\n let app = Router::new()\n .route(\"/requires_foo\", get(requires_foo))\n .route(\"/optional_foo\", get(optional_foo))\n .route(\"/requires_bar\", get(requires_bar))\n .route(\"/optional_bar\", get(optional_bar))\n .layer(Extension(Foo(\"foo\".to_owned())));\n\n let client = TestClient::new(app);\n\n let response = client.get(\"/requires_foo\").await;\n assert_eq!(response.status(), StatusCode::OK);\n assert_eq!(response.text().await, \"foo\");\n\n let response = client.get(\"/optional_foo\").await;\n assert_eq!(response.status(), StatusCode::OK);\n assert_"} {"repo":"axum","file":"axum/src/extension.rs","line":205,"symbol":"requires_foo","kind":"function","lang":"rust","code":"async fn requires_foo(Extension(foo): Extension) -> String {\n foo.0\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":209,"symbol":"optional_foo","kind":"function","lang":"rust","code":"async fn optional_foo(extension: Option>) -> String {\n extension.map(|foo| foo.0 .0).unwrap_or(\"none\".to_owned())\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":213,"symbol":"requires_bar","kind":"function","lang":"rust","code":"async fn requires_bar(Extension(bar): Extension) -> String {\n bar.0\n }"} {"repo":"axum","file":"axum/src/extension.rs","line":217,"symbol":"optional_bar","kind":"function","lang":"rust","code":"async fn optional_bar(extension: Option>) -> String {\n extension.map(|bar| bar.0 .0).unwrap_or(\"none\".to_owned())\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":28,"symbol":"IntoMakeServiceWithConnectInfo","kind":"type","lang":"rust","doc":"A [`MakeService`] created from a router. See [`Router::into_make_service_with_connect_info`] for more details. [`MakeService`]: tower::make::MakeService [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info","code":"pub struct IntoMakeServiceWithConnectInfo {\n svc: S,\n _connect_info: PhantomData C>,\n}"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":34,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(svc: S) -> Self {\n Self {\n svc,\n _connect_info: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":46,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"IntoMakeServiceWithConnectInfo\")\n .field(\"svc\", &self.svc)\n .finish()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":57,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n svc: self.svc.clone(),\n _connect_info: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":74,"symbol":"Connected","kind":"type","lang":"rust","doc":"The goal for this trait is to allow users to implement custom IO types that can still provide the same connection metadata. See [`Router::into_make_service_with_connect_info`] for more details. [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info","code":"pub trait Connected: Clone + Send + Sync + 'static {\n /// Create type holding information about the connection.\n fn connect_info(stream: T) -> Self;\n}"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":76,"symbol":"connect_info","kind":"function","lang":"rust","doc":"Create type holding information about the connection.","code":"fn connect_info(stream: T) -> Self;"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":87,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(stream: serve::IncomingStream<'_, L>) -> Self {\n *stream.remote_addr()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":94,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(remote_addr: Self) -> Self {\n remote_addr\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":109,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":113,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, target: T) -> Self::Future {\n let connect_info = ConnectInfo(C::connect_info(target));\n let svc = Extension(connect_info).layer(self.svc.clone());\n ResponseFuture::new(ready(Ok(svc)))\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":136,"symbol":"ConnectInfo","kind":"type","lang":"rust","doc":"[`Router::into_make_service_with_connect_info`] to run your app otherwise it will fail at runtime. See [`Router::into_make_service_with_connect_info`] for more details. [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info","code":"pub struct ConnectInfo(pub T);"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":145,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n match Extension::::from_request_parts(parts, state).await {\n Ok(Extension(connect_info)) => Ok(connect_info),\n Err(err) => match parts.extensions.get::>() {\n Some(MockConnectInfo(connect_info)) => Ok(Self(connect_info.clone())),\n None => Err(err),\n },\n }\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":206,"symbol":"MockConnectInfo","kind":"type","lang":"rust","doc":"# async fn main() { # some_test().await; # } ``` [`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info","code":"pub struct MockConnectInfo(pub T);"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":214,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n Extension(self.clone()).layer(inner)\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":229,"symbol":"into_make_service_traits","kind":"function","lang":"rust","code":"fn into_make_service_traits() {\n use crate::test_helpers::*;\n assert_send::>();\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":236,"symbol":"connected_traits","kind":"function","lang":"rust","code":"fn connected_traits() {\n // Test that the `Connected` trait can be used with custom address and listener types.\n\n fn create_router() -> Router {\n todo!()\n }\n\n fn tcp_listener() -> TcpListener {\n todo!()\n }\n\n #[derive(Clone)]\n struct CustomAddr(SocketAddr);\n\n impl Connected> for CustomAddr {\n fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {\n todo!()\n }\n }\n\n impl Connected> for CustomAddr {\n fn connect_info(_stream: IncomingStream<'_, CustomListener>) -> Self {\n todo!()\n }\n }\n\n struct CustomListener {}\n\n impl Listener for CustomListener {\n type Io = TcpStream;\n type Addr = SocketAddr;\n\n async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n todo!()\n }\n\n fn local_addr(&self) -> tokio::io::Result {\n todo!()\n }\n }\n\n fn custom_connected() {\n let router = create_router();\n let _"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":239,"symbol":"create_router","kind":"function","lang":"rust","code":"fn create_router() -> Router {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":243,"symbol":"tcp_listener","kind":"function","lang":"rust","code":"fn tcp_listener() -> TcpListener {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":248,"symbol":"CustomAddr","kind":"type","lang":"rust","code":"struct CustomAddr(SocketAddr);"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":251,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":257,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(_stream: IncomingStream<'_, CustomListener>) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":262,"symbol":"CustomListener","kind":"type","lang":"rust","code":"struct CustomListener {}"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":268,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":272,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> tokio::io::Result {\n todo!()\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":277,"symbol":"custom_connected","kind":"function","lang":"rust","code":"fn custom_connected() {\n let router = create_router();\n let _ = crate::serve(\n tcp_listener(),\n router.into_make_service_with_connect_info::(),\n );\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":285,"symbol":"custom_listener","kind":"function","lang":"rust","code":"fn custom_listener() {\n let router = create_router();\n let _ = crate::serve(CustomListener {}, router.into_make_service());\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":290,"symbol":"custom_listener_with_connect","kind":"function","lang":"rust","code":"fn custom_listener_with_connect() {\n let router = create_router();\n let _ = crate::serve(\n CustomListener {},\n router.into_make_service_with_connect_info::(),\n );\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":298,"symbol":"custom_listener_with_custom_connect","kind":"function","lang":"rust","code":"fn custom_listener_with_custom_connect() {\n let router = create_router();\n let _ = crate::serve(\n CustomListener {},\n router.into_make_service_with_connect_info::(),\n );\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":308,"symbol":"socket_addr","kind":"function","lang":"rust","code":"async fn socket_addr() {\n async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let addr = listener.local_addr().unwrap();\n\n let (tx, rx) = tokio::sync::oneshot::channel();\n tokio::spawn(async move {\n let app = Router::new().route(\"/\", get(handler));\n tx.send(()).unwrap();\n crate::serve(\n listener,\n app.into_make_service_with_connect_info::(),\n )\n .await;\n });\n rx.await.unwrap();\n\n let client = reqwest::Client::new();\n\n let res = client.get(format!(\"http://{addr}\")).send().await.unwrap();\n let body = res.text().await.unwrap();\n assert!(body.starts_with(\"127.0.0.1:\"));\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":309,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":336,"symbol":"custom","kind":"function","lang":"rust","code":"async fn custom() {\n #[derive(Clone, Debug)]\n struct MyConnectInfo {\n value: &'static str,\n }\n\n impl Connected> for MyConnectInfo {\n fn connect_info(_target: IncomingStream<'_, TcpListener>) -> Self {\n Self {\n value: \"it worked!\",\n }\n }\n }\n\n async fn handler(ConnectInfo(addr): ConnectInfo) -> &'static str {\n addr.value\n }\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let addr = listener.local_addr().unwrap();\n\n let (tx, rx) = tokio::sync::oneshot::channel();\n tokio::spawn(async move {\n let app = Router::new().route(\"/\", get(handler));\n tx.send(()).unwrap();\n crate::serve(\n listener,\n app.into_make_service_with_connect_info::(),\n )\n .await;\n });\n rx.await.unwrap();\n\n let client = reqwest::Client::new();\n\n let res = client.get(format!(\"http://{addr}\")).send().await.unwrap();\n let body = res.text().await.unwrap();\n "} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":338,"symbol":"MyConnectInfo","kind":"type","lang":"rust","code":"struct MyConnectInfo {\n value: &'static str,\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":343,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(_target: IncomingStream<'_, TcpListener>) -> Self {\n Self {\n value: \"it worked!\",\n }\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":350,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ConnectInfo(addr): ConnectInfo) -> &'static str {\n addr.value\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":377,"symbol":"mock_connect_info","kind":"function","lang":"rust","code":"async fn mock_connect_info() {\n async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }\n\n let app = Router::new()\n .route(\"/\", get(handler))\n .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert!(body.starts_with(\"0.0.0.0:1337\"));\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":378,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":394,"symbol":"both_mock_and_real_connect_info","kind":"function","lang":"rust","code":"async fn both_mock_and_real_connect_info() {\n async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let addr = listener.local_addr().unwrap();\n\n tokio::spawn(async move {\n let app = Router::new()\n .route(\"/\", get(handler))\n .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337))));\n\n crate::serve(\n listener,\n app.into_make_service_with_connect_info::(),\n )\n .await;\n });\n\n let client = reqwest::Client::new();\n\n let res = client.get(format!(\"http://{addr}\")).send().await.unwrap();\n let body = res.text().await.unwrap();\n assert!(body.starts_with(\"127.0.0.1:\"));\n }"} {"repo":"axum","file":"axum/src/extract/connect_info.rs","line":395,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ConnectInfo(addr): ConnectInfo) -> String {\n format!(\"{addr}\")\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":57,"symbol":"MatchedPath","kind":"type","lang":"rust","doc":"}; tracing::info_span!(\"http-request\", %path) }), ); # let _: Router = app; ```","code":"pub struct MatchedPath(pub(crate) Arc);"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":62,"symbol":"as_str","kind":"function","lang":"rust","doc":"Returns a `str` representation of the path.","code":"pub fn as_str(&self) -> &str {\n &self.0\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":73,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let matched_path = parts\n .extensions\n .get::()\n .ok_or(MatchedPathRejection::MatchedPathMissing(MatchedPathMissing))?\n .clone();\n\n Ok(matched_path)\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":90,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n _state: &S,\n ) -> Result, Self::Rejection> {\n Ok(parts.extensions.get::().cloned())\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":99,"symbol":"MatchedNestedPath","kind":"type","lang":"rust","code":"struct MatchedNestedPath(Arc);"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":101,"symbol":"set_matched_path_for_request","kind":"function","lang":"rust","code":"pub(crate) fn set_matched_path_for_request(\n id: RouteId,\n route_id_to_path: &HashMap>,\n extensions: &mut http::Extensions,\n) {\n let Some(matched_path) = route_id_to_path.get(&id) else {\n #[cfg(debug_assertions)]\n panic!(\"should always have a matched path for a route id\");\n #[cfg(not(debug_assertions))]\n return;\n };\n\n let matched_path = append_nested_matched_path(matched_path, extensions);\n\n if matched_path.ends_with(NEST_TAIL_PARAM_CAPTURE) {\n extensions.insert(MatchedNestedPath(matched_path));\n debug_assert!(extensions.remove::().is_none());\n } else {\n extensions.insert(MatchedPath(matched_path));\n extensions.remove::();\n }\n}"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":125,"symbol":"append_nested_matched_path","kind":"function","lang":"rust","doc":"a previous `MatchedPath` might exist if we're inside a nested Router","code":"fn append_nested_matched_path(matched_path: &Arc, extensions: &http::Extensions) -> Arc {\n if let Some(previous) = extensions\n .get::()\n .map(|matched_path| matched_path.as_str())\n .or_else(|| Some(&extensions.get::()?.0))\n {\n let previous = previous\n .strip_suffix(NEST_TAIL_PARAM_CAPTURE)\n .unwrap_or(previous);\n\n let matched_path = format!(\"{previous}{matched_path}\");\n matched_path.into()\n } else {\n Arc::clone(matched_path)\n }\n}"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":156,"symbol":"extracting_on_handler","kind":"function","lang":"rust","code":"async fn extracting_on_handler() {\n let app = Router::new().route(\n \"/{a}\",\n get(|path: MatchedPath| async move { path.as_str().to_owned() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.text().await, \"/{a}\");\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":169,"symbol":"extracting_on_handler_in_nested_router","kind":"function","lang":"rust","code":"async fn extracting_on_handler_in_nested_router() {\n let app = Router::new().nest(\n \"/{a}\",\n Router::new().route(\n \"/{b}\",\n get(|path: MatchedPath| async move { path.as_str().to_owned() }),\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.text().await, \"/{a}/{b}\");\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":185,"symbol":"extracting_on_handler_in_deeply_nested_router","kind":"function","lang":"rust","code":"async fn extracting_on_handler_in_deeply_nested_router() {\n let app = Router::new().nest(\n \"/{a}\",\n Router::new().nest(\n \"/{b}\",\n Router::new().route(\n \"/{c}\",\n get(|path: MatchedPath| async move { path.as_str().to_owned() }),\n ),\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.text().await, \"/{a}/{b}/{c}\");\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":204,"symbol":"cannot_extract_nested_matched_path_in_middleware","kind":"function","lang":"rust","code":"async fn cannot_extract_nested_matched_path_in_middleware() {\n async fn extract_matched_path(\n matched_path: Option,\n req: Request,\n ) -> Request {\n assert!(matched_path.is_none());\n req\n }\n\n let app = Router::new()\n .nest_service(\"/{a}\", Router::new().route(\"/{b}\", get(|| async move {})))\n .layer(map_request(extract_matched_path));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":205,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(\n matched_path: Option,\n req: Request,\n ) -> Request {\n assert!(matched_path.is_none());\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":224,"symbol":"can_extract_nested_matched_path_in_middleware_using_nest","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_in_middleware_using_nest() {\n async fn extract_matched_path(\n matched_path: Option,\n req: Request,\n ) -> Request {\n assert_eq!(matched_path.unwrap().as_str(), \"/{a}/{b}\");\n req\n }\n\n let app = Router::new()\n .nest(\"/{a}\", Router::new().route(\"/{b}\", get(|| async move {})))\n .layer(map_request(extract_matched_path));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":225,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(\n matched_path: Option,\n req: Request,\n ) -> Request {\n assert_eq!(matched_path.unwrap().as_str(), \"/{a}/{b}\");\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":244,"symbol":"cannot_extract_nested_matched_path_in_middleware_via_extension","kind":"function","lang":"rust","code":"async fn cannot_extract_nested_matched_path_in_middleware_via_extension() {\n async fn assert_no_matched_path(req: Request) -> Request {\n assert!(req.extensions().get::().is_none());\n req\n }\n\n let app = Router::new()\n .nest_service(\"/{a}\", Router::new().route(\"/{b}\", get(|| async move {})))\n .layer(map_request(assert_no_matched_path));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":245,"symbol":"assert_no_matched_path","kind":"function","lang":"rust","code":"async fn assert_no_matched_path(req: Request) -> Request {\n assert!(req.extensions().get::().is_none());\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":261,"symbol":"can_extract_nested_matched_path_in_middleware_via_extension_using_nest","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_in_middleware_via_extension_using_nest() {\n async fn assert_matched_path(req: Request) -> Request {\n assert!(req.extensions().get::().is_some());\n req\n }\n\n let app = Router::new()\n .nest(\"/{a}\", Router::new().route(\"/{b}\", get(|| async move {})))\n .layer(map_request(assert_matched_path));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":262,"symbol":"assert_matched_path","kind":"function","lang":"rust","code":"async fn assert_matched_path(req: Request) -> Request {\n assert!(req.extensions().get::().is_some());\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":278,"symbol":"can_extract_nested_matched_path_in_middleware_on_nested_router","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_in_middleware_on_nested_router() {\n async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/{a}/{b}\");\n req\n }\n\n let app = Router::new().nest(\n \"/{a}\",\n Router::new()\n .route(\"/{b}\", get(|| async move {}))\n .layer(map_request(extract_matched_path)),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":279,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/{a}/{b}\");\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":298,"symbol":"can_extract_nested_matched_path_with_prefix_in_middleware_on_nested_router","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_with_prefix_in_middleware_on_nested_router() {\n async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/foo{one}/bar{two}\");\n req\n }\n\n let app = Router::new().nest(\n \"/foo{one}\",\n Router::new()\n .route(\"/bar{two}\", get(|| async move {}))\n .layer(map_request(extract_matched_path)),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo1/bar2\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":299,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/foo{one}/bar{two}\");\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":318,"symbol":"can_extract_nested_matched_path_with_prefix_and_suffix_in_middleware_on_nested_router","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_with_prefix_and_suffix_in_middleware_on_nested_router()\n {\n async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/foo{one}foo/bar{two}bar\");\n req\n }\n\n let app = Router::new().nest(\n \"/foo{one}foo\",\n Router::new()\n .route(\"/bar{two}bar\", get(|| async move {}))\n .layer(map_request(extract_matched_path)),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo1foo/bar2bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":320,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(matched_path: MatchedPath, req: Request) -> Request {\n assert_eq!(matched_path.as_str(), \"/foo{one}foo/bar{two}bar\");\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":339,"symbol":"can_extract_nested_matched_path_in_middleware_on_nested_router_via_extension","kind":"function","lang":"rust","code":"async fn can_extract_nested_matched_path_in_middleware_on_nested_router_via_extension() {\n async fn extract_matched_path(req: Request) -> Request {\n let matched_path = req.extensions().get::().unwrap();\n assert_eq!(matched_path.as_str(), \"/{a}/{b}\");\n req\n }\n\n let app = Router::new().nest(\n \"/{a}\",\n Router::new()\n .route(\"/{b}\", get(|| async move {}))\n .layer(map_request(extract_matched_path)),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":340,"symbol":"extract_matched_path","kind":"function","lang":"rust","code":"async fn extract_matched_path(req: Request) -> Request {\n let matched_path = req.extensions().get::().unwrap();\n assert_eq!(matched_path.as_str(), \"/{a}/{b}\");\n req\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":360,"symbol":"extracting_on_nested_handler","kind":"function","lang":"rust","code":"async fn extracting_on_nested_handler() {\n async fn handler(path: Option) {\n assert!(path.is_none());\n }\n\n let app = Router::new().nest_service(\"/{a}\", handler.into_service());\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":361,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(path: Option) {\n assert!(path.is_none());\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":375,"symbol":"doesnt_panic_if_router_called_from_wildcard_route","kind":"function","lang":"rust","doc":"https://github.com/tokio-rs/axum/issues/1579","code":"async fn doesnt_panic_if_router_called_from_wildcard_route() {\n use tower::ServiceExt;\n\n let app = Router::new().route(\n \"/{*path}\",\n any(|req: Request| {\n Router::new()\n .nest(\"/foo\", Router::new().route(\"/bar\", get(|| async {})))\n .oneshot(req)\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":394,"symbol":"cant_extract_in_fallback","kind":"function","lang":"rust","code":"async fn cant_extract_in_fallback() {\n async fn handler(path: Option, req: Request) {\n assert!(path.is_none());\n assert!(req.extensions().get::().is_none());\n }\n\n let app = Router::new().fallback(handler);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":395,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(path: Option, req: Request) {\n assert!(path.is_none());\n assert!(req.extensions().get::().is_none());\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":409,"symbol":"matching_colon","kind":"function","lang":"rust","code":"async fn matching_colon() {\n let app = Router::new().route(\n \"/:foo\",\n get(|path: MatchedPath| async move { path.as_str().to_owned() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/:foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/:foo\");\n\n let res = client.get(\"/:bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n }"} {"repo":"axum","file":"axum/src/extract/matched_path.rs","line":429,"symbol":"matching_asterisk","kind":"function","lang":"rust","code":"async fn matching_asterisk() {\n let app = Router::new().route(\n \"/*foo\",\n get(|path: MatchedPath| async move { path.as_str().to_owned() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/*foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/*foo\");\n\n let res = client.get(\"/*bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n }"} {"repo":"axum","file":"axum/src/extract/mod.rs","line":86,"symbol":"has_content_type","kind":"function","lang":"rust","doc":"this is duplicated in `axum-extra/src/extract/form.rs`","code":"pub(super) fn has_content_type(headers: &HeaderMap, expected_content_type: &mime::Mime) -> bool {\n let Some(content_type) = headers.get(header::CONTENT_TYPE) else {\n return false;\n };\n\n let Ok(content_type) = content_type.to_str() else {\n return false;\n };\n\n content_type.starts_with(expected_content_type.as_ref())\n}"} {"repo":"axum","file":"axum/src/extract/mod.rs","line":103,"symbol":"consume_body","kind":"function","lang":"rust","code":"async fn consume_body() {\n let app = Router::new().route(\"/\", get(|body: String| async { body }));\n\n let client = TestClient::new(app);\n let res = client.get(\"/\").body(\"foo\").await;\n let body = res.text().await;\n\n assert_eq!(body, \"foo\");\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":64,"symbol":"Multipart","kind":"type","lang":"rust","doc":"# Large Files For security reasons, by default, `Multipart` limits the request body size to 2MB. See [`DefaultBodyLimit`][default-body-limit] for how to configure this limit. [default-body-limit]: crate::extract::DefaultBodyLimit","code":"pub struct Multipart {\n inner: multer::Multipart<'static>,\n}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":74,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n let boundary = content_type_str(req.headers())\n .and_then(|content_type| multer::parse_boundary(content_type).ok())\n .ok_or(InvalidBoundary)?;\n let stream = req.with_limited_body().into_body();\n let multipart = multer::Multipart::new(stream.into_data_stream(), boundary);\n Ok(Self { inner: multipart })\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":90,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result, Self::Rejection> {\n let Some(content_type) = content_type_str(req.headers()) else {\n return Ok(None);\n };\n match multer::parse_boundary(content_type) {\n Ok(boundary) => {\n let stream = req.with_limited_body().into_body();\n let multipart = multer::Multipart::new(stream.into_data_stream(), boundary);\n Ok(Some(Self { inner: multipart }))\n }\n Err(multer::Error::NoMultipart) => Ok(None),\n Err(_) => Err(MultipartRejection::InvalidBoundary(InvalidBoundary)),\n }\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":108,"symbol":"next_field","kind":"function","lang":"rust","doc":"Yields the next [`Field`] if available.","code":"pub async fn next_field(&mut self) -> Result>, MultipartError> {\n let field = self\n .inner\n .next_field()\n .await\n .map_err(MultipartError::from_multer)?;\n\n if let Some(field) = field {\n Ok(Some(Field {\n inner: field,\n _multipart: self,\n }))\n } else {\n Ok(None)\n }\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":128,"symbol":"Field","kind":"type","lang":"rust","doc":"A single field in a multipart stream.","code":"pub struct Field<'a> {\n inner: multer::Field<'static>,\n // multer requires there to only be one live `multer::Field` at any point. This enforces that\n // statically, which multer does not do, it returns an error instead.\n _multipart: &'a mut Multipart,\n}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":138,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n Pin::new(&mut self.inner)\n .poll_next(cx)\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":150,"symbol":"name","kind":"function","lang":"rust","doc":"The field name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.","code":"pub fn name(&self) -> Option<&str> {\n self.inner.name()\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":158,"symbol":"file_name","kind":"function","lang":"rust","doc":"The file name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.","code":"pub fn file_name(&self) -> Option<&str> {\n self.inner.file_name()\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":164,"symbol":"content_type","kind":"function","lang":"rust","doc":"Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field.","code":"pub fn content_type(&self) -> Option<&str> {\n self.inner.content_type().map(|m| m.as_ref())\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":170,"symbol":"headers","kind":"function","lang":"rust","doc":"Get a map of headers as [`HeaderMap`].","code":"pub fn headers(&self) -> &HeaderMap {\n self.inner.headers()\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":175,"symbol":"bytes","kind":"function","lang":"rust","doc":"Get the full data of the field as [`Bytes`].","code":"pub async fn bytes(self) -> Result {\n self.inner\n .bytes()\n .await\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":183,"symbol":"text","kind":"function","lang":"rust","doc":"Get the full field data as text.","code":"pub async fn text(self) -> Result {\n self.inner.text().await.map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":225,"symbol":"chunk","kind":"function","lang":"rust","doc":"Ok(()) } let app = Router::new().route(\"/upload\", post(upload)); # let _: Router = app; ```","code":"pub async fn chunk(&mut self) -> Result, MultipartError> {\n self.inner\n .chunk()\n .await\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":235,"symbol":"MultipartError","kind":"type","lang":"rust","doc":"Errors associated with parsing `multipart/form-data` requests.","code":"pub struct MultipartError {\n source: multer::Error,\n}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":240,"symbol":"from_multer","kind":"function","lang":"rust","code":"fn from_multer(multer: multer::Error) -> Self {\n Self { source: multer }\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":246,"symbol":"body_text","kind":"function","lang":"rust","doc":"Get the response body text used for this rejection.","code":"pub fn body_text(&self) -> String {\n if is_body_limit_error(&self.source) {\n \"Request payload is too large\".to_owned()\n } else {\n self.source.to_string()\n }\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":256,"symbol":"status","kind":"function","lang":"rust","doc":"Get the status code used for this rejection.","code":"pub fn status(&self) -> http::StatusCode {\n status_code_from_multer_error(&self.source)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":261,"symbol":"status_code_from_multer_error","kind":"function","lang":"rust","code":"fn status_code_from_multer_error(err: &multer::Error) -> StatusCode {\n match err {\n multer::Error::UnknownField { .. }\n | multer::Error::IncompleteFieldData { .. }\n | multer::Error::IncompleteHeaders\n | multer::Error::ReadHeaderFailed(..)\n | multer::Error::DecodeHeaderName { .. }\n | multer::Error::DecodeContentType(..)\n | multer::Error::NoBoundary\n | multer::Error::DecodeHeaderValue { .. }\n | multer::Error::NoMultipart\n | multer::Error::IncompleteStream => StatusCode::BAD_REQUEST,\n multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => {\n StatusCode::PAYLOAD_TOO_LARGE\n }\n multer::Error::StreamReadFailed(err) => {\n if let Some(err) = err.downcast_ref::() {\n return status_code_from_multer_error(err);\n }\n\n if err\n .downcast_ref::()\n .and_then(|err| err.source())\n .and_then(|err| err.downcast_ref::())\n .is_some()\n {\n return StatusCode::PAYLOAD_TOO_LARGE;\n "} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":296,"symbol":"is_body_limit_error","kind":"function","lang":"rust","code":"fn is_body_limit_error(err: &multer::Error) -> bool {\n match err {\n multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => true,\n multer::Error::StreamReadFailed(err) => {\n if let Some(err) = err.downcast_ref::() {\n return is_body_limit_error(err);\n }\n err.downcast_ref::()\n .and_then(|err| err.source())\n .and_then(|err| err.downcast_ref::())\n .is_some()\n }\n _ => false,\n }\n}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":313,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"Error parsing `multipart/form-data` request\")\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":319,"symbol":"source","kind":"function","lang":"rust","code":"fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n Some(&self.source)\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":325,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let body = self.body_text();\n axum_core::__log_rejection!(\n rejection_type = Self,\n body_text = body,\n status = self.status(),\n );\n (self.status(), body).into_response()\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":336,"symbol":"content_type_str","kind":"function","lang":"rust","code":"fn content_type_str(headers: &HeaderMap) -> Option<&str> {\n headers.get(CONTENT_TYPE)?.to_str().ok()\n}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":365,"symbol":"content_type_with_encoding","kind":"function","lang":"rust","code":"async fn content_type_with_encoding() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n const FILE_NAME: &str = \"index.html\";\n const CONTENT_TYPE: &str = \"text/html; charset=utf-8\";\n\n async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let field = multipart.next_field().await.unwrap().unwrap();\n\n assert_eq!(field.file_name().unwrap(), FILE_NAME);\n assert_eq!(field.content_type().unwrap(), CONTENT_TYPE);\n assert_eq!(field.headers()[\"foo\"], \"bar\");\n assert_eq!(field.bytes().await.unwrap(), BYTES);\n\n assert!(multipart.next_field().await.unwrap().is_none());\n }\n\n let app = Router::new().route(\"/\", post(handle));\n\n let client = TestClient::new(app);\n\n let form = reqwest::multipart::Form::new().part(\n \"file\",\n reqwest::multipart::Part::bytes(BYTES)\n .file_name(FILE_NAME)\n .mime_str(CONTENT_TYPE)\n .unwrap()\n .headers(reqwest::header::HeaderMap::from_iter([(\n reqwest::header::HeaderName::from_static(\"foo\"),\n reqwest::"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":370,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let field = multipart.next_field().await.unwrap().unwrap();\n\n assert_eq!(field.file_name().unwrap(), FILE_NAME);\n assert_eq!(field.content_type().unwrap(), CONTENT_TYPE);\n assert_eq!(field.headers()[\"foo\"], \"bar\");\n assert_eq!(field.bytes().await.unwrap(), BYTES);\n\n assert!(multipart.next_field().await.unwrap().is_none());\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":401,"symbol":"_multipart_from_request_limited","kind":"function","lang":"rust","doc":"No need for this to be a #[test], we just want to make sure it compiles","code":"fn _multipart_from_request_limited() {\n async fn handler(_: Multipart) {}\n let _app: Router = Router::new()\n .route(\"/\", post(handler))\n .layer(tower_http::limit::RequestBodyLimitLayer::new(1024));\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":402,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Multipart) {}"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":409,"symbol":"body_too_large","kind":"function","lang":"rust","code":"async fn body_too_large() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n\n async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }\n\n let app = Router::new()\n .route(\"/\", post(handle))\n .layer(DefaultBodyLimit::max(BYTES.len() - 1));\n\n let client = TestClient::new(app);\n\n let form =\n reqwest::multipart::Form::new().part(\"file\", reqwest::multipart::Part::bytes(BYTES));\n\n let res = client.post(\"/\").multipart(form).await;\n assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);\n assert_eq!(res.text().await, \"Request payload is too large\");\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":412,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":434,"symbol":"optional_multipart","kind":"function","lang":"rust","code":"async fn optional_multipart() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n\n async fn handle(multipart: Option) -> Result {\n if let Some(mut multipart) = multipart {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(StatusCode::OK)\n } else {\n Ok(StatusCode::NO_CONTENT)\n }\n }\n\n let app = Router::new().route(\"/\", post(handle));\n let client = TestClient::new(app);\n let form =\n reqwest::multipart::Form::new().part(\"file\", reqwest::multipart::Part::bytes(BYTES));\n\n let res = client.post(\"/\").multipart(form).await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/\").await;\n assert_eq!(res.status(), StatusCode::NO_CONTENT);\n }"} {"repo":"axum","file":"axum/src/extract/multipart.rs","line":437,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(multipart: Option) -> Result {\n if let Some(mut multipart) = multipart {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(StatusCode::OK)\n } else {\n Ok(StatusCode::NO_CONTENT)\n }\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":40,"symbol":"NestedPath","kind":"type","lang":"rust","doc":"}) ); let app = Router::new().nest(\"/api\", api); # let _: Router = app; ```","code":"pub struct NestedPath(Arc);"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":45,"symbol":"as_str","kind":"function","lang":"rust","doc":"Returns a `str` representation of the path.","code":"pub fn as_str(&self) -> &str {\n &self.0\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":57,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n match parts.extensions.get::() {\n Some(nested_path) => Ok(nested_path.clone()),\n None => Err(NestedPathRejection),\n }\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":66,"symbol":"SetNestedPath","kind":"type","lang":"rust","code":"pub(crate) struct SetNestedPath {\n inner: S,\n path: Arc,\n}"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":72,"symbol":"layer","kind":"function","lang":"rust","code":"pub(crate) fn layer(path: &str) -> impl Layer + Clone {\n let path = Arc::from(path);\n layer_fn(move |inner| Self {\n inner,\n path: Arc::clone(&path),\n })\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":90,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":94,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, mut req: Request) -> Self::Future {\n if let Some(prev) = req.extensions_mut().get_mut::() {\n let new_path = if prev.as_str() == \"/\" {\n Arc::clone(&self.path)\n } else {\n format!(\"{}{}\", prev.as_str().trim_end_matches('/'), self.path).into()\n };\n prev.0 = new_path;\n } else {\n req.extensions_mut()\n .insert(NestedPath(Arc::clone(&self.path)));\n };\n\n self.inner.call(req)\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":125,"symbol":"one_level_of_nesting","kind":"function","lang":"rust","code":"async fn one_level_of_nesting() {\n let api = Router::new().route(\n \"/users\",\n get(|nested_path: NestedPath| {\n assert_eq!(nested_path.as_str(), \"/api\");\n async {}\n }),\n );\n\n let app = Router::new().nest(\"/api\", api);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":143,"symbol":"one_level_of_nesting_with_trailing_slash","kind":"function","lang":"rust","code":"async fn one_level_of_nesting_with_trailing_slash() {\n let api = Router::new().route(\n \"/users\",\n get(|nested_path: NestedPath| {\n assert_eq!(nested_path.as_str(), \"/api/\");\n async {}\n }),\n );\n\n let app = Router::new().nest(\"/api/\", api);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":161,"symbol":"two_levels_of_nesting","kind":"function","lang":"rust","code":"async fn two_levels_of_nesting() {\n let api = Router::new().route(\n \"/users\",\n get(|nested_path: NestedPath| {\n assert_eq!(nested_path.as_str(), \"/api/v2\");\n async {}\n }),\n );\n\n let app = Router::new().nest(\"/api\", Router::new().nest(\"/v2\", api));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/v2/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":179,"symbol":"two_levels_of_nesting_with_trailing_slash","kind":"function","lang":"rust","code":"async fn two_levels_of_nesting_with_trailing_slash() {\n let api = Router::new().route(\n \"/users\",\n get(|nested_path: NestedPath| {\n assert_eq!(nested_path.as_str(), \"/api/v2\");\n async {}\n }),\n );\n\n let app = Router::new().nest(\"/api/\", Router::new().nest(\"/v2\", api));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/v2/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":197,"symbol":"in_fallbacks","kind":"function","lang":"rust","code":"async fn in_fallbacks() {\n let api = Router::new().fallback(get(|nested_path: NestedPath| {\n assert_eq!(nested_path.as_str(), \"/api\");\n async {}\n }));\n\n let app = Router::new().nest(\"/api\", api);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/doesnt-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":212,"symbol":"in_middleware","kind":"function","lang":"rust","code":"async fn in_middleware() {\n async fn middleware(nested_path: NestedPath, req: Request, next: Next) -> Response {\n assert_eq!(nested_path.as_str(), \"/api\");\n next.run(req).await\n }\n\n let api = Router::new()\n .route(\"/users\", get(|| async {}))\n .layer(from_fn(middleware));\n\n let app = Router::new().nest(\"/api\", api);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/nested_path.rs","line":213,"symbol":"middleware","kind":"function","lang":"rust","code":"async fn middleware(nested_path: NestedPath, req: Request, next: Next) -> Response {\n assert_eq!(nested_path.as_str(), \"/api\");\n next.run(req).await\n }"} {"repo":"axum","file":"axum/src/extract/original_uri.rs","line":68,"symbol":"OriginalUri","kind":"type","lang":"rust","doc":"}), ); let app = Router::new().nest(\"/api\", api_routes); # let _: Router = app; ```","code":"pub struct OriginalUri(pub Uri);"} {"repo":"axum","file":"axum/src/extract/original_uri.rs","line":76,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let uri = Extension::::from_request_parts(parts, state)\n .await\n .unwrap_or_else(|_| Extension(Self(parts.uri.clone())))\n .0;\n Ok(uri)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":45,"symbol":"PathDeserializer","kind":"type","lang":"rust","code":"pub(crate) struct PathDeserializer<'de> {\n url_params: &'de [(Arc, PercentDecodedStr)],\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":51,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(url_params: &'de [(Arc, PercentDecodedStr)]) -> Self {\n PathDeserializer { url_params }\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":81,"symbol":"deserialize_any","kind":"function","lang":"rust","code":"fn deserialize_any(self, v: V) -> Result\n where\n V: Visitor<'de>,\n {\n self.deserialize_str(v)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":88,"symbol":"deserialize_str","kind":"function","lang":"rust","code":"fn deserialize_str(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n if self.url_params.len() != 1 {\n return Err(PathDeserializationError::wrong_number_of_parameters()\n .got(self.url_params.len())\n .expected(1));\n }\n let key = &self.url_params[0].0;\n let value = &self.url_params[0].1;\n visitor\n .visit_borrowed_str(value)\n .map_err(|e: PathDeserializationError| {\n if let ErrorKind::Message(message) = &e.kind {\n PathDeserializationError::new(ErrorKind::DeserializeError {\n key: key.to_string(),\n value: value.as_str().to_owned(),\n message: message.to_owned(),\n })\n } else {\n e\n }\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":114,"symbol":"deserialize_unit","kind":"function","lang":"rust","code":"fn deserialize_unit(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_unit()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":121,"symbol":"deserialize_unit_struct","kind":"function","lang":"rust","code":"fn deserialize_unit_struct(\n self,\n _name: &'static str,\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_unit()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":132,"symbol":"deserialize_newtype_struct","kind":"function","lang":"rust","code":"fn deserialize_newtype_struct(\n self,\n _name: &'static str,\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_newtype_struct(self)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":143,"symbol":"deserialize_seq","kind":"function","lang":"rust","code":"fn deserialize_seq(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_seq(SeqDeserializer {\n params: self.url_params,\n idx: 0,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":153,"symbol":"deserialize_tuple","kind":"function","lang":"rust","code":"fn deserialize_tuple(self, len: usize, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n if self.url_params.len() != len {\n return Err(PathDeserializationError::wrong_number_of_parameters()\n .got(self.url_params.len())\n .expected(len));\n }\n visitor.visit_seq(SeqDeserializer {\n params: self.url_params,\n idx: 0,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":168,"symbol":"deserialize_tuple_struct","kind":"function","lang":"rust","code":"fn deserialize_tuple_struct(\n self,\n _name: &'static str,\n len: usize,\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n if self.url_params.len() != len {\n return Err(PathDeserializationError::wrong_number_of_parameters()\n .got(self.url_params.len())\n .expected(len));\n }\n visitor.visit_seq(SeqDeserializer {\n params: self.url_params,\n idx: 0,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":188,"symbol":"deserialize_map","kind":"function","lang":"rust","code":"fn deserialize_map(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_map(MapDeserializer {\n params: self.url_params,\n value: None,\n key: None,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":199,"symbol":"deserialize_struct","kind":"function","lang":"rust","code":"fn deserialize_struct(\n self,\n _name: &'static str,\n _fields: &'static [&'static str],\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n self.deserialize_map(visitor)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":211,"symbol":"deserialize_enum","kind":"function","lang":"rust","code":"fn deserialize_enum(\n self,\n _name: &'static str,\n _variants: &'static [&'static str],\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n if self.url_params.len() != 1 {\n return Err(PathDeserializationError::wrong_number_of_parameters()\n .got(self.url_params.len())\n .expected(1));\n }\n\n visitor.visit_enum(EnumDeserializer {\n value: &self.url_params[0].1,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":232,"symbol":"MapDeserializer","kind":"type","lang":"rust","code":"struct MapDeserializer<'de> {\n params: &'de [(Arc, PercentDecodedStr)],\n key: Option>,\n value: Option<&'de PercentDecodedStr>,\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":241,"symbol":"next_key_seed","kind":"function","lang":"rust","code":"fn next_key_seed(&mut self, seed: K) -> Result, Self::Error>\n where\n K: DeserializeSeed<'de>,\n {\n match self.params.split_first() {\n Some(((key, value), tail)) => {\n self.value = Some(value);\n self.params = tail;\n self.key = Some(KeyOrIdx::Key(key));\n seed.deserialize(KeyDeserializer { key }).map(Some)\n }\n None => Ok(None),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":256,"symbol":"next_value_seed","kind":"function","lang":"rust","code":"fn next_value_seed(&mut self, seed: V) -> Result\n where\n V: DeserializeSeed<'de>,\n {\n match self.value.take() {\n Some(value) => seed.deserialize(ValueDeserializer {\n key: self.key.take(),\n value,\n }),\n None => Err(PathDeserializationError::custom(\"value is missing\")),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":270,"symbol":"KeyDeserializer","kind":"type","lang":"rust","code":"struct KeyDeserializer<'de> {\n key: &'de str,\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":292,"symbol":"deserialize_any","kind":"function","lang":"rust","code":"fn deserialize_any(self, _visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::custom(\"Unexpected key type\"))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":340,"symbol":"ValueDeserializer","kind":"type","lang":"rust","code":"struct ValueDeserializer<'de> {\n key: Option>,\n value: &'de PercentDecodedStr,\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":368,"symbol":"deserialize_any","kind":"function","lang":"rust","code":"fn deserialize_any(self, v: V) -> Result\n where\n V: Visitor<'de>,\n {\n self.deserialize_str(v)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":375,"symbol":"deserialize_str","kind":"function","lang":"rust","code":"fn deserialize_str(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor\n .visit_borrowed_str(self.value)\n .map_err(|e: PathDeserializationError| {\n if let (ErrorKind::Message(message), Some(key)) = (&e.kind, self.key.as_ref()) {\n PathDeserializationError::new(ErrorKind::DeserializeError {\n key: key.key().to_owned(),\n value: self.value.as_str().to_owned(),\n message: message.to_owned(),\n })\n } else {\n e\n }\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":394,"symbol":"deserialize_bytes","kind":"function","lang":"rust","code":"fn deserialize_bytes(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_borrowed_bytes(self.value.as_bytes())\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":401,"symbol":"deserialize_option","kind":"function","lang":"rust","code":"fn deserialize_option(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_some(self)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":408,"symbol":"deserialize_unit","kind":"function","lang":"rust","code":"fn deserialize_unit(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_unit()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":415,"symbol":"deserialize_unit_struct","kind":"function","lang":"rust","code":"fn deserialize_unit_struct(\n self,\n _name: &'static str,\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_unit()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":426,"symbol":"deserialize_newtype_struct","kind":"function","lang":"rust","code":"fn deserialize_newtype_struct(\n self,\n _name: &'static str,\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_newtype_struct(self)\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":437,"symbol":"deserialize_tuple","kind":"function","lang":"rust","code":"fn deserialize_tuple(self, len: usize, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n struct PairDeserializer<'de> {\n key: Option>,\n value: Option<&'de PercentDecodedStr>,\n }\n\n impl<'de> SeqAccess<'de> for PairDeserializer<'de> {\n type Error = PathDeserializationError;\n\n fn next_element_seed(&mut self, seed: T) -> Result, Self::Error>\n where\n T: DeserializeSeed<'de>,\n {\n match self.key.take() {\n Some(KeyOrIdx::Idx { idx: _, key }) => {\n return seed.deserialize(KeyDeserializer { key }).map(Some);\n }\n Some(KeyOrIdx::Key(_)) => {\n return Err(PathDeserializationError::custom(\n \"array types are not supported\",\n ));\n }\n None => {}\n };\n\n self.value\n .take()\n .map(|value| seed.deserialize(ValueDeserializer { key: None, value }))\n "} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":441,"symbol":"PairDeserializer","kind":"type","lang":"rust","code":"struct PairDeserializer<'de> {\n key: Option>,\n value: Option<&'de PercentDecodedStr>,\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":449,"symbol":"next_element_seed","kind":"function","lang":"rust","code":"fn next_element_seed(&mut self, seed: T) -> Result, Self::Error>\n where\n T: DeserializeSeed<'de>,\n {\n match self.key.take() {\n Some(KeyOrIdx::Idx { idx: _, key }) => {\n return seed.deserialize(KeyDeserializer { key }).map(Some);\n }\n Some(KeyOrIdx::Key(_)) => {\n return Err(PathDeserializationError::custom(\n \"array types are not supported\",\n ));\n }\n None => {}\n };\n\n self.value\n .take()\n .map(|value| seed.deserialize(ValueDeserializer { key: None, value }))\n .transpose()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":489,"symbol":"deserialize_seq","kind":"function","lang":"rust","code":"fn deserialize_seq(self, _visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::unsupported_type(type_name::<\n V::Value,\n >()))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":498,"symbol":"deserialize_tuple_struct","kind":"function","lang":"rust","code":"fn deserialize_tuple_struct(\n self,\n _name: &'static str,\n _len: usize,\n _visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::unsupported_type(type_name::<\n V::Value,\n >()))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":512,"symbol":"deserialize_struct","kind":"function","lang":"rust","code":"fn deserialize_struct(\n self,\n _name: &'static str,\n _fields: &'static [&'static str],\n _visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::unsupported_type(type_name::<\n V::Value,\n >()))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":526,"symbol":"deserialize_enum","kind":"function","lang":"rust","code":"fn deserialize_enum(\n self,\n _name: &'static str,\n _variants: &'static [&'static str],\n visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_enum(EnumDeserializer { value: self.value })\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":538,"symbol":"deserialize_ignored_any","kind":"function","lang":"rust","code":"fn deserialize_ignored_any(self, visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n visitor.visit_unit()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":546,"symbol":"EnumDeserializer","kind":"type","lang":"rust","code":"struct EnumDeserializer<'de> {\n value: &'de str,\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":554,"symbol":"variant_seed","kind":"function","lang":"rust","code":"fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>\n where\n V: de::DeserializeSeed<'de>,\n {\n Ok((\n seed.deserialize(KeyDeserializer { key: self.value })?,\n UnitVariant,\n ))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":565,"symbol":"UnitVariant","kind":"type","lang":"rust","code":"struct UnitVariant;"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":570,"symbol":"unit_variant","kind":"function","lang":"rust","code":"fn unit_variant(self) -> Result<(), Self::Error> {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":574,"symbol":"newtype_variant_seed","kind":"function","lang":"rust","code":"fn newtype_variant_seed(self, _seed: T) -> Result\n where\n T: DeserializeSeed<'de>,\n {\n Err(PathDeserializationError::unsupported_type(\n \"newtype enum variant\",\n ))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":583,"symbol":"tuple_variant","kind":"function","lang":"rust","code":"fn tuple_variant(self, _len: usize, _visitor: V) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::unsupported_type(\n \"tuple enum variant\",\n ))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":592,"symbol":"struct_variant","kind":"function","lang":"rust","code":"fn struct_variant(\n self,\n _fields: &'static [&'static str],\n _visitor: V,\n ) -> Result\n where\n V: Visitor<'de>,\n {\n Err(PathDeserializationError::unsupported_type(\n \"struct enum variant\",\n ))\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":606,"symbol":"SeqDeserializer","kind":"type","lang":"rust","code":"struct SeqDeserializer<'de> {\n params: &'de [(Arc, PercentDecodedStr)],\n idx: usize,\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":614,"symbol":"next_element_seed","kind":"function","lang":"rust","code":"fn next_element_seed(&mut self, seed: T) -> Result, Self::Error>\n where\n T: DeserializeSeed<'de>,\n {\n match self.params.split_first() {\n Some(((key, value), tail)) => {\n self.params = tail;\n let idx = self.idx;\n self.idx += 1;\n Ok(Some(seed.deserialize(ValueDeserializer {\n key: Some(KeyOrIdx::Idx { idx, key }),\n value,\n })?))\n }\n None => Ok(None),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":634,"symbol":"KeyOrIdx","kind":"type","lang":"rust","code":"enum KeyOrIdx<'de> {\n Key(&'de str),\n Idx { idx: usize, key: &'de str },\n}"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":640,"symbol":"key","kind":"function","lang":"rust","code":"fn key(&self) -> &'de str {\n match &self {\n Self::Idx { key, .. } | Self::Key(key) => key,\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":654,"symbol":"MyEnum","kind":"type","lang":"rust","code":"enum MyEnum {\n A,\n B,\n #[serde(rename = \"c\")]\n C,\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":662,"symbol":"Struct","kind":"type","lang":"rust","code":"struct Struct {\n c: String,\n b: bool,\n a: i32,\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":668,"symbol":"create_url_params","kind":"function","lang":"rust","code":"fn create_url_params(values: I) -> Vec<(Arc, PercentDecodedStr)>\n where\n I: IntoIterator,\n K: AsRef,\n V: AsRef,\n {\n values\n .into_iter()\n .map(|(k, v)| (Arc::from(k.as_ref()), PercentDecodedStr::new(v).unwrap()))\n .collect()\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":692,"symbol":"test_parse_single_value","kind":"function","lang":"rust","code":"fn test_parse_single_value() {\n check_single_value!(bool, \"true\", true);\n check_single_value!(bool, \"false\", false);\n check_single_value!(i8, \"-123\", -123);\n check_single_value!(i16, \"-123\", -123);\n check_single_value!(i32, \"-123\", -123);\n check_single_value!(i64, \"-123\", -123);\n check_single_value!(i128, \"123\", 123);\n check_single_value!(u8, \"123\", 123);\n check_single_value!(u16, \"123\", 123);\n check_single_value!(u32, \"123\", 123);\n check_single_value!(u64, \"123\", 123);\n check_single_value!(u128, \"123\", 123);\n check_single_value!(f32, \"123\", 123.0);\n check_single_value!(f64, \"123\", 123.0);\n check_single_value!(String, \"abc\", \"abc\");\n check_single_value!(String, \"one%20two\", \"one two\");\n check_single_value!(&str, \"abc\", \"abc\");\n check_single_value!(&str, \"one%20two\", \"one two\");\n check_single_value!(char, \"a\", 'a');\n\n let url_params = create_url_params(vec![(\"a\", \"B\")]);\n assert_eq!(\n MyEnum::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n MyEnum::B\n );\n\n let url_params = create_url_params(ve"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":733,"symbol":"test_parse_seq","kind":"function","lang":"rust","code":"fn test_parse_seq() {\n let url_params = create_url_params(vec![(\"a\", \"1\"), (\"b\", \"true\"), (\"c\", \"abc\")]);\n assert_eq!(\n <(i32, bool, String)>::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n (1, true, \"abc\".to_owned())\n );\n\n #[derive(Debug, Deserialize, Eq, PartialEq)]\n struct TupleStruct(i32, bool, String);\n assert_eq!(\n TupleStruct::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n TupleStruct(1, true, \"abc\".to_owned())\n );\n\n let url_params = create_url_params(vec![(\"a\", \"1\"), (\"b\", \"2\"), (\"c\", \"3\")]);\n assert_eq!(\n >::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n vec![1, 2, 3]\n );\n\n let url_params = create_url_params(vec![(\"a\", \"c\"), (\"a\", \"B\")]);\n assert_eq!(\n >::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n vec![MyEnum::C, MyEnum::B]\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":741,"symbol":"TupleStruct","kind":"type","lang":"rust","code":"struct TupleStruct(i32, bool, String);"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":761,"symbol":"test_parse_seq_tuple_string_string","kind":"function","lang":"rust","code":"fn test_parse_seq_tuple_string_string() {\n let url_params = create_url_params(vec![(\"a\", \"foo\"), (\"b\", \"bar\")]);\n assert_eq!(\n >::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n vec![\n (\"a\".to_owned(), \"foo\".to_owned()),\n (\"b\".to_owned(), \"bar\".to_owned())\n ]\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":773,"symbol":"test_parse_seq_tuple_string_parse","kind":"function","lang":"rust","code":"fn test_parse_seq_tuple_string_parse() {\n let url_params = create_url_params(vec![(\"a\", \"1\"), (\"b\", \"2\")]);\n assert_eq!(\n >::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n vec![(\"a\".to_owned(), 1), (\"b\".to_owned(), 2)]\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":782,"symbol":"test_parse_struct","kind":"function","lang":"rust","code":"fn test_parse_struct() {\n let url_params = create_url_params(vec![(\"a\", \"1\"), (\"b\", \"true\"), (\"c\", \"abc\")]);\n assert_eq!(\n Struct::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n Struct {\n c: \"abc\".to_owned(),\n b: true,\n a: 1,\n }\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":795,"symbol":"test_parse_struct_ignoring_additional_fields","kind":"function","lang":"rust","code":"fn test_parse_struct_ignoring_additional_fields() {\n let url_params = create_url_params(vec![\n (\"a\", \"1\"),\n (\"b\", \"true\"),\n (\"c\", \"abc\"),\n (\"d\", \"false\"),\n ]);\n assert_eq!(\n Struct::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n Struct {\n c: \"abc\".to_owned(),\n b: true,\n a: 1,\n }\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":813,"symbol":"test_parse_map","kind":"function","lang":"rust","code":"fn test_parse_map() {\n let url_params = create_url_params(vec![(\"a\", \"1\"), (\"b\", \"true\"), (\"c\", \"abc\")]);\n assert_eq!(\n >::deserialize(PathDeserializer::new(&url_params)).unwrap(),\n [(\"a\", \"1\"), (\"b\", \"true\"), (\"c\", \"abc\")]\n .iter()\n .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))\n .collect()\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":839,"symbol":"test_parse_tuple_too_many_fields","kind":"function","lang":"rust","code":"fn test_parse_tuple_too_many_fields() {\n test_parse_error!(\n vec![(\"a\", \"abc\"), (\"b\", \"true\"), (\"c\", \"1\"), (\"d\", \"false\"),],\n (&str, bool, u32),\n ErrorKind::WrongNumberOfParameters {\n got: 4,\n expected: 3,\n }\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":851,"symbol":"test_wrong_number_of_parameters_error","kind":"function","lang":"rust","code":"fn test_wrong_number_of_parameters_error() {\n test_parse_error!(\n vec![(\"a\", \"1\")],\n (u32, u32),\n ErrorKind::WrongNumberOfParameters {\n got: 1,\n expected: 2,\n }\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":863,"symbol":"test_parse_error_at_key_error","kind":"function","lang":"rust","code":"fn test_parse_error_at_key_error() {\n #[derive(Debug, Deserialize)]\n #[allow(dead_code)]\n struct Params {\n a: u32,\n }\n test_parse_error!(\n vec![(\"a\", \"false\")],\n Params,\n ErrorKind::ParseErrorAtKey {\n key: \"a\".to_owned(),\n value: \"false\".to_owned(),\n expected_type: \"u32\",\n }\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/de.rs","line":866,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n a: u32,\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":138,"symbol":"InnerPath","kind":"type","lang":"rust","doc":"[`serde`]: https://crates.io/crates/serde [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs [`Path`]: crate::extract::Path [`nest`]: crate::routing::Router::nest","code":"pub struct InnerPath(pub T);"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":149,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n get_inner_params(parts)\n .and_then(serialize_path_params)\n .map(Self)\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":163,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n _state: &S,\n ) -> Result, Self::Rejection> {\n match parts.extract::().await {\n Ok(Self(params)) => Ok(Some(Self(params))),\n Err(InnerPathRejection::FailedToDeserializePathParams(e))\n if e.kind().is_zero_params() =>\n {\n Ok(None)\n }\n Err(e) => Err(e),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":179,"symbol":"get_inner_params","kind":"function","lang":"rust","code":"fn get_inner_params(parts: &Parts) -> Result<&[(Arc, PercentDecodedStr)], InnerPathRejection> {\n let url_params = parts\n .extensions\n .get::()\n .ok_or(MissingPathParams)?;\n\n match url_params {\n UrlParams::Params {\n params,\n inner_start,\n } => {\n let inner_params = params\n .get(*inner_start..)\n .expect(\"Mismatch between url params and count of captures. This is bug in axum. Please file an issue.\");\n\n Ok(inner_params)\n }\n UrlParams::InvalidUtf8InPathParam { key } => {\n let error = PathDeserializationError {\n kind: ErrorKind::InvalidUtf8InPathParam {\n key: key.to_string(),\n },\n };\n Err(InnerPathRejection::from(FailedToDeserializePathParams(\n error,\n )))\n }\n }\n}"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":225,"symbol":"params","kind":"function","lang":"rust","code":"fn params(pairs: &[(&str, &str)]) -> Params {\n pairs\n .iter()\n .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))\n .collect()\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":233,"symbol":"without_nesting_matches_path","kind":"function","lang":"rust","code":"async fn without_nesting_matches_path() {\n let app = Router::new().route(\n \"/users/{user_id}/team/{team_id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n let expected = params(&[(\"user_id\", \"42\"), (\"team_id\", \"1337\")]);\n assert_eq!(all, expected);\n assert_eq!(inner, expected);\n assert_eq!(inner, all);\n \"teams#show\"\n },\n ),\n );\n let res = TestClient::new(app).get(\"/users/42/team/1337\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"teams#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":253,"symbol":"static_nest_prefix_contributes_nothing","kind":"function","lang":"rust","code":"async fn static_nest_prefix_contributes_nothing() {\n let app = Router::new().nest(\n \"/api\",\n Router::new().route(\n \"/users/{user_id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n let expected = params(&[(\"user_id\", \"42\")]);\n assert_eq!(all, expected);\n assert_eq!(inner, expected);\n assert_eq!(inner, all);\n \"users#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/api/users/42\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"users#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":276,"symbol":"dynamic_nest_prefix_is_excluded","kind":"function","lang":"rust","code":"async fn dynamic_nest_prefix_is_excluded() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/team/{team_id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"team_id\", \"1337\")]));\n assert_eq!(inner, params(&[(\"team_id\", \"1337\")]));\n \"teams#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/team/1337\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"teams#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":297,"symbol":"nesting_mixing_static_and_dynamic_levels","kind":"function","lang":"rust","code":"async fn nesting_mixing_static_and_dynamic_levels() {\n let app = Router::new().nest(\n \"/api\",\n Router::new().nest(\n \"/{version}\",\n Router::new().nest(\n \"/admin\",\n Router::new().route(\n \"/{id}\",\n get(\n |Path(all): Path,\n InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"version\", \"v2\"), (\"id\", \"42\")]));\n assert_eq!(inner, params(&[(\"id\", \"42\")]));\n \"admin#show\"\n },\n ),\n ),\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/api/v2/admin/42\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"admin#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":325,"symbol":"offset_sums_captures_across_levels","kind":"function","lang":"rust","code":"async fn offset_sums_captures_across_levels() {\n let app = Router::new().nest(\n \"/{prefix_one}\",\n Router::new().nest(\n \"/{prefix_two}/{prefix_three}\",\n Router::new().nest(\n \"/x/{prefix_four}\",\n Router::new().route(\n \"/{leaf_one}/{leaf_two}\",\n get(\n |Path(all): Path,\n InnerPath(inner): InnerPath| async move {\n assert_eq!(\n all,\n params(&[\n (\"prefix_one\", \"1\"),\n (\"prefix_two\", \"2\"),\n (\"prefix_three\", \"3\"),\n (\"prefix_four\", \"4\"),\n (\"leaf_one\", \"5\"),\n (\"leaf_two\", \"6\"),\n ])\n );\n assert_eq!(\n inner,\n "} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":368,"symbol":"outer_nest_with_inner_nest_service","kind":"function","lang":"rust","doc":"`#[crate::test]` generates extra tests where `nest` calls are converted to `nest_service`. This test mixes `nest` and `nest_service` at different levels.","code":"async fn outer_nest_with_inner_nest_service() {\n let app = Router::new().nest(\n \"/api\",\n Router::new().nest_service(\n \"/{version}\",\n Router::new().route(\n \"/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"version\", \"v2\"), (\"id\", \"42\")]));\n assert_eq!(inner, params(&[(\"id\", \"42\")]));\n \"items#show\"\n },\n ),\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/api/v2/42\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"items#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":392,"symbol":"wildcard","kind":"function","lang":"rust","code":"async fn wildcard() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/files/{*rest}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"rest\", \"a/b/c\")]));\n assert_eq!(inner, params(&[(\"rest\", \"a/b/c\")]));\n \"files#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/files/a/b/c\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"files#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":413,"symbol":"inner_route_without_captures","kind":"function","lang":"rust","code":"async fn inner_route_without_captures() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/static\",\n get(\n |Path(all): Path,\n InnerPath(inner): InnerPath,\n opt: Option>| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\")]));\n assert_eq!(inner, params(&[]));\n assert_eq!(opt.as_deref(), None);\n \"static\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/static\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"static\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":437,"symbol":"hash_map_only_contains_inner_captures","kind":"function","lang":"rust","code":"async fn hash_map_only_contains_inner_captures() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/team/{team_id}\",\n get(\n |Path(all): Path>,\n InnerPath(inner): InnerPath>| async move {\n assert_eq!(\n all,\n HashMap::from_iter(params(&[(\"org\", \"acme\"), (\"team_id\", \"1337\")]))\n );\n assert_eq!(inner, HashMap::from_iter(params(&[(\"team_id\", \"1337\")])));\n \"teams#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/team/1337\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"teams#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":462,"symbol":"same_router_nested_at_prefixes_of_different_arity","kind":"function","lang":"rust","code":"async fn same_router_nested_at_prefixes_of_different_arity() {\n fn resources() -> Router {\n Router::new().route(\n \"/{id}/{version}\",\n get(|InnerPath(inner): InnerPath| async move {\n assert_eq!(inner, params(&[(\"id\", \"thing\"), (\"version\", \"3\")]));\n \"resources#show\"\n }),\n )\n }\n\n let app = Router::new()\n .nest(\"/global/{env}\", resources())\n .nest(\"/customer/{customer_id}/{env}\", resources());\n let client = TestClient::new(app);\n\n let res = client.get(\"/global/prod/thing/3\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"resources#show\");\n\n let res = client.get(\"/customer/acme/prod/thing/3\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"resources#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":463,"symbol":"resources","kind":"function","lang":"rust","code":"fn resources() -> Router {\n Router::new().route(\n \"/{id}/{version}\",\n get(|InnerPath(inner): InnerPath| async move {\n assert_eq!(inner, params(&[(\"id\", \"thing\"), (\"version\", \"3\")]));\n \"resources#show\"\n }),\n )\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":488,"symbol":"in_nested_fallback","kind":"function","lang":"rust","code":"async fn in_nested_fallback() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().fallback(get(\n |Path(all): Path,\n InnerPath(inner): InnerPath,\n opt: Option>| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\")]));\n assert_eq!(inner, params(&[]));\n assert_eq!(opt.as_deref(), None);\n \"fallback\"\n },\n )),\n );\n let res = TestClient::new(app).get(\"/org/acme/does-not-exist\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"fallback\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":509,"symbol":"in_nested_middleware","kind":"function","lang":"rust","code":"async fn in_nested_middleware() {\n async fn middleware(\n Path(all): Path,\n InnerPath(inner): InnerPath,\n req: Request,\n next: Next,\n ) -> Response {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"team_id\", \"1337\")]));\n assert_eq!(inner, params(&[(\"team_id\", \"1337\")]));\n next.run(req).await\n }\n\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new()\n .route(\"/team/{team_id}\", get(|| async { \"teams#show\" }))\n .layer(from_fn(middleware)),\n );\n let res = TestClient::new(app).get(\"/org/acme/team/1337\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"teams#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":510,"symbol":"middleware","kind":"function","lang":"rust","code":"async fn middleware(\n Path(all): Path,\n InnerPath(inner): InnerPath,\n req: Request,\n next: Next,\n ) -> Response {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"team_id\", \"1337\")]));\n assert_eq!(inner, params(&[(\"team_id\", \"1337\")]));\n next.run(req).await\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":534,"symbol":"merge_preserves_per_route_offsets","kind":"function","lang":"rust","code":"async fn merge_preserves_per_route_offsets() {\n let unnested = Router::new().route(\n \"/plain/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n let expected = params(&[(\"id\", \"0\")]);\n assert_eq!(all, expected);\n assert_eq!(inner, expected);\n \"unnested\"\n },\n ),\n );\n\n let nested_under_one_capture = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"id\", \"1\")]));\n assert_eq!(inner, params(&[(\"id\", \"1\")]));\n \"nested_under_one_capture\"\n },\n ),\n ),\n );\n\n let nested_under_two_captures = Router::new().nest(\n \"/team/{team}/{env}\",\n Router::new().route(\n \"/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"v\", \"2\"), (\"org\", \"acme\"), (\"id\", \"1\")]));\n assert_eq!(inner, params(&[(\"id\", \"1\")]));\n \"already_nested\"\n },\n ),\n ),\n );\n\n let not_yet_nested = Router::new().route(\n \"/plain/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"v\", \"2\"), (\"id\", \"0\")]));\n assert_eq!(inner, params(&[(\"id\", \"0\")]));\n \"not_yet_nested\"\n },\n ),\n );\n\n let app = Router::new().nest(\"/api/{v}\", already_nested.merge(not_yet_nested));\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/2/org/acme/1\").await;\n assert_eq!(res.status()"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":637,"symbol":"percent_decoding_still_applies","kind":"function","lang":"rust","code":"async fn percent_decoding_still_applies() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/{name}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"org\", \"acme\"), (\"name\", \"one two\")]));\n assert_eq!(inner, params(&[(\"name\", \"one two\")]));\n \"names#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/one%20two\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"names#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":658,"symbol":"wrong_number_of_parameters_is_rejected","kind":"function","lang":"rust","code":"async fn wrong_number_of_parameters_is_rejected() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\"/{id}\", get(|_: InnerPath<(u32, u32)>| async move {})),\n );\n let res = TestClient::new(app).get(\"/org/acme/42\").await;\n\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(\n res.text().await,\n \"Wrong number of path arguments for `Path`. Expected 2 but got 1\"\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":673,"symbol":"duplicate_capture_names_across_levels","kind":"function","lang":"rust","code":"async fn duplicate_capture_names_across_levels() {\n let app = Router::new().nest(\n \"/org/{id}\",\n Router::new().route(\n \"/{id}\",\n get(\n |Path(all): Path, InnerPath(inner): InnerPath| async move {\n assert_eq!(all, params(&[(\"id\", \"outer\"), (\"id\", \"inner\")]));\n assert_eq!(inner, params(&[(\"id\", \"inner\")]));\n \"items#show\"\n },\n ),\n ),\n );\n let res = TestClient::new(app).get(\"/org/outer/inner\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"items#show\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":694,"symbol":"invalid_utf8_in_nest_prefix_capture","kind":"function","lang":"rust","code":"async fn invalid_utf8_in_nest_prefix_capture() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/team/{team_id}\",\n get(|_: InnerPath| async move { \"teams#show\" }),\n ),\n );\n let res = TestClient::new(app).get(\"/org/%FF/team/1337\").await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(res.text().await, \"Invalid URL: Invalid UTF-8 in `org`\");\n }"} {"repo":"axum","file":"axum/src/extract/path/inner_path.rs","line":709,"symbol":"invalid_utf8_in_inner_capture","kind":"function","lang":"rust","code":"async fn invalid_utf8_in_inner_capture() {\n let app = Router::new().nest(\n \"/org/{org}\",\n Router::new().route(\n \"/team/{team_id}\",\n get(|_: InnerPath| async move { \"teams#show\" }),\n ),\n );\n let res = TestClient::new(app).get(\"/org/acme/team/%FF\").await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(res.text().await, \"Invalid URL: Invalid UTF-8 in `team_id`\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":163,"symbol":"Path","kind":"type","lang":"rust","doc":"[`serde`]: https://crates.io/crates/serde [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs [`InnerPath`]: crate::extract::InnerPath [`nest`]: crate::routing::Router::nest","code":"pub struct Path(pub T);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":174,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n get_params(parts).and_then(serialize_path_params).map(Self)\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":186,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n _state: &S,\n ) -> Result, Self::Rejection> {\n match parts.extract::().await {\n Ok(Self(params)) => Ok(Some(Self(params))),\n Err(PathRejection::FailedToDeserializePathParams(e)) if e.kind().is_zero_params() => {\n Ok(None)\n }\n Err(e) => Err(e),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":203,"symbol":"PathDeserializationError","kind":"type","lang":"rust","doc":"this wrapper type is used as the deserializer error to hide the `serde::de::Error` impl which would otherwise be public if we used `ErrorKind` as the error directly","code":"pub(crate) struct PathDeserializationError {\n pub(super) kind: ErrorKind,\n}"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":208,"symbol":"new","kind":"function","lang":"rust","code":"pub(super) fn new(kind: ErrorKind) -> Self {\n Self { kind }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":212,"symbol":"wrong_number_of_parameters","kind":"function","lang":"rust","code":"pub(super) fn wrong_number_of_parameters() -> WrongNumberOfParameters<()> {\n WrongNumberOfParameters { got: () }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":217,"symbol":"unsupported_type","kind":"function","lang":"rust","code":"pub(super) fn unsupported_type(name: &'static str) -> Self {\n Self::new(ErrorKind::UnsupportedType { name })\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":222,"symbol":"WrongNumberOfParameters","kind":"type","lang":"rust","code":"pub(super) struct WrongNumberOfParameters {\n got: G,\n}"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":228,"symbol":"got","kind":"function","lang":"rust","code":"pub(super) fn got(self, got: G2) -> WrongNumberOfParameters {\n WrongNumberOfParameters { got }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":234,"symbol":"expected","kind":"function","lang":"rust","code":"pub(super) fn expected(self, expected: usize) -> PathDeserializationError {\n PathDeserializationError::new(ErrorKind::WrongNumberOfParameters {\n got: self.got,\n expected,\n })\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":244,"symbol":"custom","kind":"function","lang":"rust","code":"fn custom(msg: T) -> Self\n where\n T: fmt::Display,\n {\n Self {\n kind: ErrorKind::Message(msg.to_string()),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":255,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.kind.fmt(f)\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":270,"symbol":"ErrorKind","kind":"type","lang":"rust","doc":"The kinds of errors that can happen we deserializing into a [`Path`]. This type is obtained through [`FailedToDeserializePathParams::kind`] or [`FailedToDeserializePathParams::into_kind`] and is useful for building more precise error messages.","code":"pub enum ErrorKind {\n /// The URI contained the wrong number of parameters.\n WrongNumberOfParameters {\n /// The number of actual parameters in the URI.\n got: usize,\n /// The number of expected parameters.\n expected: usize,\n },\n\n /// Failed to parse the value at a specific key into the expected type.\n ///\n /// This variant is used when deserializing into types that have named fields, such as structs.\n ParseErrorAtKey {\n /// The key at which the value was located.\n key: String,\n /// The value from the URI.\n value: String,\n /// The expected type of the value.\n expected_type: &'static str,\n },\n\n /// Failed to parse the value at a specific index into the expected type.\n ///\n /// This variant is used when deserializing into sequence types, such as tuples.\n ParseErrorAtIndex {\n /// The index at which the value was located.\n index: usize,\n /// The value from the URI.\n value: String,\n /// The expected type of the value.\n expected_type: &'static str,\n },\n\n /// Failed to parse a value into the expected type.\n ///\n /// This variant is u"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":343,"symbol":"is_zero_params","kind":"function","lang":"rust","code":"fn is_zero_params(&self) -> bool {\n matches!(&self, Self::WrongNumberOfParameters { got: 0, .. })\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":349,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::Message(error) => error.fmt(f),\n Self::InvalidUtf8InPathParam { key } => write!(f, \"Invalid UTF-8 in `{key}`\"),\n Self::WrongNumberOfParameters { got, expected } => {\n write!(\n f,\n \"Wrong number of path arguments for `Path`. Expected {expected} but got {got}\"\n )?;\n\n if *expected == 1 {\n write!(f, \". Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path`\")?;\n }\n\n Ok(())\n }\n Self::UnsupportedType { name } => write!(f, \"Unsupported type `{name}`\"),\n Self::ParseErrorAtKey {\n key,\n value,\n expected_type,\n } => write!(\n f,\n \"Cannot parse `{key}` with value `{value}` to a `{expected_type}`\"\n ),\n Self::ParseError {\n value,\n expected_type,\n } => write!(f, \"Cannot parse `{value}` to a `{expected_type}`\"),\n "} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":398,"symbol":"FailedToDeserializePathParams","kind":"type","lang":"rust","doc":"Rejection type for [`Path`] if the captured routes params couldn't be deserialized into the expected type.","code":"pub struct FailedToDeserializePathParams(PathDeserializationError);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":403,"symbol":"kind","kind":"function","lang":"rust","doc":"Get a reference to the underlying error kind.","code":"pub fn kind(&self) -> &ErrorKind {\n &self.0.kind\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":408,"symbol":"into_kind","kind":"function","lang":"rust","doc":"Convert this error into the underlying error kind.","code":"pub fn into_kind(self) -> ErrorKind {\n self.0.kind\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":414,"symbol":"body_text","kind":"function","lang":"rust","doc":"Get the response body text used for this rejection.","code":"pub fn body_text(&self) -> String {\n match self.0.kind {\n ErrorKind::Message(_)\n | ErrorKind::DeserializeError { .. }\n | ErrorKind::InvalidUtf8InPathParam { .. }\n | ErrorKind::ParseError { .. }\n | ErrorKind::ParseErrorAtIndex { .. }\n | ErrorKind::ParseErrorAtKey { .. } => format!(\"Invalid URL: {}\", self.0.kind),\n ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {\n self.0.kind.to_string()\n }\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":430,"symbol":"status","kind":"function","lang":"rust","doc":"Get the status code used for this rejection.","code":"pub fn status(&self) -> StatusCode {\n match self.0.kind {\n ErrorKind::Message(_)\n | ErrorKind::DeserializeError { .. }\n | ErrorKind::InvalidUtf8InPathParam { .. }\n | ErrorKind::ParseError { .. }\n | ErrorKind::ParseErrorAtIndex { .. }\n | ErrorKind::ParseErrorAtKey { .. } => StatusCode::BAD_REQUEST,\n ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {\n StatusCode::INTERNAL_SERVER_ERROR\n }\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":446,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let body = self.body_text();\n axum_core::__log_rejection!(\n rejection_type = Self,\n body_text = body,\n status = self.status(),\n );\n (self.status(), body).into_response()\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":458,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.0.fmt(f)\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":493,"symbol":"RawPathParams","kind":"type","lang":"rust","doc":"} } let app = Router::new().route(\"/users/{user_id}/team/{team_id}\", get(users_teams_show)); # let _: Router = app; ```","code":"pub struct RawPathParams(Vec<(Arc, PercentDecodedStr)>);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":501,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n Self::from_request_extensions(&parts.extensions)\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":511,"symbol":"from_request_extensions","kind":"function","lang":"rust","doc":"Construct a `RawPathParams` from request extensions. Most users should prefer to use the `FromRequestParts` impl but special cases may require extracting `RawPathParams` outside of an async context.","code":"pub fn from_request_extensions(\n extensions: &Extensions,\n ) -> Result {\n match extensions.get::() {\n Some(UrlParams::Params { params, .. }) => Ok(Self(params.clone())),\n Some(UrlParams::InvalidUtf8InPathParam { key }) => Err(InvalidUtf8InPathParam {\n key: Arc::clone(key),\n }\n .into()),\n None => Err(MissingPathParams.into()),\n }\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":526,"symbol":"iter","kind":"function","lang":"rust","doc":"Get an iterator over the path parameters.","code":"pub fn iter(&self) -> RawPathParamsIter<'_> {\n self.into_iter()\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":535,"symbol":"into_iter","kind":"function","lang":"rust","code":"fn into_iter(self) -> Self::IntoIter {\n RawPathParamsIter(self.0.iter())\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":544,"symbol":"RawPathParamsIter","kind":"type","lang":"rust","doc":"An iterator over raw path parameters. Created with [`RawPathParams::iter`].","code":"pub struct RawPathParamsIter<'a>(std::slice::Iter<'a, (Arc, PercentDecodedStr)>);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":549,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option {\n let (key, value) = self.0.next()?;\n Some((&**key, value.as_str()))\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":558,"symbol":"InvalidUtf8InPathParam","kind":"type","lang":"rust","doc":"Rejection used by [`RawPathParams`] if a parameter contained text that, once percent decoded, wasn't valid UTF-8.","code":"pub struct InvalidUtf8InPathParam {\n key: Arc,\n}"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":565,"symbol":"body_text","kind":"function","lang":"rust","doc":"Get the response body text used for this rejection.","code":"pub fn body_text(&self) -> String {\n self.to_string()\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":571,"symbol":"status","kind":"function","lang":"rust","doc":"Get the status code used for this rejection.","code":"pub fn status(&self) -> StatusCode {\n StatusCode::BAD_REQUEST\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":577,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"Invalid UTF-8 in `{}`\", self.key)\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":585,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let body = self.body_text();\n axum_core::__log_rejection!(\n rejection_type = Self,\n body_text = body,\n status = self.status(),\n );\n (self.status(), body).into_response()\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":596,"symbol":"get_params","kind":"function","lang":"rust","code":"fn get_params(parts: &Parts) -> Result<&[(Arc, PercentDecodedStr)], PathRejection> {\n let url_params = parts\n .extensions\n .get::()\n .ok_or(MissingPathParams)?;\n\n match url_params {\n UrlParams::Params { params, .. } => Ok(params),\n UrlParams::InvalidUtf8InPathParam { key } => {\n let error = PathDeserializationError {\n kind: ErrorKind::InvalidUtf8InPathParam {\n key: key.to_string(),\n },\n };\n Err(PathRejection::from(FailedToDeserializePathParams(error)))\n }\n }\n}"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":615,"symbol":"serialize_path_params","kind":"function","lang":"rust","code":"fn serialize_path_params(params: &[(Arc, PercentDecodedStr)]) -> Result\nwhere\n T: DeserializeOwned + Send,\n E: From,\n{\n let deserializer = de::PathDeserializer::new(params);\n T::deserialize(deserializer)\n .map_err(FailedToDeserializePathParams)\n .map_err(E::from)\n}"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":634,"symbol":"extracting_url_params","kind":"function","lang":"rust","code":"async fn extracting_url_params() {\n let app = Router::new().route(\n \"/users/{id}\",\n get(|Path(id): Path| async move {\n assert_eq!(id, 42);\n })\n .post(|Path(params_map): Path>| async move {\n assert_eq!(params_map.get(\"id\").unwrap(), &1337);\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/users/42\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/users/1337\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":655,"symbol":"extracting_url_params_multiple_times","kind":"function","lang":"rust","code":"async fn extracting_url_params_multiple_times() {\n let app = Router::new().route(\"/users/{id}\", get(|_: Path, _: Path| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/users/42\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":665,"symbol":"percent_decoding","kind":"function","lang":"rust","code":"async fn percent_decoding() {\n let app = Router::new().route(\n \"/{key}\",\n get(|Path(param): Path| async move { param }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/one%20two\").await;\n\n assert_eq!(res.text().await, \"one two\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":679,"symbol":"supports_128_bit_numbers","kind":"function","lang":"rust","code":"async fn supports_128_bit_numbers() {\n let app = Router::new()\n .route(\n \"/i/{key}\",\n get(|Path(param): Path| async move { param.to_string() }),\n )\n .route(\n \"/u/{key}\",\n get(|Path(param): Path| async move { param.to_string() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/i/123\").await;\n assert_eq!(res.text().await, \"123\");\n\n let res = client.get(\"/u/123\").await;\n assert_eq!(res.text().await, \"123\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":700,"symbol":"wildcard","kind":"function","lang":"rust","code":"async fn wildcard() {\n let app = Router::new()\n .route(\n \"/foo/{*rest}\",\n get(|Path(param): Path| async move { param }),\n )\n .route(\n \"/bar/{*rest}\",\n get(|Path(params): Path>| async move {\n params.get(\"rest\").unwrap().clone()\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.text().await, \"bar/baz\");\n\n let res = client.get(\"/bar/baz/qux\").await;\n assert_eq!(res.text().await, \"baz/qux\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":723,"symbol":"captures_dont_match_empty_path","kind":"function","lang":"rust","code":"async fn captures_dont_match_empty_path() {\n let app = Router::new().route(\"/{key}\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":736,"symbol":"captures_match_empty_inner_segments","kind":"function","lang":"rust","code":"async fn captures_match_empty_inner_segments() {\n let app = Router::new().route(\n \"/{key}/method\",\n get(|Path(param): Path| async move { param.clone() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/abc/method\").await;\n assert_eq!(res.text().await, \"abc\");\n\n let res = client.get(\"//method\").await;\n assert_eq!(res.text().await, \"\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":752,"symbol":"captures_match_empty_inner_segments_near_end","kind":"function","lang":"rust","code":"async fn captures_match_empty_inner_segments_near_end() {\n let app = Router::new().route(\n \"/method/{key}/\",\n get(|Path(param): Path| async move { param.clone() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/method/abc\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/method/abc/\").await;\n assert_eq!(res.text().await, \"abc\");\n\n let res = client.get(\"/method//\").await;\n assert_eq!(res.text().await, \"\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":771,"symbol":"captures_match_empty_trailing_segment","kind":"function","lang":"rust","code":"async fn captures_match_empty_trailing_segment() {\n let app = Router::new().route(\n \"/method/{key}\",\n get(|Path(param): Path| async move { param.clone() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/method/abc/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/method/abc\").await;\n assert_eq!(res.text().await, \"abc\");\n\n let res = client.get(\"/method/\").await;\n assert_eq!(res.text().await, \"\");\n\n let res = client.get(\"/method\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":793,"symbol":"str_reference_deserialize","kind":"function","lang":"rust","code":"async fn str_reference_deserialize() {\n struct Param(String);\n impl<'de> serde::Deserialize<'de> for Param {\n fn deserialize(deserializer: D) -> Result\n where\n D: serde::Deserializer<'de>,\n {\n let s = <&str as serde::Deserialize>::deserialize(deserializer)?;\n Ok(Self(s.to_owned()))\n }\n }\n\n let app = Router::new().route(\n \"/{key}\",\n get(|param: Path| async move { param.0 .0 }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.text().await, \"foo\");\n\n // percent decoding should also work\n let res = client.get(\"/foo%20bar\").await;\n assert_eq!(res.text().await, \"foo bar\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":794,"symbol":"Param","kind":"type","lang":"rust","code":"struct Param(String);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":796,"symbol":"deserialize","kind":"function","lang":"rust","code":"fn deserialize(deserializer: D) -> Result\n where\n D: serde::Deserializer<'de>,\n {\n let s = <&str as serde::Deserialize>::deserialize(deserializer)?;\n Ok(Self(s.to_owned()))\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":821,"symbol":"two_path_extractors","kind":"function","lang":"rust","code":"async fn two_path_extractors() {\n let app = Router::new().route(\"/{a}/{b}\", get(|_: Path, _: Path| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/a/b\").await;\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(\n res.text().await,\n \"Wrong number of path arguments for `Path`. Expected 1 but got 2. \\\n Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path`\",\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":836,"symbol":"tuple_param_matches_exactly","kind":"function","lang":"rust","code":"async fn tuple_param_matches_exactly() {\n #[allow(dead_code)]\n #[derive(Deserialize)]\n struct Tuple(String, String);\n\n let app = Router::new()\n .route(\n \"/foo/{a}/{b}/{c}\",\n get(|_: Path<(String, String)>| async {}),\n )\n .route(\"/bar/{a}/{b}/{c}\", get(|_: Path| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/a/b/c\").await;\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(\n res.text().await,\n \"Wrong number of path arguments for `Path`. Expected 2 but got 3\",\n );\n\n let res = client.get(\"/bar/a/b/c\").await;\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(\n res.text().await,\n \"Wrong number of path arguments for `Path`. Expected 2 but got 3\",\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":839,"symbol":"Tuple","kind":"type","lang":"rust","code":"struct Tuple(String, String);"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":866,"symbol":"deserialize_into_vec_of_tuples","kind":"function","lang":"rust","code":"async fn deserialize_into_vec_of_tuples() {\n let app = Router::new().route(\n \"/{a}/{b}\",\n get(|Path(params): Path>| async move {\n assert_eq!(\n params,\n vec![\n (\"a\".to_owned(), \"foo\".to_owned()),\n (\"b\".to_owned(), \"bar\".to_owned())\n ]\n );\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":887,"symbol":"deserialize_into_vec_of_tuples_with_prefixes_and_suffixes","kind":"function","lang":"rust","code":"async fn deserialize_into_vec_of_tuples_with_prefixes_and_suffixes() {\n let app = Router::new().route(\n \"/f{o}o/b{a}r\",\n get(|Path(params): Path>| async move {\n assert_eq!(\n params,\n vec![\n (\"o\".to_owned(), \"0\".to_owned()),\n (\"a\".to_owned(), \"4\".to_owned())\n ]\n );\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/f0o/b4r\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":908,"symbol":"type_that_uses_deserialize_any","kind":"function","lang":"rust","code":"async fn type_that_uses_deserialize_any() {\n use time::Date;\n\n #[derive(Deserialize)]\n struct Params {\n a: Date,\n b: Date,\n c: Date,\n }\n\n let app = Router::new()\n .route(\n \"/single/{a}\",\n get(|Path(a): Path| async move { format!(\"single: {a}\") }),\n )\n .route(\n \"/tuple/{a}/{b}/{c}\",\n get(|Path((a, b, c)): Path<(Date, Date, Date)>| async move {\n format!(\"tuple: {a} {b} {c}\")\n }),\n )\n .route(\n \"/vec/{a}/{b}/{c}\",\n get(|Path(vec): Path>| async move {\n let [a, b, c]: [Date; 3] = vec.try_into().unwrap();\n format!(\"vec: {a} {b} {c}\")\n }),\n )\n .route(\n \"/vec_pairs/{a}/{b}/{c}\",\n get(|Path(vec): Path>| async move {\n let [(_, a), (_, b), (_, c)]: [(String, Date); 3] = vec.try_into().unwrap();\n format!(\"vec_pairs: {a} {b} {c}\")\n }),\n )\n ."} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":912,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n a: Date,\n b: Date,\n c: Date,\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":986,"symbol":"wrong_number_of_parameters_json","kind":"function","lang":"rust","code":"async fn wrong_number_of_parameters_json() {\n use serde_json::Value;\n\n let app = Router::new()\n .route(\"/one/{a}\", get(|_: Path<(Value, Value)>| async {}))\n .route(\"/two/{a}/{b}\", get(|_: Path| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/one/1\").await;\n assert!(res\n .text()\n .await\n .starts_with(\"Wrong number of path arguments for `Path`. Expected 2 but got 1\"));\n\n let res = client.get(\"/two/1/2\").await;\n assert!(res\n .text()\n .await\n .starts_with(\"Wrong number of path arguments for `Path`. Expected 1 but got 2\"));\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":1009,"symbol":"raw_path_params","kind":"function","lang":"rust","code":"async fn raw_path_params() {\n let app = Router::new().route(\n \"/{a}/{b}/{c}\",\n get(|params: RawPathParams| async move {\n params\n .into_iter()\n .map(|(key, value)| format!(\"{key}={value}\"))\n .collect::>()\n .join(\" \")\n }),\n );\n\n let client = TestClient::new(app);\n let res = client.get(\"/foo/bar/baz\").await;\n let body = res.text().await;\n assert_eq!(body, \"a=foo b=bar c=baz\");\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":1028,"symbol":"deserialize_error_single_value","kind":"function","lang":"rust","code":"async fn deserialize_error_single_value() {\n let app = Router::new().route(\n \"/resources/{res}\",\n get(|res: Path| async move {\n let _res = res;\n }),\n );\n\n let client = TestClient::new(app);\n let response = client.get(\"/resources/123123-123-123123\").await;\n let body = response.text().await;\n assert_eq!(\n body,\n \"Invalid URL: Cannot parse `res` with value `123123-123-123123`: UUID parsing failed: invalid group count: expected 5, found 3\"\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":1046,"symbol":"deserialize_error_multi_value","kind":"function","lang":"rust","code":"async fn deserialize_error_multi_value() {\n let app = Router::new().route(\n \"/resources/{res}/sub/{sub}\",\n get(\n |Path((res, sub)): Path<(uuid::Uuid, uuid::Uuid)>| async move {\n let _res = res;\n let _sub = sub;\n },\n ),\n );\n\n let client = TestClient::new(app);\n let response = client.get(\"/resources/456456-123-456456/sub/123\").await;\n let body = response.text().await;\n assert_eq!(\n body,\n \"Invalid URL: Cannot parse `res` with value `456456-123-456456`: UUID parsing failed: invalid group count: expected 5, found 3\"\n );\n }"} {"repo":"axum","file":"axum/src/extract/path/mod.rs","line":1067,"symbol":"regression_3038","kind":"function","lang":"rust","code":"async fn regression_3038() {\n #[derive(Deserialize)]\n #[allow(dead_code)]\n struct MoreChars {\n first_two: [char; 2],\n second_two: [char; 2],\n crate_name: String,\n }\n\n let app = Router::new().route(\n \"/{first_two}/{second_two}/{crate_name}\",\n get(|Path(_): Path| async move {}),\n );\n\n let client = TestClient::new(app);\n let res = client.get(\"/te/st/_thing\").await;\n let body = res.text().await;\n assert_eq!(body, \"Invalid URL: array types are not supported\");\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":41,"symbol":"Query","kind":"type","lang":"rust","doc":"let app = Router::new().route(\"/list_things\", get(list_things)); # let _: Router = app; ``` If the query string cannot be parsed it will reject the request with a `400 Bad Request` response.","code":"pub struct Query(pub T);"} {"repo":"axum","file":"axum/src/extract/query.rs","line":50,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n Self::try_from_uri(&parts.uri)\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":78,"symbol":"try_from_uri","kind":"function","lang":"rust","doc":"let uri: Uri = \"http://example.com/path?foo=hello&bar=42\".parse().unwrap(); let result: Query = Query::try_from_uri(&uri).unwrap(); assert_eq!(result.foo, String::from(\"hello\")); assert_eq!(result.bar, 42); ```","code":"pub fn try_from_uri(value: &Uri) -> Result {\n let query = value.query().unwrap_or_default();\n let deserializer =\n serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));\n let params = serde_path_to_error::deserialize(deserializer)\n .map_err(FailedToDeserializeQueryString::from_err)?;\n Ok(Self(params))\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":100,"symbol":"check","kind":"function","lang":"rust","code":"async fn check(uri: impl AsRef, value: T)\n where\n T: DeserializeOwned + PartialEq + Debug,\n {\n let req = Request::builder()\n .uri(uri.as_ref())\n .body(Body::empty())\n .unwrap();\n assert_eq!(Query::::from_request(req, &()).await.unwrap().0, value);\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":112,"symbol":"test_query","kind":"function","lang":"rust","code":"async fn test_query() {\n #[derive(Debug, PartialEq, Deserialize)]\n struct Pagination {\n size: Option,\n page: Option,\n }\n\n check(\n \"http://example.com/test\",\n Pagination {\n size: None,\n page: None,\n },\n )\n .await;\n\n check(\n \"http://example.com/test?size=10\",\n Pagination {\n size: Some(10),\n page: None,\n },\n )\n .await;\n\n check(\n \"http://example.com/test?size=10&page=20\",\n Pagination {\n size: Some(10),\n page: Some(20),\n },\n )\n .await;\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":114,"symbol":"Pagination","kind":"type","lang":"rust","code":"struct Pagination {\n size: Option,\n page: Option,\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":148,"symbol":"correct_rejection_status_code","kind":"function","lang":"rust","code":"async fn correct_rejection_status_code() {\n #[derive(Deserialize)]\n #[allow(dead_code)]\n struct Params {\n n: i32,\n }\n\n async fn handler(_: Query) {}\n\n let app = Router::new().route(\"/\", get(handler));\n let client = TestClient::new(app);\n\n let res = client.get(\"/?n=hi\").await;\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize query string: n: invalid digit found in string\"\n );\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":151,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n n: i32,\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":155,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Query) {}"} {"repo":"axum","file":"axum/src/extract/query.rs","line":169,"symbol":"test_try_from_uri","kind":"function","lang":"rust","code":"fn test_try_from_uri() {\n #[derive(Deserialize)]\n struct TestQueryParams {\n foo: String,\n bar: u32,\n }\n let uri: Uri = \"http://example.com/path?foo=hello&bar=42\".parse().unwrap();\n let result: Query = Query::try_from_uri(&uri).unwrap();\n assert_eq!(result.foo, String::from(\"hello\"));\n assert_eq!(result.bar, 42);\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":171,"symbol":"TestQueryParams","kind":"type","lang":"rust","code":"struct TestQueryParams {\n foo: String,\n bar: u32,\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":182,"symbol":"test_try_from_uri_with_invalid_query","kind":"function","lang":"rust","code":"fn test_try_from_uri_with_invalid_query() {\n #[derive(Deserialize)]\n struct TestQueryParams {\n _foo: String,\n _bar: u32,\n }\n let uri: Uri = \"http://example.com/path?foo=hello&bar=invalid\"\n .parse()\n .unwrap();\n let result: Result, _> = Query::try_from_uri(&uri);\n\n assert!(result.is_err());\n }"} {"repo":"axum","file":"axum/src/extract/query.rs","line":184,"symbol":"TestQueryParams","kind":"type","lang":"rust","code":"struct TestQueryParams {\n _foo: String,\n _bar: u32,\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":30,"symbol":"RawForm","kind":"type","lang":"rust","doc":"async fn handler(RawForm(form): RawForm) {} let app = Router::new().route(\"/\", get(handler)); # let _: Router = app; ```","code":"pub struct RawForm(pub Bytes);"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":38,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n if req.method() == Method::GET || req.method() == Method::HEAD {\n if let Some(query) = req.uri().query() {\n return Ok(Self(Bytes::copy_from_slice(query.as_bytes())));\n }\n\n Ok(Self(Bytes::new()))\n } else {\n if !has_content_type(req.headers(), &mime::APPLICATION_WWW_FORM_URLENCODED) {\n return Err(InvalidFormContentType.into());\n }\n\n Ok(Self(Bytes::from_request(req, state).await?))\n }\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":64,"symbol":"check_query","kind":"function","lang":"rust","code":"async fn check_query(uri: &str, value: &[u8]) {\n let req = Request::builder().uri(uri).body(Body::empty()).unwrap();\n\n assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, value);\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":70,"symbol":"check_head_query","kind":"function","lang":"rust","code":"async fn check_head_query(uri: &str, value: &[u8]) {\n let req = Request::builder()\n .method(Method::HEAD)\n .uri(uri)\n .body(Body::empty())\n .unwrap();\n\n assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, value);\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":80,"symbol":"check_body","kind":"function","lang":"rust","code":"async fn check_body(body: &'static [u8]) {\n let req = Request::post(\"http://example.com/test\")\n .header(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())\n .body(Body::from(body))\n .unwrap();\n\n assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, body);\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":90,"symbol":"test_from_query","kind":"function","lang":"rust","code":"async fn test_from_query() {\n check_query(\"http://example.com/test\", b\"\").await;\n\n check_query(\"http://example.com/test?page=0&size=10\", b\"page=0&size=10\").await;\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":97,"symbol":"test_from_head_query","kind":"function","lang":"rust","code":"async fn test_from_head_query() {\n check_head_query(\"http://example.com/test\", b\"\").await;\n\n check_head_query(\"http://example.com/test?page=0&size=10\", b\"page=0&size=10\").await;\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":104,"symbol":"test_from_body","kind":"function","lang":"rust","code":"async fn test_from_body() {\n check_body(b\"\").await;\n\n check_body(b\"username=user&password=secure%20password\").await;\n }"} {"repo":"axum","file":"axum/src/extract/raw_form.rs","line":111,"symbol":"test_incorrect_content_type","kind":"function","lang":"rust","code":"async fn test_incorrect_content_type() {\n let req = Request::post(\"http://example.com/test\")\n .body(Body::from(\"page=0&size=10\"))\n .unwrap();\n\n assert!(matches!(\n RawForm::from_request(req, &()).await.unwrap_err(),\n RawFormRejection::InvalidFormContentType(InvalidFormContentType)\n ))\n }"} {"repo":"axum","file":"axum/src/extract/raw_query.rs","line":25,"symbol":"RawQuery","kind":"type","lang":"rust","doc":"// ... } let app = Router::new().route(\"/users\", get(handler)); # let _: Router = app; ```","code":"pub struct RawQuery(pub Option);"} {"repo":"axum","file":"axum/src/extract/raw_query.rs","line":33,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let query = parts.uri.query().map(|query| query.to_owned());\n Ok(Self(query))\n }"} {"repo":"axum","file":"axum/src/extract/state.rs","line":301,"symbol":"State","kind":"type","lang":"rust","doc":".with_state(state); # let _: Router = app; ``` [global]: crate::Router::with_state [the tokio docs]: https://docs.rs/tokio/1.25.0/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use","code":"pub struct State(pub S);"} {"repo":"axum","file":"axum/src/extract/state.rs","line":310,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n state: &OuterState,\n ) -> Result {\n let inner_state = InnerState::from_ref(state);\n Ok(Self(inner_state))\n }"} {"repo":"axum","file":"axum/src/extract/state.rs","line":322,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Self::Target {\n &self.0\n }"} {"repo":"axum","file":"axum/src/extract/state.rs","line":328,"symbol":"deref_mut","kind":"function","lang":"rust","code":"fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":183,"symbol":"WebSocketUpgrade","kind":"type","lang":"rust","doc":"in later versions, `CONNECT` is used instead. To support both, it should be used with [`any`](crate::routing::any). See the [module docs](self) for an example. [`MethodFilter`]: crate::routing::MethodFilter","code":"pub struct WebSocketUpgrade {\n config: WebSocketConfig,\n /// The chosen protocol sent in the `Sec-WebSocket-Protocol` header of the response.\n protocol: Option,\n /// `None` if HTTP/2+ WebSockets are used.\n sec_websocket_key: Option,\n on_upgrade: hyper::upgrade::OnUpgrade,\n on_failed_upgrade: F,\n sec_websocket_protocol: BTreeSet,\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":195,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"WebSocketUpgrade\")\n .field(\"config\", &self.config)\n .field(\"protocol\", &self.protocol)\n .field(\"sec_websocket_key\", &self.sec_websocket_key)\n .field(\"sec_websocket_protocol\", &self.sec_websocket_protocol)\n .finish_non_exhaustive()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":207,"symbol":"read_buffer_size","kind":"function","lang":"rust","doc":"Read buffer capacity. The default value is 128KiB","code":"pub fn read_buffer_size(mut self, size: usize) -> Self {\n self.config.read_buffer_size = size;\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":221,"symbol":"write_buffer_size","kind":"function","lang":"rust","doc":"The default value is 128 KiB. If set to `0` each message will be eagerly written to the underlying stream. It is often more optimal to allow them to buffer a little, hence the default value. Note: [`flush`](SinkExt::flush) will always fully write the buffer regardless.","code":"pub fn write_buffer_size(mut self, size: usize) -> Self {\n self.config.write_buffer_size = size;\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":237,"symbol":"max_write_buffer_size","kind":"function","lang":"rust","doc":"Note: The write buffer only builds up past [`write_buffer_size`](Self::write_buffer_size) when writes to the underlying stream are failing. So the **write buffer can not fill up if you are not observing write errors even if not flushing**. Note: Should always be at least [`write_buffer_size + 1 message`](Self::write_buffer_size) and probably a little more depending on error handling strategy.","code":"pub fn max_write_buffer_size(mut self, max: usize) -> Self {\n self.config.max_write_buffer_size = max;\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":243,"symbol":"max_message_size","kind":"function","lang":"rust","doc":"Set the maximum message size (defaults to 64 megabytes)","code":"pub fn max_message_size(mut self, max: usize) -> Self {\n self.config.max_message_size = Some(max);\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":249,"symbol":"max_frame_size","kind":"function","lang":"rust","doc":"Set the maximum frame size (defaults to 16 megabytes)","code":"pub fn max_frame_size(mut self, max: usize) -> Self {\n self.config.max_frame_size = Some(max);\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":255,"symbol":"accept_unmasked_frames","kind":"function","lang":"rust","doc":"Allow server to accept unmasked frames (defaults to false)","code":"pub fn accept_unmasked_frames(mut self, accept: bool) -> Self {\n self.config.accept_unmasked_frames = accept;\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":290,"symbol":"protocols","kind":"function","lang":"rust","doc":".on_upgrade(|socket| async { // ... }) } # let _: Router = app; ```","code":"pub fn protocols(mut self, protocols: I) -> Self\n where\n I: IntoIterator,\n I::Item: Into>,\n {\n self.protocol = protocols\n .into_iter()\n .map(Into::into)\n .find(|proto| {\n // FIXME: When https://github.com/hyperium/http/pull/814\n // is merged + released, we can look use\n // `contains(proto.as_bytes())` without converting\n // to `HeaderValue` first.\n let Ok(proto) = HeaderValue::from_str(proto) else {\n return false;\n };\n self.sec_websocket_protocol.contains(&proto)\n })\n .map(|protocol| match protocol {\n Cow::Owned(s) => HeaderValue::from_str(&s).unwrap(),\n Cow::Borrowed(s) => HeaderValue::from_static(s),\n });\n\n self\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":327,"symbol":"requested_protocols","kind":"function","lang":"rust","doc":"```txt Sec-WebSocket-Protocol: soap, wamp ``` this method returns an iterator yielding `\"soap\"` and `\"wamp\"`.","code":"pub fn requested_protocols(&self) -> impl Iterator {\n self.sec_websocket_protocol.iter()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":341,"symbol":"set_selected_protocol","kind":"function","lang":"rust","doc":"# Notes - The chosen protocol is echoed back in the WebSocket upgrade response as required by RFC 6455. Some browsers may reject a value that was not present in the client's request.","code":"pub fn set_selected_protocol(&mut self, protocol: HeaderValue) {\n self.protocol = Some(protocol);\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":350,"symbol":"selected_protocol","kind":"function","lang":"rust","doc":"Return the selected WebSocket subprotocol, if one has been chosen. If [`protocols()`][Self::protocols] selects a matching protocol, or [`set_selected_protocol()`][Self::set_selected_protocol] has been called, the return value will be `Some` containing the selected protocol. Otherwise, it will be `None`.","code":"pub fn selected_protocol(&self) -> Option<&HeaderValue> {\n self.protocol.as_ref()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":378,"symbol":"on_failed_upgrade","kind":"function","lang":"rust","doc":"}) .on_upgrade(|socket| async { /* ... */ }) } # # fn report_error(_: axum::Error) {} ```","code":"pub fn on_failed_upgrade(self, callback: C) -> WebSocketUpgrade\n where\n C: OnFailedUpgrade,\n {\n WebSocketUpgrade {\n config: self.config,\n protocol: self.protocol,\n sec_websocket_key: self.sec_websocket_key,\n on_upgrade: self.on_upgrade,\n on_failed_upgrade: callback,\n sec_websocket_protocol: self.sec_websocket_protocol,\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":395,"symbol":"on_upgrade","kind":"function","lang":"rust","doc":"Finalize upgrading the connection and call the provided callback with the stream.","code":"pub fn on_upgrade(self, callback: C) -> Response\n where\n C: FnOnce(WebSocket) -> Fut + Send + 'static,\n Fut: Future + Send + 'static,\n F: OnFailedUpgrade,\n {\n let on_upgrade = self.on_upgrade;\n let config = self.config;\n let on_failed_upgrade = self.on_failed_upgrade;\n\n let protocol = self.protocol.clone();\n\n tokio::spawn(async move {\n let upgraded = match on_upgrade.await {\n Ok(upgraded) => upgraded,\n Err(err) => {\n on_failed_upgrade.call(Error::new(err));\n return;\n }\n };\n let upgraded = TokioIo::new(upgraded);\n\n let socket =\n WebSocketStream::from_raw_socket(upgraded, protocol::Role::Server, Some(config))\n .await;\n let socket = WebSocket {\n inner: socket,\n protocol,\n };\n callback(socket).await;\n });\n\n let mut response = if let Some(sec_websocket_key) = &self.sec_websocket_key {\n // If `sec_websocket_key` was `Some`, we are using HTTP/1.1.\n\n #["} {"repo":"axum","file":"axum/src/extract/ws.rs","line":465,"symbol":"OnFailedUpgrade","kind":"type","lang":"rust","doc":"What to do when a connection upgrade fails. See [`WebSocketUpgrade::on_failed_upgrade`] for more details.","code":"pub trait OnFailedUpgrade: Send + 'static {\n /// Call the callback.\n fn call(self, error: Error);\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":467,"symbol":"call","kind":"function","lang":"rust","doc":"Call the callback.","code":"fn call(self, error: Error);"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":474,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, error: Error) {\n self(error)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":484,"symbol":"DefaultOnFailedUpgrade","kind":"type","lang":"rust","doc":"The default `OnFailedUpgrade` used by `WebSocketUpgrade`. It simply ignores the error.","code":"pub struct DefaultOnFailedUpgrade;"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":488,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, _error: Error) {}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":497,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let sec_websocket_key = if parts.version <= Version::HTTP_11 {\n if parts.method != Method::GET {\n return Err(MethodNotGet.into());\n }\n\n if !header_contains(&parts.headers, &header::CONNECTION, \"upgrade\") {\n return Err(InvalidConnectionHeader.into());\n }\n\n if !header_eq(&parts.headers, &header::UPGRADE, \"websocket\") {\n return Err(InvalidUpgradeHeader.into());\n }\n\n Some(\n parts\n .headers\n .get(header::SEC_WEBSOCKET_KEY)\n .ok_or(WebSocketKeyHeaderMissing)?\n .clone(),\n )\n } else {\n if parts.method != Method::CONNECT {\n return Err(MethodNotConnect.into());\n }\n\n // if this feature flag is disabled, we won’t be receiving an HTTP/2 request to begin\n // with.\n #[cfg(feature = \"http2\")]\n if parts\n .extensions\n .get::()\n "} {"repo":"axum","file":"axum/src/extract/ws.rs","line":568,"symbol":"header_eq","kind":"function","lang":"rust","code":"fn header_eq(headers: &HeaderMap, key: &HeaderName, value: &'static str) -> bool {\n if let Some(header) = headers.get(key) {\n header.as_bytes().eq_ignore_ascii_case(value.as_bytes())\n } else {\n false\n }\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":576,"symbol":"header_contains","kind":"function","lang":"rust","code":"fn header_contains(headers: &HeaderMap, key: &HeaderName, value: &'static str) -> bool {\n let Some(header) = headers.get(key) else {\n return false;\n };\n\n if let Ok(header) = std::str::from_utf8(header.as_bytes()) {\n header.to_ascii_lowercase().contains(value)\n } else {\n false\n }\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":592,"symbol":"WebSocket","kind":"type","lang":"rust","doc":"A stream of WebSocket messages. See [the module level documentation](self) for more details.","code":"pub struct WebSocket {\n inner: WebSocketStream>,\n protocol: Option,\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":610,"symbol":"recv","kind":"function","lang":"rust","doc":"# Cancel safety This method is cancel safe. If used as a branch in [`tokio::select!`] and another branch completes first, then no message is received. [`tokio::select!`]: https://docs.rs/tokio/latest/tokio/macro.select.html","code":"pub async fn recv(&mut self) -> Option> {\n self.next().await\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":617,"symbol":"send","kind":"function","lang":"rust","doc":"Send a message. This method delegates to [`Sink`].","code":"pub async fn send(&mut self, msg: Message) -> Result<(), Error> {\n self.inner\n .send(msg.into_tungstenite())\n .await\n .map_err(Error::new)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":625,"symbol":"protocol","kind":"function","lang":"rust","doc":"Return the selected WebSocket subprotocol, if one has been chosen.","code":"pub fn protocol(&self) -> Option<&HeaderValue> {\n self.protocol.as_ref()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":632,"symbol":"is_terminated","kind":"function","lang":"rust","doc":"Returns true if the websocket has been terminated.","code":"fn is_terminated(&self) -> bool {\n self.inner.is_terminated()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":640,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n loop {\n match ready!(self.inner.poll_next_unpin(cx)) {\n Some(Ok(msg)) => {\n if let Some(msg) = Message::from_tungstenite(msg) {\n return Poll::Ready(Some(Ok(msg)));\n }\n }\n Some(Err(err)) => return Poll::Ready(Some(Err(Error::new(err)))),\n None => return Poll::Ready(None),\n }\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":658,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n Pin::new(&mut self.inner).poll_ready(cx).map_err(Error::new)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":662,"symbol":"start_send","kind":"function","lang":"rust","code":"fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {\n Pin::new(&mut self.inner)\n .start_send(item.into_tungstenite())\n .map_err(Error::new)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":668,"symbol":"poll_flush","kind":"function","lang":"rust","code":"fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n Pin::new(&mut self.inner).poll_flush(cx).map_err(Error::new)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":672,"symbol":"poll_close","kind":"function","lang":"rust","code":"fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n Pin::new(&mut self.inner).poll_close(cx).map_err(Error::new)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":681,"symbol":"Utf8Bytes","kind":"type","lang":"rust","doc":"UTF-8 wrapper for [Bytes]. An [Utf8Bytes] is always guaranteed to contain valid UTF-8.","code":"pub struct Utf8Bytes(ts::Utf8Bytes);"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":687,"symbol":"from_static","kind":"function","lang":"rust","doc":"Creates from a static str.","code":"pub const fn from_static(str: &'static str) -> Self {\n Self(ts::Utf8Bytes::from_static(str))\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":693,"symbol":"as_str","kind":"function","lang":"rust","doc":"Returns as a string slice.","code":"pub fn as_str(&self) -> &str {\n self.0.as_str()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":697,"symbol":"into_tungstenite","kind":"function","lang":"rust","code":"fn into_tungstenite(self) -> ts::Utf8Bytes {\n self.0\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":718,"symbol":"deref","kind":"function","lang":"rust","doc":"// auto-deref as arg a(&data); // deref to str methods assert_eq!(data.len(), 6); ```","code":"fn deref(&self) -> &Self::Target {\n self.as_str()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":725,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.write_str(self.as_str())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":734,"symbol":"try_from","kind":"function","lang":"rust","code":"fn try_from(bytes: Bytes) -> Result {\n Ok(Self(bytes.try_into()?))\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":743,"symbol":"try_from","kind":"function","lang":"rust","code":"fn try_from(v: Vec) -> Result {\n Ok(Self(v.try_into()?))\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":750,"symbol":"from","kind":"function","lang":"rust","code":"fn from(s: String) -> Self {\n Self(s.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":757,"symbol":"from","kind":"function","lang":"rust","code":"fn from(s: &str) -> Self {\n Self(s.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":764,"symbol":"from","kind":"function","lang":"rust","code":"fn from(s: &String) -> Self {\n Self(s.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":771,"symbol":"from","kind":"function","lang":"rust","code":"fn from(Utf8Bytes(bytes): Utf8Bytes) -> Self {\n bytes.into()\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":788,"symbol":"eq","kind":"function","lang":"rust","doc":"let payload = axum::extract::ws::Utf8Bytes::from_static(\"foo123\"); assert_eq!(payload, \"foo123\"); assert_eq!(payload, \"foo123\".to_string()); assert_eq!(payload, &\"foo123\".to_string()); assert_eq!(payload, std::borrow::Cow::from(\"foo123\")); ```","code":"fn eq(&self, other: &T) -> bool {\n self.as_str() == *other\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":798,"symbol":"CloseFrame","kind":"type","lang":"rust","doc":"A struct representing the close command.","code":"pub struct CloseFrame {\n /// The reason as a code.\n pub code: CloseCode,\n /// The reason as text string.\n pub reason: Utf8Bytes,\n}"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":829,"symbol":"Message","kind":"type","lang":"rust","doc":"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","code":"pub enum Message {\n /// A text WebSocket message\n Text(Utf8Bytes),\n /// A binary WebSocket message\n Binary(Bytes),\n /// A ping message with the specified payload\n ///\n /// The payload here must have a length less than 125 bytes.\n ///\n /// Ping messages will be automatically responded to by the server, so you do not have to worry\n /// about dealing with them yourself.\n Ping(Bytes),\n /// A pong message with the specified payload\n ///\n /// The payload here must have a length less than 125 bytes.\n ///\n /// Pong messages will be automatically sent to the client if a ping message is received, so\n /// you do not have to worry about constructing them yourself unless you want to implement a\n /// [unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3).\n Pong(Bytes),\n /// A close message with the optional close frame.\n ///\n /// You may \"uncleanly\" close a WebSocket connection at any time\n /// by simply dropping the [`WebSocket`].\n /// However, you may also use the graceful closing protocol, in which\n /// 1. peer A sends a close frame, and does not send any further messages;\n /// 2. peer B respo"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":872,"symbol":"into_tungstenite","kind":"function","lang":"rust","code":"fn into_tungstenite(self) -> ts::Message {\n match self {\n Self::Text(text) => ts::Message::Text(text.into_tungstenite()),\n Self::Binary(binary) => ts::Message::Binary(binary),\n Self::Ping(ping) => ts::Message::Ping(ping),\n Self::Pong(pong) => ts::Message::Pong(pong),\n Self::Close(Some(close)) => ts::Message::Close(Some(ts::protocol::CloseFrame {\n code: ts::protocol::frame::coding::CloseCode::from(close.code),\n reason: close.reason.into_tungstenite(),\n })),\n Self::Close(None) => ts::Message::Close(None),\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":886,"symbol":"from_tungstenite","kind":"function","lang":"rust","code":"fn from_tungstenite(message: ts::Message) -> Option {\n match message {\n ts::Message::Text(text) => Some(Self::Text(Utf8Bytes(text))),\n ts::Message::Binary(binary) => Some(Self::Binary(binary)),\n ts::Message::Ping(ping) => Some(Self::Ping(ping)),\n ts::Message::Pong(pong) => Some(Self::Pong(pong)),\n ts::Message::Close(Some(close)) => Some(Self::Close(Some(CloseFrame {\n code: close.code.into(),\n reason: Utf8Bytes(close.reason),\n }))),\n ts::Message::Close(None) => Some(Self::Close(None)),\n // we can ignore `Frame` frames as recommended by the tungstenite maintainers\n // https://github.com/snapview/tungstenite-rs/issues/268\n ts::Message::Frame(_) => None,\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":904,"symbol":"into_data","kind":"function","lang":"rust","doc":"Consume the WebSocket and return it as binary data.","code":"pub fn into_data(self) -> Bytes {\n match self {\n Self::Text(string) => Bytes::from(string),\n Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data,\n Self::Close(None) => Bytes::new(),\n Self::Close(Some(frame)) => Bytes::from(frame.reason),\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":914,"symbol":"into_text","kind":"function","lang":"rust","doc":"Attempt to consume the WebSocket message and convert it to a Utf8Bytes.","code":"pub fn into_text(self) -> Result {\n match self {\n Self::Text(string) => Ok(string),\n Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => {\n Ok(Utf8Bytes::try_from(data).map_err(Error::new)?)\n }\n Self::Close(None) => Ok(Utf8Bytes::default()),\n Self::Close(Some(frame)) => Ok(frame.reason),\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":927,"symbol":"to_text","kind":"function","lang":"rust","doc":"Attempt to get a &str from the WebSocket message, this will try to convert binary data to utf8.","code":"pub fn to_text(&self) -> Result<&str, Error> {\n match *self {\n Self::Text(ref string) => Ok(string.as_str()),\n Self::Binary(ref data) | Self::Ping(ref data) | Self::Pong(ref data) => {\n Ok(std::str::from_utf8(data).map_err(Error::new)?)\n }\n Self::Close(None) => Ok(\"\"),\n Self::Close(Some(ref frame)) => Ok(&frame.reason),\n }\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":939,"symbol":"text","kind":"function","lang":"rust","doc":"Create a new text WebSocket message from a stringable.","code":"pub fn text(string: S) -> Self\n where\n S: Into,\n {\n Self::Text(string.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":947,"symbol":"binary","kind":"function","lang":"rust","doc":"Create a new binary WebSocket message by converting to `Bytes`.","code":"pub fn binary(bin: B) -> Self\n where\n B: Into,\n {\n Self::Binary(bin.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":956,"symbol":"from","kind":"function","lang":"rust","code":"fn from(string: String) -> Self {\n Self::Text(string.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":962,"symbol":"from","kind":"function","lang":"rust","code":"fn from(string: &'s str) -> Self {\n Self::Text(string.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":968,"symbol":"from","kind":"function","lang":"rust","code":"fn from(data: &'b [u8]) -> Self {\n Self::Binary(Bytes::copy_from_slice(data))\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":974,"symbol":"from","kind":"function","lang":"rust","code":"fn from(data: Bytes) -> Self {\n Self::Binary(data)\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":980,"symbol":"from","kind":"function","lang":"rust","code":"fn from(data: Vec) -> Self {\n Self::Binary(data.into())\n }"} {"repo":"axum","file":"axum/src/extract/ws.rs","line":986,"symbol":"from","kind":"function","lang":"rust","code":"fn from(msg: Message) -> Self {\n msg.into_data().to_vec()\n }"} {"repo":"axum","file":"axum/src/form.rs","line":71,"symbol":"Form","kind":"type","lang":"rust","doc":"Form(Payload { value: \"foo\".to_owned() }) } ``` [`Query`]: crate::extract::Query [`Multipart`]: crate::extract::Multipart","code":"pub struct Form(pub T);"} {"repo":"axum","file":"axum/src/form.rs","line":80,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n let is_get_or_head =\n req.method() == http::Method::GET || req.method() == http::Method::HEAD;\n\n match req.extract().await {\n Ok(RawForm(bytes)) => {\n let deserializer =\n serde_html_form::Deserializer::new(form_urlencoded::parse(&bytes));\n let value = serde_path_to_error::deserialize(deserializer).map_err(\n |err| -> FormRejection {\n if is_get_or_head {\n FailedToDeserializeForm::from_err(err).into()\n } else {\n FailedToDeserializeFormBody::from_err(err).into()\n }\n },\n )?;\n Ok(Self(value))\n }\n Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)),\n Err(RawFormRejection::InvalidFormContentType(r)) => {\n Err(FormRejection::InvalidFormContentType(r))\n }\n }\n }"} {"repo":"axum","file":"axum/src/form.rs","line":111,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n // Extracted into separate fn so it's only compiled once for all T.\n fn make_response(ser_result: Result) -> Response {\n match ser_result {\n Ok(body) => (\n [(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())],\n body,\n )\n .into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }\n\n make_response(serde_html_form::to_string(&self.0))\n }"} {"repo":"axum","file":"axum/src/form.rs","line":113,"symbol":"make_response","kind":"function","lang":"rust","doc":"Extracted into separate fn so it's only compiled once for all T.","code":"fn make_response(ser_result: Result) -> Response {\n match ser_result {\n Ok(body) => (\n [(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())],\n body,\n )\n .into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }"} {"repo":"axum","file":"axum/src/form.rs","line":150,"symbol":"Pagination","kind":"type","lang":"rust","code":"struct Pagination {\n size: Option,\n page: Option,\n }"} {"repo":"axum","file":"axum/src/form.rs","line":155,"symbol":"check_query","kind":"function","lang":"rust","code":"async fn check_query(uri: impl AsRef, value: T) {\n let req = Request::builder()\n .uri(uri.as_ref())\n .body(Body::empty())\n .unwrap();\n assert_eq!(Form::::from_request(req, &()).await.unwrap().0, value);\n }"} {"repo":"axum","file":"axum/src/form.rs","line":163,"symbol":"check_body","kind":"function","lang":"rust","code":"async fn check_body(value: T) {\n let req = Request::builder()\n .uri(\"http://example.com/test\")\n .method(Method::POST)\n .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())\n .body(Body::from(serde_html_form::to_string(&value).unwrap()))\n .unwrap();\n assert_eq!(Form::::from_request(req, &()).await.unwrap().0, value);\n }"} {"repo":"axum","file":"axum/src/form.rs","line":174,"symbol":"test_form_query","kind":"function","lang":"rust","code":"async fn test_form_query() {\n check_query(\n \"http://example.com/test\",\n Pagination {\n size: None,\n page: None,\n },\n )\n .await;\n\n check_query(\n \"http://example.com/test?size=10\",\n Pagination {\n size: Some(10),\n page: None,\n },\n )\n .await;\n\n check_query(\n \"http://example.com/test?size=10&page=20\",\n Pagination {\n size: Some(10),\n page: Some(20),\n },\n )\n .await;\n }"} {"repo":"axum","file":"axum/src/form.rs","line":204,"symbol":"test_form_body","kind":"function","lang":"rust","code":"async fn test_form_body() {\n check_body(Pagination {\n size: None,\n page: None,\n })\n .await;\n\n check_body(Pagination {\n size: Some(10),\n page: None,\n })\n .await;\n\n check_body(Pagination {\n size: Some(10),\n page: Some(20),\n })\n .await;\n }"} {"repo":"axum","file":"axum/src/form.rs","line":225,"symbol":"test_incorrect_content_type","kind":"function","lang":"rust","code":"async fn test_incorrect_content_type() {\n let req = Request::builder()\n .uri(\"http://example.com/test\")\n .method(Method::POST)\n .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())\n .body(Body::from(\n serde_html_form::to_string(&Pagination {\n size: Some(10),\n page: None,\n })\n .unwrap(),\n ))\n .unwrap();\n assert!(matches!(\n Form::::from_request(req, &())\n .await\n .unwrap_err(),\n FormRejection::InvalidFormContentType(InvalidFormContentType)\n ));\n }"} {"repo":"axum","file":"axum/src/form.rs","line":247,"symbol":"deserialize_error_status_codes","kind":"function","lang":"rust","code":"async fn deserialize_error_status_codes() {\n #[allow(dead_code)]\n #[derive(Deserialize)]\n struct Payload {\n a: i32,\n }\n\n let app = Router::new().route(\n \"/\",\n on(\n MethodFilter::GET.or(MethodFilter::POST),\n |_: Form| async {},\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/?a=false\").await;\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize form: a: invalid digit found in string\"\n );\n\n let res = client\n .post(\"/\")\n .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())\n .body(\"a=false\")\n .await;\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize form body: a: invalid digit found in string\"\n );\n }"} {"repo":"axum","file":"axum/src/form.rs","line":250,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {\n a: i32,\n }"} {"repo":"axum","file":"axum/src/handler/future.rs","line":35,"symbol":"new","kind":"function","lang":"rust","code":"pub(super) fn new(\n inner: Map, fn(Result) -> Response>,\n ) -> Self {\n Self { inner }\n }"} {"repo":"axum","file":"axum/src/handler/future.rs","line":49,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll {\n self.project().inner.poll(cx)\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":148,"symbol":"Handler","kind":"type","lang":"rust","code":"pub trait Handler: Clone + Send + Sync + Sized + 'static {\n /// The type of future calling this handler returns.\n type Future: Future + Send + 'static;\n\n /// Call the handler with the given request.\n fn call(self, req: Request, state: S) -> Self::Future;\n\n /// Apply a [`tower::Layer`] to the handler.\n ///\n /// All requests to the handler will be processed by the layer's\n /// corresponding middleware.\n ///\n /// This can be used to add additional processing to a request for a single\n /// handler.\n ///\n /// Note this differs from [`routing::Router::layer`](crate::routing::Router::layer)\n /// which adds a middleware to a group of routes.\n ///\n /// If you're applying middleware that produces errors you have to handle the errors\n /// so they're converted into responses. You can learn more about doing that\n /// [here](crate::error_handling).\n ///\n /// # Example\n ///\n /// Adding the [`tower::limit::ConcurrencyLimit`] middleware to a handler\n /// can be done like so:\n ///\n /// ```rust\n /// use axum::{\n /// routing::get,\n /// handler::Handler,\n /// Router,\n /// };\n "} {"repo":"axum","file":"axum/src/handler/mod.rs","line":153,"symbol":"call","kind":"function","lang":"rust","doc":"Call the handler with the given request.","code":"fn call(self, req: Request, state: S) -> Self::Future;"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":189,"symbol":"layer","kind":"function","lang":"rust","doc":"async fn handler() { /* ... */ } let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64)); let app = Router::new().route(\"/\", get(layered_handler)); # let _: Router = app; ```","code":"fn layer(self, layer: L) -> Layered\n where\n L: Layer> + Clone,\n L::Service: Service,\n {\n Layered {\n layer,\n handler: self,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":202,"symbol":"with_state","kind":"function","lang":"rust","doc":"Convert the handler into a [`Service`] by providing the state","code":"fn with_state(self, state: S) -> HandlerService {\n HandlerService::new(self, state)\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":216,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, _req: Request, _state: S) -> Self::Future {\n Box::pin(async move { self().await.into_response() })\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":268,"symbol":"IntoResponseHandler","kind":"type","lang":"rust","doc":"Marker type for `impl Handler for T`","code":"pub enum IntoResponseHandler {}"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":278,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, _req: Request, _state: S) -> Self::Future {\n std::future::ready(self.into_response())\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":286,"symbol":"Layered","kind":"type","lang":"rust","doc":"A [`Service`] created from a [`Handler`] by applying a Tower middleware. Created with [`Handler::layer`]. See that method for more details.","code":"pub struct Layered {\n layer: L,\n handler: H,\n _marker: PhantomData (T, S)>,\n}"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":296,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Layered\")\n .field(\"layer\", &self.layer)\n .finish()\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":308,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n layer: self.layer.clone(),\n handler: self.handler.clone(),\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":330,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, req: Request, state: S) -> Self::Future {\n use futures_util::future::{FutureExt, Map};\n\n let svc = self.handler.with_state(state);\n let svc = self.layer.layer(svc);\n\n let future: Map<\n _,\n fn(\n Result<\n >::Response,\n >::Error,\n >,\n ) -> _,\n > = svc.oneshot(req).map(|result| match result {\n Ok(res) => res.into_response(),\n Err(err) => match err {},\n });\n\n future::LayeredFuture::new(future)\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":358,"symbol":"HandlerWithoutStateExt","kind":"type","lang":"rust","doc":"Extension trait for [`Handler`]s that don't have state. This provides convenience methods to convert the [`Handler`] into a [`Service`] or [`MakeService`]. [`MakeService`]: tower::make::MakeService","code":"pub trait HandlerWithoutStateExt: Handler {\n /// Convert the handler into a [`Service`] and no state.\n fn into_service(self) -> HandlerService;\n\n /// Convert the handler into a [`MakeService`] and no state.\n ///\n /// See [`HandlerService::into_make_service`] for more details.\n ///\n /// [`MakeService`]: tower::make::MakeService\n fn into_make_service(self) -> IntoMakeService>;\n\n /// Convert the handler into a [`MakeService`] which stores information\n /// about the incoming connection and has no state.\n ///\n /// See [`HandlerService::into_make_service_with_connect_info`] for more details.\n ///\n /// [`MakeService`]: tower::make::MakeService\n #[cfg(feature = \"tokio\")]\n fn into_make_service_with_connect_info(\n self,\n ) -> IntoMakeServiceWithConnectInfo, C>;\n}"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":360,"symbol":"into_service","kind":"function","lang":"rust","doc":"Convert the handler into a [`Service`] and no state.","code":"fn into_service(self) -> HandlerService;"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":367,"symbol":"into_make_service","kind":"function","lang":"rust","doc":"Convert the handler into a [`MakeService`] and no state. See [`HandlerService::into_make_service`] for more details. [`MakeService`]: tower::make::MakeService","code":"fn into_make_service(self) -> IntoMakeService>;"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":376,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","doc":"Convert the handler into a [`MakeService`] which stores information about the incoming connection and has no state. See [`HandlerService::into_make_service_with_connect_info`] for more details. [`MakeService`]: tower::make::MakeService","code":"fn into_make_service_with_connect_info(\n self,\n ) -> IntoMakeServiceWithConnectInfo, C>;"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":385,"symbol":"into_service","kind":"function","lang":"rust","code":"fn into_service(self) -> HandlerService {\n self.with_state(())\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":389,"symbol":"into_make_service","kind":"function","lang":"rust","code":"fn into_make_service(self) -> IntoMakeService> {\n self.into_service().into_make_service()\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":394,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","code":"fn into_make_service_with_connect_info(\n self,\n ) -> IntoMakeServiceWithConnectInfo, C> {\n self.into_service().into_make_service_with_connect_info()\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":414,"symbol":"handler_into_service","kind":"function","lang":"rust","code":"async fn handler_into_service() {\n async fn handle(body: String) -> impl IntoResponse {\n format!(\"you said: {body}\")\n }\n\n let client = TestClient::new(handle.into_service());\n\n let res = client.post(\"/\").body(\"hi there!\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"you said: hi there!\");\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":415,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(body: String) -> impl IntoResponse {\n format!(\"you said: {body}\")\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":427,"symbol":"with_layer_that_changes_request_body_and_state","kind":"function","lang":"rust","code":"async fn with_layer_that_changes_request_body_and_state() {\n async fn handle(State(state): State<&'static str>) -> &'static str {\n state\n }\n\n let svc = handle\n .layer((\n RequestBodyLimitLayer::new(1024),\n TimeoutLayer::with_status_code(\n StatusCode::REQUEST_TIMEOUT,\n Duration::from_secs(10),\n ),\n MapResponseBodyLayer::new(Body::new),\n ))\n .layer(MapRequestBodyLayer::new(Body::new))\n .with_state(\"foo\");\n\n let client = TestClient::new(svc);\n let res = client.get(\"/\").await;\n assert_eq!(res.text().await, \"foo\");\n }"} {"repo":"axum","file":"axum/src/handler/mod.rs","line":428,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(State(state): State<&'static str>) -> &'static str {\n state\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":22,"symbol":"HandlerService","kind":"type","lang":"rust","doc":"An adapter that makes a [`Handler`] into a [`Service`]. Created with [`Handler::with_state`] or [`HandlerWithoutStateExt::into_service`]. [`HandlerWithoutStateExt::into_service`]: super::HandlerWithoutStateExt::into_service","code":"pub struct HandlerService {\n handler: H,\n state: S,\n _marker: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/handler/service.rs","line":30,"symbol":"state","kind":"function","lang":"rust","doc":"Get a reference to the state.","code":"pub fn state(&self) -> &S {\n &self.state\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":63,"symbol":"into_make_service","kind":"function","lang":"rust","doc":"let listener = tokio::net::TcpListener::bind(\"0.0.0.0:3000\").await.unwrap(); axum::serve(listener, app.into_make_service()).await; # }; ``` [`MakeService`]: tower::make::MakeService","code":"pub fn into_make_service(self) -> IntoMakeService {\n IntoMakeService::new(self)\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":104,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","doc":").await; # }; ``` [`MakeService`]: tower::make::MakeService [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info","code":"pub fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo {\n IntoMakeServiceWithConnectInfo::new(self)\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":110,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n assert_send::>();\n assert_sync::>();\n}"} {"repo":"axum","file":"axum/src/handler/service.rs","line":117,"symbol":"new","kind":"function","lang":"rust","code":"pub(super) fn new(handler: H, state: S) -> Self {\n Self {\n handler,\n state,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":127,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"IntoService\").finish_non_exhaustive()\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":137,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n handler: self.handler.clone(),\n state: self.state.clone(),\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":158,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n // `IntoService` can only be constructed from async functions which are always ready, or\n // from `Layered` which buffers in `::call` and is therefore\n // also always ready.\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":165,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n use futures_util::future::FutureExt;\n\n let req = req.map(Body::new);\n\n let handler = self.handler.clone();\n let future = Handler::call(handler, req, self.state.clone());\n let future = future.map(Ok as _);\n\n super::future::IntoServiceFuture::new(future)\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":193,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/handler/service.rs","line":197,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {\n std::future::ready(Ok(self.clone()))\n }"} {"repo":"axum","file":"axum/src/json.rs","line":97,"symbol":"Json","kind":"type","lang":"rust","doc":"# unimplemented!() } let app = Router::new().route(\"/users/{id}\", get(get_user)); # let _: Router = app; ```","code":"pub struct Json(pub T);"} {"repo":"axum","file":"axum/src/json.rs","line":106,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n if !json_content_type(req.headers()) {\n return Err(MissingJsonContentType.into());\n }\n\n let bytes = Bytes::from_request(req, state).await?;\n Self::from_bytes(&bytes)\n }"} {"repo":"axum","file":"axum/src/json.rs","line":123,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result, Self::Rejection> {\n let headers = req.headers();\n if headers.get(header::CONTENT_TYPE).is_some() {\n if json_content_type(headers) {\n let bytes = Bytes::from_request(req, state).await?;\n Ok(Some(Self::from_bytes(&bytes)?))\n } else {\n Err(MissingJsonContentType.into())\n }\n } else {\n Ok(None)\n }\n }"} {"repo":"axum","file":"axum/src/json.rs","line":138,"symbol":"json_content_type","kind":"function","lang":"rust","code":"fn json_content_type(headers: &HeaderMap) -> bool {\n headers\n .get(header::CONTENT_TYPE)\n .and_then(|content_type| content_type.to_str().ok())\n .and_then(|content_type| content_type.parse::().ok())\n .is_some_and(|mime| {\n mime.type_() == \"application\"\n && (mime.subtype() == \"json\" || mime.suffix().is_some_and(|name| name == \"json\"))\n })\n}"} {"repo":"axum","file":"axum/src/json.rs","line":152,"symbol":"from","kind":"function","lang":"rust","code":"fn from(inner: T) -> Self {\n Self(inner)\n }"} {"repo":"axum","file":"axum/src/json.rs","line":164,"symbol":"from_bytes","kind":"function","lang":"rust","doc":"Construct a `Json` from a byte slice. Most users should prefer to use the `FromRequest` impl but special cases may require first extracting a `Request` into `Bytes` then optionally constructing a `Json`.","code":"pub fn from_bytes(bytes: &[u8]) -> Result {\n // Extracted into separate fn so it's only compiled once for all T.\n fn make_rejection(err: serde_path_to_error::Error) -> JsonRejection {\n match err.inner().classify() {\n serde_json::error::Category::Data => JsonDataError::from_err(err).into(),\n serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {\n JsonSyntaxError::from_err(err).into()\n }\n serde_json::error::Category::Io => {\n if cfg!(debug_assertions) {\n // we don't use `serde_json::from_reader` and instead always buffer\n // bodies first, so we shouldn't encounter any IO errors\n unreachable!()\n } else {\n JsonSyntaxError::from_err(err).into()\n }\n }\n }\n }\n\n let mut deserializer = serde_json::Deserializer::from_slice(bytes);\n\n serde_path_to_error::deserialize(&mut deserializer)\n .map_err(make_rejection)\n .and_t"} {"repo":"axum","file":"axum/src/json.rs","line":166,"symbol":"make_rejection","kind":"function","lang":"rust","doc":"Extracted into separate fn so it's only compiled once for all T.","code":"fn make_rejection(err: serde_path_to_error::Error) -> JsonRejection {\n match err.inner().classify() {\n serde_json::error::Category::Data => JsonDataError::from_err(err).into(),\n serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {\n JsonSyntaxError::from_err(err).into()\n }\n serde_json::error::Category::Io => {\n if cfg!(debug_assertions) {\n // we don't use `serde_json::from_reader` and instead always buffer\n // bodies first, so we shouldn't encounter any IO errors\n unreachable!()\n } else {\n JsonSyntaxError::from_err(err).into()\n }\n }\n }\n }"} {"repo":"axum","file":"axum/src/json.rs","line":201,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n // Extracted into separate fn so it's only compiled once for all T.\n fn make_response(buf: BytesMut, ser_result: serde_json::Result<()>) -> Response {\n match ser_result {\n Ok(()) => (\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),\n )],\n buf.freeze(),\n )\n .into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),\n )],\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }\n\n // Use a small initial capacity of 128 bytes like serde_json::to_vec\n // https://docs.rs/serde_json/1.0.82/src/serde_json/ser.rs.html#2189\n let mut buf = BytesMut::with_capacity(128).writer();\n let res = serde_json::to_write"} {"repo":"axum","file":"axum/src/json.rs","line":203,"symbol":"make_response","kind":"function","lang":"rust","doc":"Extracted into separate fn so it's only compiled once for all T.","code":"fn make_response(buf: BytesMut, ser_result: serde_json::Result<()>) -> Response {\n match ser_result {\n Ok(()) => (\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),\n )],\n buf.freeze(),\n )\n .into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),\n )],\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }"} {"repo":"axum","file":"axum/src/json.rs","line":242,"symbol":"deserialize_body","kind":"function","lang":"rust","code":"async fn deserialize_body() {\n #[derive(Debug, Deserialize)]\n struct Input {\n foo: String,\n }\n\n let app = Router::new().route(\"/\", post(|input: Json| async { input.0.foo }));\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").json(&json!({ \"foo\": \"bar\" })).await;\n let body = res.text().await;\n\n assert_eq!(body, \"bar\");\n }"} {"repo":"axum","file":"axum/src/json.rs","line":244,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n foo: String,\n }"} {"repo":"axum","file":"axum/src/json.rs","line":258,"symbol":"consume_body_to_json_requires_json_content_type","kind":"function","lang":"rust","code":"async fn consume_body_to_json_requires_json_content_type() {\n #[derive(Debug, Deserialize)]\n struct Input {\n foo: String,\n }\n\n let app = Router::new().route(\"/\", post(|input: Json| async { input.0.foo }));\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(r#\"{ \"foo\": \"bar\" }\"#).await;\n\n let status = res.status();\n\n assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);\n }"} {"repo":"axum","file":"axum/src/json.rs","line":260,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n foo: String,\n }"} {"repo":"axum","file":"axum/src/json.rs","line":275,"symbol":"json_content_types","kind":"function","lang":"rust","code":"async fn json_content_types() {\n async fn valid_json_content_type(content_type: &str) -> bool {\n println!(\"testing {content_type:?}\");\n\n let app = Router::new().route(\"/\", post(|Json(_): Json| async {}));\n\n let res = TestClient::new(app)\n .post(\"/\")\n .header(\"content-type\", content_type)\n .body(\"{}\")\n .await;\n\n res.status() == StatusCode::OK\n }\n\n assert!(valid_json_content_type(\"application/json\").await);\n assert!(valid_json_content_type(\"application/json; charset=utf-8\").await);\n assert!(valid_json_content_type(\"application/json;charset=utf-8\").await);\n assert!(valid_json_content_type(\"application/cloudevents+json\").await);\n assert!(!valid_json_content_type(\"text/json\").await);\n }"} {"repo":"axum","file":"axum/src/json.rs","line":276,"symbol":"valid_json_content_type","kind":"function","lang":"rust","code":"async fn valid_json_content_type(content_type: &str) -> bool {\n println!(\"testing {content_type:?}\");\n\n let app = Router::new().route(\"/\", post(|Json(_): Json| async {}));\n\n let res = TestClient::new(app)\n .post(\"/\")\n .header(\"content-type\", content_type)\n .body(\"{}\")\n .await;\n\n res.status() == StatusCode::OK\n }"} {"repo":"axum","file":"axum/src/json.rs","line":298,"symbol":"invalid_json_syntax","kind":"function","lang":"rust","code":"async fn invalid_json_syntax() {\n let app = Router::new().route(\"/\", post(|_: Json| async {}));\n\n let client = TestClient::new(app);\n let res = client\n .post(\"/\")\n .body(\"{\")\n .header(\"content-type\", \"application/json\")\n .await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n }"} {"repo":"axum","file":"axum/src/json.rs","line":312,"symbol":"extra_chars_after_valid_json_syntax","kind":"function","lang":"rust","code":"async fn extra_chars_after_valid_json_syntax() {\n #[derive(Debug, Deserialize)]\n struct Input {\n foo: String,\n }\n\n let app = Router::new().route(\"/\", post(|input: Json| async { input.0.foo }));\n\n let client = TestClient::new(app);\n let res = client\n .post(\"/\")\n .body(r#\"{ \"foo\": \"bar\" } baz \"#)\n .header(\"content-type\", \"application/json\")\n .await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n let body_text = res.text().await;\n assert_eq!(\n body_text,\n \"Failed to parse the request body as JSON: trailing characters at line 1 column 18\"\n );\n }"} {"repo":"axum","file":"axum/src/json.rs","line":314,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n foo: String,\n }"} {"repo":"axum","file":"axum/src/json.rs","line":336,"symbol":"Foo","kind":"type","lang":"rust","code":"struct Foo {\n #[allow(dead_code)]\n a: i32,\n #[allow(dead_code)]\n b: Vec,\n }"} {"repo":"axum","file":"axum/src/json.rs","line":344,"symbol":"Bar","kind":"type","lang":"rust","code":"struct Bar {\n #[allow(dead_code)]\n x: i32,\n #[allow(dead_code)]\n y: i32,\n }"} {"repo":"axum","file":"axum/src/json.rs","line":352,"symbol":"invalid_json_data","kind":"function","lang":"rust","code":"async fn invalid_json_data() {\n let app = Router::new().route(\"/\", post(|_: Json| async {}));\n\n let client = TestClient::new(app);\n let res = client\n .post(\"/\")\n .body(\"{\\\"a\\\": 1, \\\"b\\\": [{\\\"x\\\": 2}]}\")\n .header(\"content-type\", \"application/json\")\n .await;\n\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n let body_text = res.text().await;\n assert_eq!(\n body_text,\n \"Failed to deserialize the JSON body into the target type: b[0]: missing field `y` at line 1 column 23\"\n );\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":89,"symbol":"from_extractor","kind":"function","lang":"rust","doc":"// The extractor will run before all routes .route_layer(from_extractor::()); # let _: Router = app; ``` [`Bytes`]: bytes::Bytes","code":"pub fn from_extractor() -> FromExtractorLayer {\n from_extractor_with_state(())\n}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":96,"symbol":"from_extractor_with_state","kind":"function","lang":"rust","doc":"Create a middleware from an extractor with the given state. See [`State`](crate::extract::State) for more details about accessing state.","code":"pub fn from_extractor_with_state(state: S) -> FromExtractorLayer {\n FromExtractorLayer {\n state,\n _marker: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":110,"symbol":"FromExtractorLayer","kind":"type","lang":"rust","doc":"[`Layer`] that applies [`FromExtractor`] that runs an extractor and discards the value. See [`from_extractor`] for more details. [`Layer`]: tower::Layer","code":"pub struct FromExtractorLayer {\n state: S,\n _marker: PhantomData E>,\n}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":119,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n state: self.state.clone(),\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":131,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"FromExtractorLayer\")\n .field(\"state\", &self.state)\n .field(\"extractor\", &format_args!(\"{}\", std::any::type_name::()))\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":145,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: T) -> Self::Service {\n FromExtractor {\n inner,\n state: self.state.clone(),\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":157,"symbol":"FromExtractor","kind":"type","lang":"rust","doc":"Middleware that runs an extractor and discards the value. See [`from_extractor`] for more details.","code":"pub struct FromExtractor {\n inner: T,\n state: S,\n _extractor: PhantomData E>,\n}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":164,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n assert_send::>();\n assert_sync::>();\n}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":175,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n inner: self.inner.clone(),\n state: self.state.clone(),\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":189,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"FromExtractor\")\n .field(\"inner\", &self.inner)\n .field(\"state\", &self.state)\n .field(\"extractor\", &format_args!(\"{}\", std::any::type_name::()))\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":211,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":215,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n let state = self.state.clone();\n let (mut parts, body) = req.into_parts();\n\n let extract_future = Box::pin(async move {\n let extracted = E::from_request_parts(&mut parts, &state).await;\n let req = Request::from_parts(parts, body);\n (req, extracted)\n });\n\n ResponseFuture {\n state: State::Extracting {\n future: extract_future,\n },\n svc: Some(self.inner.clone()),\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":270,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n loop {\n let mut this = self.as_mut().project();\n\n let new_state = match this.state.as_mut().project() {\n StateProj::Extracting { future } => {\n let (req, extracted) = ready!(future.as_mut().poll(cx));\n\n match extracted {\n Ok(_) => {\n let mut svc = this.svc.take().expect(\"future polled after completion\");\n let future = svc.call(req);\n State::Call { future }\n }\n Err(err) => {\n let res = err.into_response();\n return Poll::Ready(Ok(res));\n }\n }\n }\n StateProj::Call { future } => {\n return future\n .poll(cx)\n .map(|result| result.map(IntoResponse::into_response));\n }\n };\n\n this.state.set(new_state);\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":311,"symbol":"test_from_extractor","kind":"function","lang":"rust","code":"async fn test_from_extractor() {\n #[derive(Clone)]\n struct Secret(&'static str);\n\n struct RequireAuth;\n\n impl FromRequestParts for RequireAuth\n where\n S: Send + Sync,\n Secret: FromRef,\n {\n type Rejection = StatusCode;\n\n async fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> Result {\n let Secret(secret) = Secret::from_ref(state);\n if let Some(auth) = parts\n .headers\n .get(header::AUTHORIZATION)\n .and_then(|v| v.to_str().ok())\n {\n if auth == secret {\n return Ok(Self);\n }\n }\n\n Err(StatusCode::UNAUTHORIZED)\n }\n }\n\n async fn handler() {}\n\n let state = Secret(\"secret\");\n let app = Router::new().route(\n \"/\",\n get(handler.layer(from_extractor_with_state::(state))),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").awa"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":313,"symbol":"Secret","kind":"type","lang":"rust","code":"struct Secret(&'static str);"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":315,"symbol":"RequireAuth","kind":"type","lang":"rust","code":"struct RequireAuth;"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":324,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> Result {\n let Secret(secret) = Secret::from_ref(state);\n if let Some(auth) = parts\n .headers\n .get(header::AUTHORIZATION)\n .and_then(|v| v.to_str().ok())\n {\n if auth == secret {\n return Ok(Self);\n }\n }\n\n Err(StatusCode::UNAUTHORIZED)\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":343,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":365,"symbol":"works_with_request_body_limit","kind":"function","lang":"rust","doc":"just needs to compile","code":"fn works_with_request_body_limit() {\n struct MyExtractor;\n\n impl FromRequestParts for MyExtractor\n where\n S: Send + Sync,\n {\n type Rejection = std::convert::Infallible;\n\n async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n unimplemented!()\n }\n }\n\n let _: Router = Router::new()\n .layer(from_extractor::())\n .layer(RequestBodyLimitLayer::new(1));\n }"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":366,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"struct MyExtractor;"} {"repo":"axum","file":"axum/src/middleware/from_extractor.rs","line":374,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":114,"symbol":"from_fn","kind":"function","lang":"rust","doc":".route_layer(middleware::from_fn(auth)); # let app: Router = app; ``` [extractors]: crate::extract::FromRequest [`State`]: crate::extract::State","code":"pub fn from_fn(f: F) -> FromFnLayer {\n from_fn_with_state((), f)\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":164,"symbol":"from_fn_with_state","kind":"function","lang":"rust","doc":"let app = Router::new() .route(\"/\", get(|| async { /* ... */ })) .route_layer(middleware::from_fn_with_state(state.clone(), my_middleware)) .with_state(state); # let _: axum::Router = app; ```","code":"pub fn from_fn_with_state(state: S, f: F) -> FromFnLayer {\n FromFnLayer {\n f,\n state,\n _extractor: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":178,"symbol":"FromFnLayer","kind":"type","lang":"rust","doc":"A [`tower::Layer`] from an async function. [`tower::Layer`] is used to apply middleware to [`Router`](crate::Router)'s. Created with [`from_fn`] or [`from_fn_with_state`]. See those functions for more details.","code":"pub struct FromFnLayer {\n f: F,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":189,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":205,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: I) -> Self::Service {\n FromFn {\n f: self.f.clone(),\n state: self.state.clone(),\n inner,\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":219,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"FromFnLayer\")\n // Write out the type name, without quoting it as `&type_name::()` would\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":231,"symbol":"FromFn","kind":"type","lang":"rust","doc":"A middleware created from an async function. Created with [`from_fn`] or [`from_fn_with_state`]. See those functions for more details.","code":"pub struct FromFn {\n f: F,\n inner: I,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":244,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n inner: self.inner.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":327,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"FromFnLayer\")\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"inner\", &self.inner)\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":338,"symbol":"Next","kind":"type","lang":"rust","doc":"The remainder of a middleware stack, including the handler.","code":"pub struct Next {\n inner: BoxCloneSyncService,\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":344,"symbol":"run","kind":"function","lang":"rust","doc":"Execute the remaining middleware stack.","code":"pub async fn run(mut self, req: Request) -> Response {\n match self.inner.call(req).await {\n Ok(res) => res,\n Err(err) => match err {},\n }\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":357,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":361,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n self.inner.call(req)\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":367,"symbol":"ResponseFuture","kind":"type","lang":"rust","doc":"Response future for [`FromFn`].","code":"pub struct ResponseFuture {\n inner: BoxFuture<'static, Response>,\n}"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":374,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n self.inner.as_mut().poll(cx).map(Ok)\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":380,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ResponseFuture\").finish()\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":394,"symbol":"basic","kind":"function","lang":"rust","code":"async fn basic() {\n async fn insert_header(mut req: Request, next: Next) -> impl IntoResponse {\n req.headers_mut()\n .insert(\"x-axum-test\", \"ok\".parse().unwrap());\n\n next.run(req).await\n }\n\n async fn handle(headers: HeaderMap) -> String {\n headers[\"x-axum-test\"].to_str().unwrap().to_owned()\n }\n\n let app = Router::new()\n .route(\"/\", get(handle))\n .layer(from_fn(insert_header));\n\n let res = app\n .oneshot(Request::builder().uri(\"/\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n assert_eq!(res.status(), StatusCode::OK);\n let body = res.collect().await.unwrap().to_bytes();\n assert_eq!(&body[..], b\"ok\");\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":395,"symbol":"insert_header","kind":"function","lang":"rust","code":"async fn insert_header(mut req: Request, next: Next) -> impl IntoResponse {\n req.headers_mut()\n .insert(\"x-axum-test\", \"ok\".parse().unwrap());\n\n next.run(req).await\n }"} {"repo":"axum","file":"axum/src/middleware/from_fn.rs","line":402,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(headers: HeaderMap) -> String {\n headers[\"x-axum-test\"].to_str().unwrap().to_owned()\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":117,"symbol":"map_request","kind":"function","lang":"rust","doc":".route(\"/\", get(|| async { /* ... */ })) .layer(map_request(log_path_params)); # let _: Router = app; ``` Note that to access state you must use either [`map_request_with_state`].","code":"pub fn map_request(f: F) -> MapRequestLayer {\n map_request_with_state((), f)\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":159,"symbol":"map_request_with_state","kind":"function","lang":"rust","doc":"let app = Router::new() .route(\"/\", get(|| async { /* ... */ })) .route_layer(map_request_with_state(state.clone(), my_middleware)) .with_state(state); # let _: axum::Router = app; ```","code":"pub fn map_request_with_state(state: S, f: F) -> MapRequestLayer {\n MapRequestLayer {\n f,\n state,\n _extractor: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":171,"symbol":"MapRequestLayer","kind":"type","lang":"rust","doc":"A [`tower::Layer`] from an async function that transforms a request. Created with [`map_request`]. See that function for more details.","code":"pub struct MapRequestLayer {\n f: F,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":182,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":198,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: I) -> Self::Service {\n MapRequest {\n f: self.f.clone(),\n state: self.state.clone(),\n inner,\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":212,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"MapRequestLayer\")\n // Write out the type name, without quoting it as `&type_name::()` would\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":224,"symbol":"MapRequest","kind":"type","lang":"rust","doc":"A middleware created from an async function that transforms a request. Created with [`map_request`]. See that function for more details.","code":"pub struct MapRequest {\n f: F,\n inner: I,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":237,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n inner: self.inner.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":327,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"MapRequest\")\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"inner\", &self.inner)\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":337,"symbol":"ResponseFuture","kind":"type","lang":"rust","doc":"Response future for [`MapRequest`].","code":"pub struct ResponseFuture {\n inner: BoxFuture<'static, Response>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":344,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n self.inner.as_mut().poll(cx).map(Ok)\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":350,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ResponseFuture\").finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":358,"symbol":"Sealed","kind":"type","lang":"rust","code":"pub trait Sealed {}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":367,"symbol":"IntoMapRequestResult","kind":"type","lang":"rust","doc":"Trait implemented by types that can be returned from [`map_request`], [`map_request_with_state`]. This trait is sealed such that it cannot be implemented outside this crate.","code":"pub trait IntoMapRequestResult: private::Sealed {\n /// Perform the conversion.\n #[allow(clippy::result_large_err)]\n fn into_map_request_result(self) -> Result, Response>;\n}"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":370,"symbol":"into_map_request_result","kind":"function","lang":"rust","doc":"Perform the conversion.","code":"fn into_map_request_result(self) -> Result, Response>;"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":377,"symbol":"into_map_request_result","kind":"function","lang":"rust","code":"fn into_map_request_result(self) -> Result, Response> {\n self.map_err(IntoResponse::into_response)\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":383,"symbol":"into_map_request_result","kind":"function","lang":"rust","code":"fn into_map_request_result(self) -> Result {\n Ok(self)\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":395,"symbol":"works","kind":"function","lang":"rust","code":"async fn works() {\n async fn add_header(mut req: Request) -> Request {\n req.headers_mut().insert(\"x-foo\", \"foo\".parse().unwrap());\n req\n }\n\n async fn handler(headers: HeaderMap) -> Response {\n headers[\"x-foo\"]\n .to_str()\n .unwrap()\n .to_owned()\n .into_response()\n }\n\n let app = Router::new()\n .route(\"/\", get(handler))\n .layer(map_request(add_header));\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n\n assert_eq!(res.text().await, \"foo\");\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":396,"symbol":"add_header","kind":"function","lang":"rust","code":"async fn add_header(mut req: Request) -> Request {\n req.headers_mut().insert(\"x-foo\", \"foo\".parse().unwrap());\n req\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":401,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(headers: HeaderMap) -> Response {\n headers[\"x-foo\"]\n .to_str()\n .unwrap()\n .to_owned()\n .into_response()\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":420,"symbol":"works_for_short_circutting","kind":"function","lang":"rust","code":"async fn works_for_short_circutting() {\n async fn add_header(_req: Request) -> Result, (StatusCode, &'static str)> {\n Err((StatusCode::INTERNAL_SERVER_ERROR, \"something went wrong\"))\n }\n\n async fn handler(_headers: HeaderMap) -> Response {\n unreachable!()\n }\n\n let app = Router::new()\n .route(\"/\", get(handler))\n .layer(map_request(add_header));\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(res.text().await, \"something went wrong\");\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":421,"symbol":"add_header","kind":"function","lang":"rust","code":"async fn add_header(_req: Request) -> Result, (StatusCode, &'static str)> {\n Err((StatusCode::INTERNAL_SERVER_ERROR, \"something went wrong\"))\n }"} {"repo":"axum","file":"axum/src/middleware/map_request.rs","line":425,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_headers: HeaderMap) -> Response {\n unreachable!()\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":99,"symbol":"map_response","kind":"function","lang":"rust","doc":"let app = Router::new() .route(\"/\", get(|| async { /* ... */ })) .layer(map_response(set_header)); # let _: Router = app; ```","code":"pub fn map_response(f: F) -> MapResponseLayer {\n map_response_with_state((), f)\n}"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":141,"symbol":"map_response_with_state","kind":"function","lang":"rust","doc":"let app = Router::new() .route(\"/\", get(|| async { /* ... */ })) .route_layer(map_response_with_state(state.clone(), my_middleware)) .with_state(state); # let _: axum::Router = app; ```","code":"pub fn map_response_with_state(state: S, f: F) -> MapResponseLayer {\n MapResponseLayer {\n f,\n state,\n _extractor: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":153,"symbol":"MapResponseLayer","kind":"type","lang":"rust","doc":"A [`tower::Layer`] from an async function that transforms a response. Created with [`map_response`]. See that function for more details.","code":"pub struct MapResponseLayer {\n f: F,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":164,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":180,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: I) -> Self::Service {\n MapResponse {\n f: self.f.clone(),\n state: self.state.clone(),\n inner,\n _extractor: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":194,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"MapResponseLayer\")\n // Write out the type name, without quoting it as `&type_name::()` would\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":206,"symbol":"MapResponse","kind":"type","lang":"rust","doc":"A middleware created from an async function that transforms a response. Created with [`map_response`]. See that function for more details.","code":"pub struct MapResponse {\n f: F,\n inner: I,\n state: S,\n _extractor: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":219,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n f: self.f.clone(),\n inner: self.inner.clone(),\n state: self.state.clone(),\n _extractor: self._extractor,\n }\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":315,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"MapResponse\")\n .field(\"f\", &format_args!(\"{}\", type_name::()))\n .field(\"inner\", &self.inner)\n .field(\"state\", &self.state)\n .finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":325,"symbol":"ResponseFuture","kind":"type","lang":"rust","doc":"Response future for [`MapResponse`].","code":"pub struct ResponseFuture {\n inner: BoxFuture<'static, Response>,\n}"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":332,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n self.inner.as_mut().poll(cx).map(Ok)\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":338,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ResponseFuture\").finish()\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":350,"symbol":"works","kind":"function","lang":"rust","code":"async fn works() {\n async fn add_header(mut res: Response) -> Response {\n res.headers_mut().insert(\"x-foo\", \"foo\".parse().unwrap());\n res\n }\n\n let app = Router::new().layer(map_response(add_header));\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n\n assert_eq!(res.headers()[\"x-foo\"], \"foo\");\n }"} {"repo":"axum","file":"axum/src/middleware/map_response.rs","line":351,"symbol":"add_header","kind":"function","lang":"rust","code":"async fn add_header(mut res: Response) -> Response {\n res.headers_mut().insert(\"x-foo\", \"foo\".parse().unwrap());\n res\n }"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":18,"symbol":"ResponseAxumBodyLayer","kind":"type","lang":"rust","doc":"Layer that transforms the Response body to [`crate::body::Body`]. This is useful when another layer maps the body to some other type to convert it back.","code":"pub struct ResponseAxumBodyLayer;"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":23,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n ResponseAxumBody::(inner)\n }"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":30,"symbol":"ResponseAxumBody","kind":"type","lang":"rust","doc":"Service generated by [`ResponseAxumBodyLayer`].","code":"pub struct ResponseAxumBody(S);"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":44,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.0.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":48,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n ResponseAxumBodyFuture {\n inner: self.0.call(req),\n }\n }"} {"repo":"axum","file":"axum/src/middleware/response_axum_body.rs","line":71,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n let res = ready!(this.inner.poll(cx)?);\n Poll::Ready(Ok(res.map(Body::new)))\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":37,"symbol":"Html","kind":"type","lang":"rust","doc":"An HTML response. Will automatically get `Content-Type: text/html`.","code":"pub struct Html(pub T);"} {"repo":"axum","file":"axum/src/response/mod.rs","line":43,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()),\n )],\n self.0,\n )\n .into_response()\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":56,"symbol":"from","kind":"function","lang":"rust","code":"fn from(inner: T) -> Self {\n Self(inner)\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":78,"symbol":"NoContent","kind":"type","lang":"rust","doc":"async fn delete_user(Path(user): Path) -> Result { // ...access database... # drop(user); Ok(NoContent) } ```","code":"pub struct NoContent;"} {"repo":"axum","file":"axum/src/response/mod.rs","line":81,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n StatusCode::NO_CONTENT.into_response()\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":102,"symbol":"impl_trait_result_works","kind":"function","lang":"rust","doc":"just needs to compile","code":"fn impl_trait_result_works() {\n async fn impl_trait_ok() -> Result {\n Ok(())\n }\n\n async fn impl_trait_err() -> Result<(), impl IntoResponse> {\n Err(())\n }\n\n async fn impl_trait_both(uri: Uri) -> Result {\n if uri.path() == \"/\" {\n Ok(())\n } else {\n Err(())\n }\n }\n\n async fn impl_trait(uri: Uri) -> impl IntoResponse {\n if uri.path() == \"/\" {\n Ok(())\n } else {\n Err(())\n }\n }\n\n _ = Router::<()>::new()\n .route(\"/\", get(impl_trait_ok))\n .route(\"/\", get(impl_trait_err))\n .route(\"/\", get(impl_trait_both))\n .route(\"/\", get(impl_trait));\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":103,"symbol":"impl_trait_ok","kind":"function","lang":"rust","code":"async fn impl_trait_ok() -> Result {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":107,"symbol":"impl_trait_err","kind":"function","lang":"rust","code":"async fn impl_trait_err() -> Result<(), impl IntoResponse> {\n Err(())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":111,"symbol":"impl_trait_both","kind":"function","lang":"rust","code":"async fn impl_trait_both(uri: Uri) -> Result {\n if uri.path() == \"/\" {\n Ok(())\n } else {\n Err(())\n }\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":119,"symbol":"impl_trait","kind":"function","lang":"rust","code":"async fn impl_trait(uri: Uri) -> impl IntoResponse {\n if uri.path() == \"/\" {\n Ok(())\n } else {\n Err(())\n }\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":136,"symbol":"tuple_responses","kind":"function","lang":"rust","doc":"just needs to compile","code":"fn tuple_responses() {\n async fn status() -> impl IntoResponse {\n StatusCode::OK\n }\n\n async fn status_headermap() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new())\n }\n\n async fn status_header_array() -> impl IntoResponse {\n (StatusCode::OK, [(\"content-type\", \"text/plain\")])\n }\n\n async fn status_headermap_body() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new(), String::new())\n }\n\n async fn status_header_array_body() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n String::new(),\n )\n }\n\n async fn status_headermap_impl_into_response() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new(), impl_into_response())\n }\n\n async fn status_header_array_impl_into_response() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n impl_into_response(),\n )\n }\n\n fn impl_into_response() -> impl IntoResponse {}\n\n async fn status_he"} {"repo":"axum","file":"axum/src/response/mod.rs","line":137,"symbol":"status","kind":"function","lang":"rust","code":"async fn status() -> impl IntoResponse {\n StatusCode::OK\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":141,"symbol":"status_headermap","kind":"function","lang":"rust","code":"async fn status_headermap() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":145,"symbol":"status_header_array","kind":"function","lang":"rust","code":"async fn status_header_array() -> impl IntoResponse {\n (StatusCode::OK, [(\"content-type\", \"text/plain\")])\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":149,"symbol":"status_headermap_body","kind":"function","lang":"rust","code":"async fn status_headermap_body() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new(), String::new())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":153,"symbol":"status_header_array_body","kind":"function","lang":"rust","code":"async fn status_header_array_body() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n String::new(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":161,"symbol":"status_headermap_impl_into_response","kind":"function","lang":"rust","code":"async fn status_headermap_impl_into_response() -> impl IntoResponse {\n (StatusCode::OK, HeaderMap::new(), impl_into_response())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":165,"symbol":"status_header_array_impl_into_response","kind":"function","lang":"rust","code":"async fn status_header_array_impl_into_response() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n impl_into_response(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":173,"symbol":"impl_into_response","kind":"function","lang":"rust","code":"fn impl_into_response() -> impl IntoResponse {}"} {"repo":"axum","file":"axum/src/response/mod.rs","line":175,"symbol":"status_header_array_extension_body","kind":"function","lang":"rust","code":"async fn status_header_array_extension_body() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n Extension(1),\n String::new(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":184,"symbol":"status_header_array_extension_mixed_body","kind":"function","lang":"rust","code":"async fn status_header_array_extension_mixed_body() -> impl IntoResponse {\n (\n StatusCode::OK,\n [(\"content-type\", \"text/plain\")],\n Extension(1),\n HeaderMap::new(),\n String::new(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":196,"symbol":"headermap","kind":"function","lang":"rust","code":"async fn headermap() -> impl IntoResponse {\n HeaderMap::new()\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":200,"symbol":"header_array","kind":"function","lang":"rust","code":"async fn header_array() -> impl IntoResponse {\n [(\"content-type\", \"text/plain\")]\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":204,"symbol":"headermap_body","kind":"function","lang":"rust","code":"async fn headermap_body() -> impl IntoResponse {\n (HeaderMap::new(), String::new())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":208,"symbol":"header_array_body","kind":"function","lang":"rust","code":"async fn header_array_body() -> impl IntoResponse {\n ([(\"content-type\", \"text/plain\")], String::new())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":212,"symbol":"headermap_impl_into_response","kind":"function","lang":"rust","code":"async fn headermap_impl_into_response() -> impl IntoResponse {\n (HeaderMap::new(), impl_into_response())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":216,"symbol":"header_array_impl_into_response","kind":"function","lang":"rust","code":"async fn header_array_impl_into_response() -> impl IntoResponse {\n ([(\"content-type\", \"text/plain\")], impl_into_response())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":220,"symbol":"header_array_extension_body","kind":"function","lang":"rust","code":"async fn header_array_extension_body() -> impl IntoResponse {\n (\n [(\"content-type\", \"text/plain\")],\n Extension(1),\n String::new(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":228,"symbol":"header_array_extension_mixed_body","kind":"function","lang":"rust","code":"async fn header_array_extension_mixed_body() -> impl IntoResponse {\n (\n [(\"content-type\", \"text/plain\")],\n Extension(1),\n HeaderMap::new(),\n String::new(),\n )\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":258,"symbol":"status_code_tuple_doesnt_override_error","kind":"function","lang":"rust","code":"fn status_code_tuple_doesnt_override_error() {\n // sanity check where there is just one status code\n assert_eq!(\n StatusCode::INTERNAL_SERVER_ERROR.into_response().status(),\n StatusCode::INTERNAL_SERVER_ERROR\n );\n assert_eq!(\n (StatusCode::INTERNAL_SERVER_ERROR,)\n .into_response()\n .status(),\n StatusCode::INTERNAL_SERVER_ERROR\n );\n\n // non-5xx status should be changed\n assert_eq!(\n (StatusCode::SEE_OTHER, StatusCode::NO_CONTENT)\n .into_response()\n .status(),\n StatusCode::SEE_OTHER\n );\n let res = (\n StatusCode::SEE_OTHER,\n [(\"location\", \"foo\")],\n StatusCode::NO_CONTENT,\n )\n .into_response();\n assert_eq!(res.status(), StatusCode::SEE_OTHER);\n assert_eq!(res.headers()[\"location\"], \"foo\");\n\n // 5xx status codes are also changed\n assert_eq!(\n (StatusCode::SEE_OTHER, StatusCode::INTERNAL_SERVER_ERROR)\n .into_response()\n .status(),\n StatusCode::SEE_OTHER\n );\n l"} {"repo":"axum","file":"axum/src/response/mod.rs","line":392,"symbol":"into_response_parts_failing_sets_extension","kind":"function","lang":"rust","code":"fn into_response_parts_failing_sets_extension() {\n struct Fail;\n\n impl IntoResponseParts for Fail {\n type Error = ();\n\n fn into_response_parts(\n self,\n _res: ResponseParts,\n ) -> Result {\n Err(())\n }\n }\n\n impl IntoResponse for Fail {\n fn into_response(self) -> Response {\n (self, ()).into_response()\n }\n }\n\n assert!(Fail\n .into_response()\n .extensions()\n .get::()\n .is_some());\n\n assert!((StatusCode::INTERNAL_SERVER_ERROR, Fail, ())\n .into_response()\n .extensions()\n .get::()\n .is_some());\n\n assert!((Response::new(()).into_parts().0, Fail, ())\n .into_response()\n .extensions()\n .get::()\n .is_some());\n\n assert!((Response::new(()), Fail, ())\n .into_response()\n .extensions()\n .get::()\n .is_some());\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":393,"symbol":"Fail","kind":"type","lang":"rust","code":"struct Fail;"} {"repo":"axum","file":"axum/src/response/mod.rs","line":398,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(\n self,\n _res: ResponseParts,\n ) -> Result {\n Err(())\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":407,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":438,"symbol":"doenst_override_status_code_when_using_into_response_failed_at_same_level","kind":"function","lang":"rust","code":"fn doenst_override_status_code_when_using_into_response_failed_at_same_level() {\n assert_eq!(\n (StatusCode::INTERNAL_SERVER_ERROR, IntoResponseFailed, ())\n .into_response()\n .status(),\n StatusCode::INTERNAL_SERVER_ERROR,\n );\n\n #[derive(Clone)]\n struct Thing;\n\n let res = (\n Response::builder()\n .status(StatusCode::INTERNAL_SERVER_ERROR)\n .header(\"x-foo\", \"foo\")\n .extension(Thing)\n .body(())\n .unwrap()\n .into_parts()\n .0,\n IntoResponseFailed,\n (),\n )\n .into_response();\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n assert_eq!(res.headers()[\"x-foo\"], \"foo\");\n assert!(res.extensions().get::().is_some());\n\n // just a sanity check\n assert_eq!(\n (IntoResponseFailed, ()).into_response().status(),\n StatusCode::OK,\n );\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":447,"symbol":"Thing","kind":"type","lang":"rust","code":"struct Thing;"} {"repo":"axum","file":"axum/src/response/mod.rs","line":474,"symbol":"force_overriding_status_code","kind":"function","lang":"rust","code":"fn force_overriding_status_code() {\n assert_eq!(\n ForceStatusCode(StatusCode::IM_A_TEAPOT)\n .into_response()\n .status(),\n StatusCode::IM_A_TEAPOT\n );\n\n assert_eq!(\n (ForceStatusCode(StatusCode::IM_A_TEAPOT),)\n .into_response()\n .status(),\n StatusCode::IM_A_TEAPOT\n );\n\n assert_eq!(\n (ForceStatusCode(StatusCode::IM_A_TEAPOT), ())\n .into_response()\n .status(),\n StatusCode::IM_A_TEAPOT\n );\n\n assert_eq!(\n (\n ForceStatusCode(StatusCode::IM_A_TEAPOT),\n IntoResponseFailed,\n StatusCode::INTERNAL_SERVER_ERROR,\n )\n .into_response()\n .status(),\n StatusCode::IM_A_TEAPOT\n );\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":509,"symbol":"status_code_tuple_doesnt_override_error_json","kind":"function","lang":"rust","code":"async fn status_code_tuple_doesnt_override_error_json() {\n let app = Router::new()\n .route(\n \"/\",\n get(|| async {\n let not_json_compatible = HashMap::from([(Vec::from([1, 2, 3]), 123)]);\n (StatusCode::IM_A_TEAPOT, Json(not_json_compatible))\n }),\n )\n .route(\n \"/two\",\n get(|| async {\n let not_json_compatible = HashMap::from([(Vec::from([1, 2, 3]), 123)]);\n (\n ForceStatusCode(StatusCode::IM_A_TEAPOT),\n Json(not_json_compatible),\n )\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n\n let res = client.get(\"/two\").await;\n assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);\n }"} {"repo":"axum","file":"axum/src/response/mod.rs","line":539,"symbol":"no_content","kind":"function","lang":"rust","code":"fn no_content() {\n assert_eq!(\n super::NoContent.into_response().status(),\n StatusCode::NO_CONTENT,\n )\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":22,"symbol":"Redirect","kind":"type","lang":"rust","doc":"let app = Router::new() .route(\"/old\", get(|| async { Redirect::permanent(\"/new\") })) .route(\"/new\", get(|| async { \"Hello!\" })); # let _: Router = app; ```","code":"pub struct Redirect {\n status_code: StatusCode,\n location: String,\n}"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":37,"symbol":"to","kind":"function","lang":"rust","doc":"to the given `uri`, which is useful after successful form submission, file upload or when you generally don't want the redirected-to page to observe the original request method and body (if non-empty). If you want to preserve the request method and body, [`Redirect::temporary`] should be used instead. [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303","code":"pub fn to(uri: impl Into) -> Self {\n Self::with_status_code(StatusCode::SEE_OTHER, uri.into())\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":47,"symbol":"temporary","kind":"function","lang":"rust","doc":"Create a new [`Redirect`] that uses a [`307 Temporary Redirect`][mdn] status code. This has the same behavior as [`Redirect::to`], except it will preserve the original HTTP method and body. [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307","code":"pub fn temporary(uri: impl Into) -> Self {\n Self::with_status_code(StatusCode::TEMPORARY_REDIRECT, uri.into())\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":54,"symbol":"permanent","kind":"function","lang":"rust","doc":"Create a new [`Redirect`] that uses a [`308 Permanent Redirect`][mdn] status code. [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308","code":"pub fn permanent(uri: impl Into) -> Self {\n Self::with_status_code(StatusCode::PERMANENT_REDIRECT, uri.into())\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":60,"symbol":"status_code","kind":"function","lang":"rust","doc":"Returns the HTTP status code of the `Redirect`.","code":"pub fn status_code(&self) -> StatusCode {\n self.status_code\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":66,"symbol":"location","kind":"function","lang":"rust","doc":"Returns the `Redirect`'s URI.","code":"pub fn location(&self) -> &str {\n &self.location\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":74,"symbol":"with_status_code","kind":"function","lang":"rust","doc":"This is intentionally not public since other kinds of redirects might not use the `Location` header, namely `304 Not Modified`. We're open to adding more constructors upon request, if they make sense :)","code":"fn with_status_code(status_code: StatusCode, uri: String) -> Self {\n assert!(\n status_code.is_redirection(),\n \"not a redirection status code\"\n );\n\n Self {\n status_code,\n location: uri,\n }\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":88,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":132,"symbol":"into_response_parts","kind":"function","lang":"rust","doc":"let response = ( StatusCode::TEMPORARY_REDIRECT, Redirect::to(\"/new\"), \"redirecting...\", ); ```","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n match HeaderValue::try_from(self.location) {\n Ok(location) => {\n *res.status_mut() = self.status_code;\n res.headers_mut().insert(LOCATION, location);\n Ok(res)\n }\n Err(err) => Err((\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"invalid redirect location: {err}\"),\n )),\n }\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":158,"symbol":"correct_status","kind":"function","lang":"rust","doc":"Tests to make sure Redirect has the correct status codes based on the way it was constructed.","code":"fn correct_status() {\n assert_eq!(\n StatusCode::SEE_OTHER,\n Redirect::to(EXAMPLE_URL).status_code()\n );\n\n assert_eq!(\n StatusCode::TEMPORARY_REDIRECT,\n Redirect::temporary(EXAMPLE_URL).status_code()\n );\n\n assert_eq!(\n StatusCode::PERMANENT_REDIRECT,\n Redirect::permanent(EXAMPLE_URL).status_code()\n );\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":176,"symbol":"correct_location","kind":"function","lang":"rust","code":"fn correct_location() {\n assert_eq!(EXAMPLE_URL, Redirect::permanent(EXAMPLE_URL).location());\n\n assert_eq!(\"/redirect\", Redirect::permanent(\"/redirect\").location())\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":183,"symbol":"test_internal_error","kind":"function","lang":"rust","code":"fn test_internal_error() {\n let response = Redirect::permanent(\"Axum is awesome, \\n but newlines aren't allowed :(\")\n .into_response();\n\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":191,"symbol":"into_response_parts_sets_status_and_location","kind":"function","lang":"rust","code":"fn into_response_parts_sets_status_and_location() {\n let response = (Redirect::to(EXAMPLE_URL), \"body\").into_response();\n\n assert_eq!(response.status(), StatusCode::SEE_OTHER);\n assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":199,"symbol":"into_response_parts_with_permanent_redirect","kind":"function","lang":"rust","code":"fn into_response_parts_with_permanent_redirect() {\n let response = (Redirect::permanent(EXAMPLE_URL), \"body\").into_response();\n\n assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":207,"symbol":"into_response_parts_with_temporary_redirect","kind":"function","lang":"rust","code":"fn into_response_parts_with_temporary_redirect() {\n let response = (Redirect::temporary(EXAMPLE_URL), \"body\").into_response();\n\n assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);\n assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":215,"symbol":"into_response_parts_explicit_status_overrides","kind":"function","lang":"rust","code":"fn into_response_parts_explicit_status_overrides() {\n // Explicit StatusCode in a tuple takes precedence over the Redirect status\n let response = (\n StatusCode::TEMPORARY_REDIRECT,\n Redirect::to(EXAMPLE_URL),\n \"body\",\n )\n .into_response();\n\n assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);\n assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);\n }"} {"repo":"axum","file":"axum/src/response/redirect.rs","line":229,"symbol":"into_response_parts_invalid_location","kind":"function","lang":"rust","code":"fn into_response_parts_invalid_location() {\n let response = (Redirect::permanent(\"invalid\\nlocation\"), \"body\").into_response();\n\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":85,"symbol":"Sse","kind":"type","lang":"rust","doc":"An SSE response","code":"pub struct Sse {\n stream: S,\n}"} {"repo":"axum","file":"axum/src/response/sse.rs","line":94,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new [`Sse`] response that will respond with the given stream of [`Event`]s. See the [module docs](self) for more details.","code":"pub fn new(stream: S) -> Self\n where\n S: TryStream + Send + 'static,\n S::Error: Into,\n {\n Self { stream }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":106,"symbol":"keep_alive","kind":"function","lang":"rust","doc":"Configure the interval between keep-alive messages. Defaults to no keep-alive messages.","code":"pub fn keep_alive(self, keep_alive: KeepAlive) -> Sse> {\n Sse {\n stream: KeepAliveStream::new(keep_alive, self.stream),\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":114,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Sse\")\n .field(\"stream\", &format_args!(\"{}\", std::any::type_name::()))\n .finish()\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":126,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (\n [\n (http::header::CONTENT_TYPE, mime::TEXT_EVENT_STREAM.as_ref()),\n (http::header::CACHE_CONTROL, \"no-cache\"),\n ],\n Body::new(SseBody {\n event_stream: SyncWrapper::new(self.stream),\n }),\n )\n .into_response()\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":154,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n let this = self.project();\n\n match ready!(this.event_stream.get_pin_mut().poll_next(cx)) {\n Some(Ok(event)) => Poll::Ready(Some(Ok(Frame::data(event.finalize())))),\n Some(Err(error)) => Poll::Ready(Some(Err(error))),\n None => Poll::Ready(None),\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":178,"symbol":"Buffer","kind":"type","lang":"rust","doc":"by using a finalized buffer. While the buffer is active, more bytes can be written to it. Once finalized, it's immutable and cheap to clone. The buffer is active during the event building, but eventually becomes finalized to send http body frames as [`Bytes`].","code":"enum Buffer {\n Active(BytesMut),\n Finalized(Bytes),\n}"} {"repo":"axum","file":"axum/src/response/sse.rs","line":188,"symbol":"as_mut","kind":"function","lang":"rust","doc":"Returns a mutable reference to the internal buffer. If the buffer was finalized, this method creates a new active buffer with the previous contents.","code":"fn as_mut(&mut self) -> &mut BytesMut {\n match self {\n Self::Active(bytes_mut) => bytes_mut,\n Self::Finalized(bytes) => {\n *self = Self::Active(BytesMut::from(mem::take(bytes)));\n match self {\n Self::Active(bytes_mut) => bytes_mut,\n Self::Finalized(_) => unreachable!(),\n }\n }\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":205,"symbol":"Event","kind":"type","lang":"rust","doc":"Server-sent event","code":"pub struct Event {\n buffer: Buffer,\n flags: EventFlags,\n}"} {"repo":"axum","file":"axum/src/response/sse.rs","line":223,"symbol":"EventDataWriter","kind":"type","lang":"rust","doc":"pair is treated as a single line ending. # Panics Panics if any `data` has already been written prior to the first write of this [`EventDataWriter`] instance.","code":"pub struct EventDataWriter {\n event: Event,\n\n // Indicates if _this_ EventDataWriter has written data,\n // this does not say anything about whether or not `event` contains\n // data or not.\n data_written: bool,\n\n // A trailing CR might be followed by an LF in the next write. Defer the\n // next `data: ` prefix until we know whether they form a CRLF pair.\n pending_cr: bool,\n}"} {"repo":"axum","file":"axum/src/response/sse.rs","line":240,"symbol":"finalized","kind":"function","lang":"rust","code":"const fn finalized(bytes: Bytes) -> Self {\n Self {\n buffer: Buffer::Finalized(bytes),\n flags: EventFlags::from_bits(0),\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":275,"symbol":"raw","kind":"function","lang":"rust","doc":"``` use axum::response::sse::Event; let event = Event::raw(\"data: hi\\n\\n\"); ```","code":"pub fn raw(bytes: T) -> Self\n where\n T: Into,\n {\n Self::finalized(bytes.into())\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":288,"symbol":"into_data_writer","kind":"function","lang":"rust","doc":"Use this [`Event`] as a [`EventDataWriter`] to write custom data. - [`Self::data`] can be used as a shortcut to write `str` data - [`Self::json_data`] can be used as a shortcut to write `json` data Turn it into an [`Event`] again using [`EventDataWriter::into_event`].","code":"pub fn into_data_writer(self) -> EventDataWriter {\n EventDataWriter {\n event: self,\n data_written: false,\n pending_cr: false,\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":309,"symbol":"data","kind":"function","lang":"rust","doc":"# Panics Panics if any `data` has already been written before. [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data","code":"pub fn data(self, data: T) -> Self\n where\n T: AsRef,\n {\n let mut writer = self.into_data_writer();\n let _ = writer.write_str(data.as_ref());\n writer.into_event()\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":328,"symbol":"json_data","kind":"function","lang":"rust","doc":"# Panics Panics if any `data` has already been written before. [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data","code":"pub fn json_data(self, data: T) -> Result\n where\n T: serde_core::Serialize,\n {\n struct JsonWriter<'a>(&'a mut EventDataWriter);\n impl std::io::Write for JsonWriter<'_> {\n #[inline]\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n Ok(self.0.write_buf(buf))\n }\n fn flush(&mut self) -> std::io::Result<()> {\n Ok(())\n }\n }\n\n let mut writer = self.into_data_writer();\n\n let json_writer = JsonWriter(&mut writer);\n serde_json::to_writer(json_writer, &data).map_err(axum_core::Error::new)?;\n\n Ok(writer.into_event())\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":332,"symbol":"JsonWriter","kind":"type","lang":"rust","code":"struct JsonWriter<'a>(&'a mut EventDataWriter);"} {"repo":"axum","file":"axum/src/response/sse.rs","line":335,"symbol":"write","kind":"function","lang":"rust","code":"fn write(&mut self, buf: &[u8]) -> std::io::Result {\n Ok(self.0.write_buf(buf))\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":338,"symbol":"flush","kind":"function","lang":"rust","code":"fn flush(&mut self) -> std::io::Result<()> {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":361,"symbol":"comment","kind":"function","lang":"rust","doc":"Unlike other functions, this function can be called multiple times to add many comments. # Panics Panics if `comment` contains any newlines or carriage returns, as they are not allowed in comments.","code":"pub fn comment(mut self, comment: T) -> Self\n where\n T: AsRef,\n {\n self.field(\"\", comment.as_ref());\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":383,"symbol":"event","kind":"function","lang":"rust","doc":"[`message` event]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event # Panics - Panics if `event` contains any newlines or carriage returns. - Panics if this function has already been called on this event.","code":"pub fn event(mut self, event: T) -> Self\n where\n T: AsRef,\n {\n if self.flags.contains(EventFlags::HAS_EVENT) {\n panic!(\"Called `Event::event` multiple times\");\n }\n self.flags.insert(EventFlags::HAS_EVENT);\n\n self.field(\"event\", event.as_ref());\n\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":406,"symbol":"retry","kind":"function","lang":"rust","doc":"SSE endpoint. Note that this is just a hint: clients are free to wait for longer if they wish, such as if they implement exponential backoff. # Panics Panics if this function has already been called on this event.","code":"pub fn retry(mut self, duration: Duration) -> Self {\n if self.flags.contains(EventFlags::HAS_RETRY) {\n panic!(\"Called `Event::retry` multiple times\");\n }\n self.flags.insert(EventFlags::HAS_RETRY);\n\n let buffer = self.buffer.as_mut();\n buffer.extend_from_slice(b\"retry: \");\n\n let secs = duration.as_secs();\n let millis = duration.subsec_millis();\n\n if secs > 0 {\n // format seconds\n buffer.extend_from_slice(itoa::Buffer::new().format(secs).as_bytes());\n\n // pad milliseconds\n if millis < 10 {\n buffer.extend_from_slice(b\"00\");\n } else if millis < 100 {\n buffer.extend_from_slice(b\"0\");\n }\n }\n\n // format milliseconds\n buffer.extend_from_slice(itoa::Buffer::new().format(millis).as_bytes());\n\n buffer.put_u8(b'\\n');\n\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":450,"symbol":"id","kind":"function","lang":"rust","doc":"[`MessageEvent`'s `lastEventId` field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/lastEventId # Panics - Panics if `id` contains any newlines, carriage returns or null characters. - Panics if this function has already been called on this event.","code":"pub fn id(mut self, id: T) -> Self\n where\n T: AsRef,\n {\n if self.flags.contains(EventFlags::HAS_ID) {\n panic!(\"Called `Event::id` multiple times\");\n }\n self.flags.insert(EventFlags::HAS_ID);\n\n let id = id.as_ref().as_bytes();\n assert_eq!(\n memchr::memchr(b'\\0', id),\n None,\n \"Event ID cannot contain null characters\",\n );\n\n self.field(\"id\", id);\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":470,"symbol":"field","kind":"function","lang":"rust","code":"fn field(&mut self, name: &str, value: impl AsRef<[u8]>) {\n let value = value.as_ref();\n assert_eq!(\n memchr::memchr2(b'\\r', b'\\n', value),\n None,\n \"SSE field value cannot contain newlines or carriage returns\",\n );\n\n let buffer = self.buffer.as_mut();\n buffer.extend_from_slice(name.as_bytes());\n buffer.put_u8(b':');\n buffer.put_u8(b' ');\n buffer.extend_from_slice(value);\n buffer.put_u8(b'\\n');\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":489,"symbol":"finalize","kind":"function","lang":"rust","doc":"Turns the event to `Bytes` ready to be sent If the events is already finalized just returns the `Bytes` again","code":"pub fn finalize(self) -> Bytes {\n match self.buffer {\n Buffer::Finalized(bytes) => bytes,\n Buffer::Active(mut bytes_mut) => {\n bytes_mut.put_u8(b'\\n');\n bytes_mut.freeze()\n }\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":505,"symbol":"into_event","kind":"function","lang":"rust","doc":"Consume the [`EventDataWriter`] and return the [`Event`] once again. In case any data was written by this instance it will also write the trailing `\\n` character.","code":"pub fn into_event(self) -> Event {\n let mut event = self.event;\n if self.data_written {\n let buffer = event.buffer.as_mut();\n if self.pending_cr {\n let _ = buffer.write_str(\"data: \");\n }\n let _ = buffer.write_char('\\n');\n }\n event\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":521,"symbol":"write_buf","kind":"function","lang":"rust","doc":"Assumption: underlying writer never returns an error: ","code":"fn write_buf(&mut self, buf: &[u8]) -> usize {\n if buf.is_empty() {\n return 0;\n }\n\n let pending_cr = mem::take(&mut self.pending_cr);\n let buffer = self.event.buffer.as_mut();\n\n if !std::mem::replace(&mut self.data_written, true) {\n if self.event.flags.contains(EventFlags::HAS_DATA) {\n panic!(\"Called `Event::data*` multiple times\");\n }\n\n let _ = buffer.write_str(\"data: \");\n self.event.flags.insert(EventFlags::HAS_DATA);\n }\n\n let mut writer = buffer.writer();\n\n if pending_cr && buf[0] != b'\\n' {\n let _ = writer.write_all(b\"data: \");\n }\n\n let mut last_split = 0;\n for delimiter in memchr::memchr2_iter(b'\\n', b'\\r', buf) {\n if buf[delimiter] == b'\\r' && buf.get(delimiter + 1) == Some(&b'\\n') {\n continue;\n }\n\n let _ = writer.write_all(&buf[last_split..=delimiter]);\n last_split = delimiter + 1;\n\n if buf[delimiter] != b'\\r' || last_split != buf.len() {\n let _ = writer.write_all(b\"data: \");\n }\n }\n let _ = writer.write_all(&buf"} {"repo":"axum","file":"axum/src/response/sse.rs","line":566,"symbol":"write_str","kind":"function","lang":"rust","code":"fn write_str(&mut self, s: &str) -> fmt::Result {\n let _ = self.write_buf(s.as_bytes());\n Ok(())\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":573,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self {\n buffer: Buffer::Active(BytesMut::new()),\n flags: EventFlags::from_bits(0),\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":582,"symbol":"EventFlags","kind":"type","lang":"rust","code":"struct EventFlags(u8);"} {"repo":"axum","file":"axum/src/response/sse.rs","line":590,"symbol":"bits","kind":"function","lang":"rust","code":"const fn bits(self) -> u8 {\n self.0\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":594,"symbol":"from_bits","kind":"function","lang":"rust","code":"const fn from_bits(bits: u8) -> Self {\n Self(bits)\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":598,"symbol":"contains","kind":"function","lang":"rust","code":"const fn contains(self, other: Self) -> bool {\n self.bits() & other.bits() == other.bits()\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":602,"symbol":"insert","kind":"function","lang":"rust","code":"fn insert(&mut self, other: Self) {\n *self = Self::from_bits(self.bits() | other.bits());\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":611,"symbol":"KeepAlive","kind":"type","lang":"rust","doc":"Configure the interval between keep-alive messages, the content of each message, and the associated stream.","code":"pub struct KeepAlive {\n event: Event,\n max_interval: Duration,\n}"} {"repo":"axum","file":"axum/src/response/sse.rs","line":618,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `KeepAlive`.","code":"pub fn new() -> Self {\n Self {\n event: Event::DEFAULT_KEEP_ALIVE,\n max_interval: Duration::from_secs(15),\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":628,"symbol":"interval","kind":"function","lang":"rust","doc":"Customize the interval between keep-alive messages. Default is 15 seconds.","code":"pub fn interval(mut self, time: Duration) -> Self {\n self.max_interval = time;\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":641,"symbol":"text","kind":"function","lang":"rust","doc":"Default is an empty comment. # Panics Panics if `text` contains any newline or carriage returns, as they are not allowed in SSE comments.","code":"pub fn text(self, text: I) -> Self\n where\n I: AsRef,\n {\n self.event(Event::default().comment(text))\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":656,"symbol":"event","kind":"function","lang":"rust","doc":"Default is an empty comment. # Panics Panics if `event` contains any newline or carriage returns, as they are not allowed in SSE comments.","code":"pub fn event(mut self, event: Event) -> Self {\n self.event = Event::finalized(event.finalize());\n self\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":663,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self::new()\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":683,"symbol":"new","kind":"function","lang":"rust","code":"fn new(keep_alive: KeepAlive, inner: S) -> Self {\n Self {\n alive_timer: tokio::time::sleep(keep_alive.max_interval),\n inner,\n keep_alive,\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":691,"symbol":"reset","kind":"function","lang":"rust","code":"fn reset(self: Pin<&mut Self>) {\n let this = self.project();\n this.alive_timer\n .reset(tokio::time::Instant::now() + this.keep_alive.max_interval);\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":705,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n use std::future::Future;\n\n let mut this = self.as_mut().project();\n\n match this.inner.as_mut().poll_next(cx) {\n Poll::Ready(Some(Ok(event))) => {\n self.reset();\n\n Poll::Ready(Some(Ok(event)))\n }\n Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),\n Poll::Ready(None) => Poll::Ready(None),\n Poll::Pending => {\n ready!(this.alive_timer.poll(cx));\n\n let event = this.keep_alive.event.clone();\n\n self.reset();\n\n Poll::Ready(Some(Ok(event)))\n }\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":741,"symbol":"leading_space_is_not_stripped","kind":"function","lang":"rust","code":"fn leading_space_is_not_stripped() {\n let no_leading_space = Event::default().data(\"\\tfoobar\");\n assert_eq!(&*no_leading_space.finalize(), b\"data: \\tfoobar\\n\\n\");\n\n let leading_space = Event::default().data(\" foobar\");\n assert_eq!(&*leading_space.finalize(), b\"data: foobar\\n\\n\");\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":750,"symbol":"write_data_writer_str","kind":"function","lang":"rust","code":"fn write_data_writer_str() {\n // also confirm that nop writers do nothing :)\n let mut writer = Event::default()\n .into_data_writer()\n .into_event()\n .into_data_writer();\n writer.write_str(\"\").unwrap();\n let mut writer = writer.into_event().into_data_writer();\n\n writer.write_str(\"\").unwrap();\n writer.write_str(\"moon \").unwrap();\n writer.write_str(\"star\\nsun\").unwrap();\n writer.write_str(\"\").unwrap();\n writer.write_str(\"set\").unwrap();\n writer.write_str(\"\").unwrap();\n writer.write_str(\" bye\\r\").unwrap();\n\n let event = writer.into_event();\n\n assert_eq!(\n &*event.finalize(),\n b\"data: moon star\\ndata: sunset bye\\rdata: \\n\\n\"\n );\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":776,"symbol":"crlf_is_one_line_ending","kind":"function","lang":"rust","code":"fn crlf_is_one_line_ending() {\n let event = Event::default().data(\"first\\r\\nsecond\");\n\n assert_eq!(&*event.finalize(), b\"data: first\\r\\ndata: second\\n\\n\");\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":783,"symbol":"data_writer_output_is_independent_of_write_boundaries","kind":"function","lang":"rust","code":"fn data_writer_output_is_independent_of_write_boundaries() {\n let data = \"first\\r\\nsecond\\rthird\\nfourth\\r\";\n let expected = b\"data: first\\r\\ndata: second\\rdata: third\\ndata: fourth\\rdata: \\n\\n\";\n\n for first_split in 0..=data.len() {\n for second_split in first_split..=data.len() {\n let mut writer = Event::default().into_data_writer();\n writer.write_str(&data[..first_split]).unwrap();\n writer.write_str(&data[first_split..second_split]).unwrap();\n writer.write_str(&data[second_split..]).unwrap();\n\n assert_eq!(\n &*writer.into_event().finalize(),\n expected,\n \"write boundaries at {first_split} and {second_split}\"\n );\n }\n }\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":804,"symbol":"valid_json_raw_value_chars_handled","kind":"function","lang":"rust","code":"fn valid_json_raw_value_chars_handled() {\n let json_string = \"{\\r\\\"foo\\\": \\n\\r\\r \\\"bar\\\\n\\\"\\n}\";\n let json_raw_value_event = Event::default()\n .json_data(serde_json::from_str::<&RawValue>(json_string).unwrap())\n .unwrap();\n assert_eq!(\n &*json_raw_value_event.finalize(),\n b\"data: {\\rdata: \\\"foo\\\": \\ndata: \\rdata: \\rdata: \\\"bar\\\\n\\\"\\ndata: }\\n\\n\"\n );\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":816,"symbol":"raw_event_round_trips_bytes_exactly","kind":"function","lang":"rust","code":"fn raw_event_round_trips_bytes_exactly() {\n let event = Event::raw(b\"data: hi\\n\\n\".as_slice());\n assert_eq!(&*event.finalize(), b\"data: hi\\n\\n\");\n\n let empty = Event::raw(Bytes::new());\n assert_eq!(&*empty.finalize(), b\"\");\n\n // No trailing `\\n` is appended, unlike an `Active` buffer.\n let no_trailing_newline = Event::raw(b\"data: hi\".as_slice());\n assert_eq!(&*no_trailing_newline.finalize(), b\"data: hi\");\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":829,"symbol":"raw_event_then_comment_appends_and_reterminates","kind":"function","lang":"rust","code":"fn raw_event_then_comment_appends_and_reterminates() {\n // Once further builder methods are called, the `Finalized` buffer is converted back\n // into an `Active` one, so a trailing `\\n` is added again on top of the appended field.\n let event = Event::raw(b\"data: hi\\n\\n\".as_slice()).comment(\"x\");\n assert_eq!(&*event.finalize(), b\"data: hi\\n\\n: x\\n\\n\");\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":837,"symbol":"basic","kind":"function","lang":"rust","code":"async fn basic() {\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let stream = stream::iter(vec![\n Event::default().data(\"one\").comment(\"this is a comment\"),\n Event::default()\n .json_data(serde_json::json!({ \"foo\": \"bar\" }))\n .unwrap(),\n Event::default()\n .event(\"three\")\n .retry(Duration::from_secs(30))\n .id(\"unique-id\"),\n ])\n .map(Ok::<_, Infallible>);\n Sse::new(stream)\n }),\n );\n\n let client = TestClient::new(app);\n let mut stream = client.get(\"/\").await;\n\n assert_eq!(stream.headers()[\"content-type\"], \"text/event-stream\");\n assert_eq!(stream.headers()[\"cache-control\"], \"no-cache\");\n\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n assert_eq!(event_fields.get(\"data\").unwrap(), \"one\");\n assert_eq!(event_fields.get(\"comment\").unwrap(), \"this is a comment\");\n\n let event_fields = parse_event(&stream.chunk_text().await.unwrap())"} {"repo":"axum","file":"axum/src/response/sse.rs","line":880,"symbol":"raw_events","kind":"function","lang":"rust","code":"async fn raw_events() {\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let stream = stream::iter(vec![\n Event::raw(Bytes::from_static(b\"data: one\\n\\n\")),\n Event::raw(Bytes::from_static(b\":raw two\\n\\n\")),\n ])\n .map(Ok::<_, Infallible>);\n Sse::new(stream)\n }),\n );\n\n let client = TestClient::new(app);\n let mut stream = client.get(\"/\").await;\n\n assert_eq!(stream.headers()[\"content-type\"], \"text/event-stream\");\n assert_eq!(stream.headers()[\"cache-control\"], \"no-cache\");\n\n // Chunks are received byte-exact: no `data:` framing or extra newline is added.\n assert_eq!(stream.chunk_text().await.unwrap(), \"data: one\\n\\n\");\n assert_eq!(stream.chunk_text().await.unwrap(), \":raw two\\n\\n\");\n\n assert!(stream.chunk_text().await.is_none());\n }"} {"repo":"axum","file":"axum/src/response/sse.rs","line":907,"symbol":"keep_alive","kind":"function","lang":"rust","code":"async fn keep_alive() {\n const DELAY: Duration = Duration::from_secs(5);\n\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let stream = stream::repeat_with(|| Event::default().data(\"msg\"))\n .map(Ok::<_, Infallible>)\n .throttle(DELAY);\n\n Sse::new(stream).keep_alive(\n KeepAlive::new()\n .interval(Duration::from_secs(1))\n .text(\"keep-alive-text\"),\n )\n }),\n );\n\n let client = TestClient::new(app);\n let mut stream = client.get(\"/\").await;\n\n for _ in 0..5 {\n // first message should be an event\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n assert_eq!(event_fields.get(\"data\").unwrap(), \"msg\");\n\n // then 4 seconds of keep-alive messages\n for _ in 0..4 {\n tokio::time::sleep(Duration::from_secs(1)).await;\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n assert_eq!(event_fields.get(\"comment\").unwrap(), \"keep-alive-text\");\n "} {"repo":"axum","file":"axum/src/response/sse.rs","line":943,"symbol":"keep_alive_with_raw_events","kind":"function","lang":"rust","code":"async fn keep_alive_with_raw_events() {\n const DELAY: Duration = Duration::from_secs(5);\n\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let stream =\n stream::repeat_with(|| Event::raw(Bytes::from_static(b\"data: raw\\n\\n\")))\n .map(Ok::<_, Infallible>)\n .throttle(DELAY);\n\n Sse::new(stream).keep_alive(\n KeepAlive::new()\n .interval(Duration::from_secs(1))\n .text(\"keep-alive-text\"),\n )\n }),\n );\n\n let client = TestClient::new(app);\n let mut stream = client.get(\"/\").await;\n\n for _ in 0..5 {\n // first message should be a raw event, sent byte-exact\n assert_eq!(stream.chunk_text().await.unwrap(), \"data: raw\\n\\n\");\n\n // then 4 seconds of keep-alive messages: a raw event resets the timer just like\n // any other event\n for _ in 0..4 {\n tokio::time::sleep(Duration::from_secs(1)).await;\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n "} {"repo":"axum","file":"axum/src/response/sse.rs","line":980,"symbol":"keep_alive_ends_when_the_stream_ends","kind":"function","lang":"rust","code":"async fn keep_alive_ends_when_the_stream_ends() {\n const DELAY: Duration = Duration::from_secs(5);\n\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let stream = stream::repeat_with(|| Event::default().data(\"msg\"))\n .map(Ok::<_, Infallible>)\n .throttle(DELAY)\n .take(2);\n\n Sse::new(stream).keep_alive(\n KeepAlive::new()\n .interval(Duration::from_secs(1))\n .text(\"keep-alive-text\"),\n )\n }),\n );\n\n let client = TestClient::new(app);\n let mut stream = client.get(\"/\").await;\n\n // first message should be an event\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n assert_eq!(event_fields.get(\"data\").unwrap(), \"msg\");\n\n // then 4 seconds of keep-alive messages\n for _ in 0..4 {\n tokio::time::sleep(Duration::from_secs(1)).await;\n let event_fields = parse_event(&stream.chunk_text().await.unwrap());\n assert_eq!(event_fields.get(\"comment\").unwrap(), \"keep-alive-text\");\n "} {"repo":"axum","file":"axum/src/response/sse.rs","line":1021,"symbol":"parse_event","kind":"function","lang":"rust","code":"fn parse_event(payload: &str) -> HashMap {\n let mut fields = HashMap::new();\n\n let mut lines = payload.lines().peekable();\n while let Some(line) = lines.next() {\n if line.is_empty() {\n assert!(lines.next().is_none());\n break;\n }\n\n let (mut key, value) = line.split_once(':').unwrap();\n let value = value.trim();\n if key.is_empty() {\n key = \"comment\";\n }\n fields.insert(key.to_owned(), value.to_owned());\n }\n\n fields\n }"} {"repo":"axum","file":"axum/src/routing/into_make_service.rs","line":12,"symbol":"IntoMakeService","kind":"type","lang":"rust","doc":"A [`MakeService`] that produces axum router services. [`MakeService`]: tower::make::MakeService","code":"pub struct IntoMakeService {\n svc: S,\n}"} {"repo":"axum","file":"axum/src/routing/into_make_service.rs","line":17,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(svc: S) -> Self {\n Self { svc }\n }"} {"repo":"axum","file":"axum/src/routing/into_make_service.rs","line":31,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/into_make_service.rs","line":35,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _target: T) -> Self::Future {\n IntoMakeServiceFuture::new(ready(Ok(self.svc.clone())))\n }"} {"repo":"axum","file":"axum/src/routing/into_make_service.rs","line":51,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n\n assert_send::>();\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":9,"symbol":"MethodFilter","kind":"type","lang":"rust","doc":"A filter that matches one or more HTTP methods.","code":"pub struct MethodFilter(u16);"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":49,"symbol":"bits","kind":"function","lang":"rust","code":"const fn bits(self) -> u16 {\n let bits = self;\n bits.0\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":54,"symbol":"from_bits","kind":"function","lang":"rust","code":"const fn from_bits(bits: u16) -> Self {\n Self(bits)\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":58,"symbol":"contains","kind":"function","lang":"rust","code":"pub(crate) const fn contains(self, other: Self) -> bool {\n self.bits() & other.bits() == other.bits()\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":64,"symbol":"or","kind":"function","lang":"rust","doc":"Performs the OR operation between the [`MethodFilter`] in `self` with `other`.","code":"pub const fn or(self, other: Self) -> Self {\n Self(self.0 | other.0)\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":71,"symbol":"NoMatchingMethodFilter","kind":"type","lang":"rust","doc":"Error type used when converting a [`Method`] to a [`MethodFilter`] fails.","code":"pub struct NoMatchingMethodFilter {\n method: Method,\n}"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":77,"symbol":"method","kind":"function","lang":"rust","doc":"Get the [`Method`] that couldn't be converted to a [`MethodFilter`].","code":"pub fn method(&self) -> &Method {\n &self.method\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":83,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n write!(f, \"no `MethodFilter` for `{}`\", self.method.as_str())\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":93,"symbol":"try_from","kind":"function","lang":"rust","code":"fn try_from(m: Method) -> Result {\n match m {\n Method::CONNECT => Ok(Self::CONNECT),\n Method::DELETE => Ok(Self::DELETE),\n Method::GET => Ok(Self::GET),\n Method::HEAD => Ok(Self::HEAD),\n Method::OPTIONS => Ok(Self::OPTIONS),\n Method::PATCH => Ok(Self::PATCH),\n Method::POST => Ok(Self::POST),\n Method::PUT => Ok(Self::PUT),\n Method::TRACE => Ok(Self::TRACE),\n Method::QUERY => Ok(Self::QUERY),\n other => Err(NoMatchingMethodFilter { method: other }),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_filter.rs","line":115,"symbol":"from_http_method","kind":"function","lang":"rust","code":"fn from_http_method() {\n assert_eq!(\n MethodFilter::try_from(Method::CONNECT).unwrap(),\n MethodFilter::CONNECT\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::DELETE).unwrap(),\n MethodFilter::DELETE\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::GET).unwrap(),\n MethodFilter::GET\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::HEAD).unwrap(),\n MethodFilter::HEAD\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::OPTIONS).unwrap(),\n MethodFilter::OPTIONS\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::PATCH).unwrap(),\n MethodFilter::PATCH\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::POST).unwrap(),\n MethodFilter::POST\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::PUT).unwrap(),\n MethodFilter::PUT\n );\n\n assert_eq!(\n MethodFilter::try_from(Method::TRACE).unwrap(),\n MethodFilter::TRACE\n );\n\n assert_eq!(\n MethodFilter::try_from(Method:"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":369,"symbol":"on_service","kind":"function","lang":"rust","doc":"}); // Requests to `POST /` will go to `service`. let app = Router::new().route(\"/\", on_service(MethodFilter::POST, service)); # let _: Router = app; ```","code":"pub fn on_service(filter: MethodFilter, svc: T) -> MethodRouter\nwhere\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse + 'static,\n T::Future: Send + 'static,\n S: Clone,\n{\n MethodRouter::new().on_service(filter, svc)\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":428,"symbol":"any_service","kind":"function","lang":"rust","doc":"}); // `POST /` goes to `other_service`. All other requests go to `service` let app = Router::new().route(\"/\", any_service(service).post_service(other_service)); # let _: Router = app; ```","code":"pub fn any_service(svc: T) -> MethodRouter\nwhere\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse + 'static,\n T::Future: Send + 'static,\n S: Clone,\n{\n MethodRouter::new()\n .fallback_service(svc)\n .skip_allow_header()\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":468,"symbol":"on","kind":"function","lang":"rust","doc":"async fn handler() {} // Requests to `POST /` will go to `handler`. let app = Router::new().route(\"/\", on(MethodFilter::POST, handler)); # let _: Router = app; ```","code":"pub fn on(filter: MethodFilter, handler: H) -> MethodRouter\nwhere\n H: Handler,\n T: 'static,\n S: Clone + Send + Sync + 'static,\n{\n MethodRouter::new().on(filter, handler)\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":510,"symbol":"any","kind":"function","lang":"rust","doc":"async fn other_handler() {} // `POST /` goes to `other_handler`. All other requests go to `handler` let app = Router::new().route(\"/\", any(handler).post(other_handler)); # let _: Router = app; ```","code":"pub fn any(handler: H) -> MethodRouter\nwhere\n H: Handler,\n T: 'static,\n S: Clone + Send + Sync + 'static,\n{\n MethodRouter::new().fallback(handler).skip_allow_header()\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":549,"symbol":"MethodRouter","kind":"type","lang":"rust","doc":"// helper to check that a value implements `Service` fn assert_service(service: S) where S: Service, {} ```","code":"pub struct MethodRouter {\n get: MethodEndpoint,\n head: MethodEndpoint,\n delete: MethodEndpoint,\n options: MethodEndpoint,\n patch: MethodEndpoint,\n post: MethodEndpoint,\n put: MethodEndpoint,\n trace: MethodEndpoint,\n connect: MethodEndpoint,\n query: MethodEndpoint,\n fallback: Fallback,\n allow_header: AllowHeader,\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":565,"symbol":"AllowHeader","kind":"type","lang":"rust","code":"enum AllowHeader {\n /// No `Allow` header value has been built-up yet. This is the default state\n None,\n /// Don't set an `Allow` header. This is used when `any` or `any_service` are called.\n Skip,\n /// The current value of the `Allow` header.\n Bytes(BytesMut),\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":575,"symbol":"merge","kind":"function","lang":"rust","code":"fn merge(self, other: Self) -> Self {\n match (self, other) {\n (Self::Skip, _) | (_, Self::Skip) => Self::Skip,\n (Self::None, Self::None) => Self::None,\n (Self::None, Self::Bytes(pick)) | (Self::Bytes(pick), Self::None) => Self::Bytes(pick),\n (mut this @ Self::Bytes(_), Self::Bytes(b)) => {\n match std::str::from_utf8(&b) {\n Ok(methods) => {\n for method in methods.split(',') {\n append_allow_header(&mut this, method);\n }\n }\n Err(_) => {\n #[cfg(debug_assertions)]\n panic!(\"`allow_header` contained invalid utf-8. This should never happen\")\n }\n }\n this\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":599,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"MethodRouter\")\n .field(\"get\", &self.get)\n .field(\"head\", &self.head)\n .field(\"delete\", &self.delete)\n .field(\"options\", &self.options)\n .field(\"patch\", &self.patch)\n .field(\"post\", &self.post)\n .field(\"put\", &self.put)\n .field(\"trace\", &self.trace)\n .field(\"connect\", &self.connect)\n .field(\"query\", &self.query)\n .field(\"fallback\", &self.fallback)\n .field(\"allow_header\", &self.allow_header)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":643,"symbol":"on","kind":"function","lang":"rust","doc":"// Requests to `GET /` will go to `handler` and `DELETE /` will go to // `other_handler` let app = Router::new().route(\"/\", get(handler).on(MethodFilter::DELETE, other_handler)); # let _: Router = app; ```","code":"pub fn on(self, filter: MethodFilter, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n S: Send + Sync + 'static,\n {\n self.on_endpoint(\n filter,\n &MethodEndpoint::BoxedHandler(BoxedIntoRoute::from_handler(handler)),\n )\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":667,"symbol":"fallback","kind":"function","lang":"rust","doc":"Add a fallback [`Handler`] to the router.","code":"pub fn fallback(mut self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n S: Send + Sync + 'static,\n {\n self.fallback = Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler));\n self\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":687,"symbol":"method_filter","kind":"function","lang":"rust","doc":"always creates an HTTP response) based on which HTTP method was used. However, the information which methods have the default behavior of returning HTTP 405 is stored, and can be queried with this method. Returns `None` if the `MethodRouter` was constructed with [`any`] or has had a [`fallback`][Self::fallback] set.","code":"pub fn method_filter(&self) -> Option {\n let Self {\n get,\n head,\n delete,\n options,\n patch,\n post,\n put,\n trace,\n connect,\n query,\n fallback,\n allow_header: _,\n } = self;\n\n if !fallback.is_default() {\n return None;\n }\n\n let filter = [\n (get, MethodFilter::GET),\n (head, MethodFilter::HEAD),\n (delete, MethodFilter::DELETE),\n (options, MethodFilter::OPTIONS),\n (patch, MethodFilter::PATCH),\n (post, MethodFilter::POST),\n (put, MethodFilter::PUT),\n (trace, MethodFilter::TRACE),\n (connect, MethodFilter::CONNECT),\n (query, MethodFilter::QUERY),\n ]\n .into_iter()\n .filter_map(|(ep, f)| ep.is_some().then_some(f))\n .reduce(MethodFilter::or)\n .expect(\"can't create a MethodRouter with all-default handlers\");\n\n Some(filter)\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":728,"symbol":"default_fallback","kind":"function","lang":"rust","doc":"Add a fallback [`Handler`] if no custom one has been provided.","code":"pub(crate) fn default_fallback(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n S: Send + Sync + 'static,\n {\n match self.fallback {\n Fallback::Default(_) => self.fallback(handler),\n _ => self,\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":770,"symbol":"into_make_service","kind":"function","lang":"rust","doc":"let listener = tokio::net::TcpListener::bind(\"0.0.0.0:3000\").await.unwrap(); axum::serve(listener, router.into_make_service()).await; # }; ``` [`MakeService`]: tower::make::MakeService","code":"pub fn into_make_service(self) -> IntoMakeService {\n IntoMakeService::new(self.with_state(()))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":804,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","doc":"axum::serve(listener, router.into_make_service()).await; # }; ``` [`MakeService`]: tower::make::MakeService [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info","code":"pub fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo {\n IntoMakeServiceWithConnectInfo::new(self.with_state(()))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":815,"symbol":"new","kind":"function","lang":"rust","doc":"Create a default `MethodRouter` that will respond with `405 Method Not Allowed` to all requests.","code":"pub fn new() -> Self {\n let fallback = Route::new(service_fn(|_: Request| async {\n Ok(StatusCode::METHOD_NOT_ALLOWED)\n }));\n\n Self {\n get: MethodEndpoint::None,\n head: MethodEndpoint::None,\n delete: MethodEndpoint::None,\n options: MethodEndpoint::None,\n patch: MethodEndpoint::None,\n post: MethodEndpoint::None,\n put: MethodEndpoint::None,\n trace: MethodEndpoint::None,\n connect: MethodEndpoint::None,\n query: MethodEndpoint::None,\n allow_header: AllowHeader::None,\n fallback: Fallback::Default(fallback),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":837,"symbol":"with_state","kind":"function","lang":"rust","doc":"Provide the state for the router.","code":"pub fn with_state(self, state: S) -> MethodRouter {\n MethodRouter {\n get: self.get.with_state(&state),\n head: self.head.with_state(&state),\n delete: self.delete.with_state(&state),\n options: self.options.with_state(&state),\n patch: self.patch.with_state(&state),\n post: self.post.with_state(&state),\n put: self.put.with_state(&state),\n trace: self.trace.with_state(&state),\n connect: self.connect.with_state(&state),\n query: self.query.with_state(&state),\n allow_header: self.allow_header,\n fallback: self.fallback.with_state(state),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":878,"symbol":"on_service","kind":"function","lang":"rust","doc":"}); // Requests to `DELETE /` will go to `service` let app = Router::new().route(\"/\", on_service(MethodFilter::DELETE, service)); # let _: Router = app; ```","code":"pub fn on_service(self, filter: MethodFilter, svc: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse + 'static,\n T::Future: Send + 'static,\n {\n self.on_endpoint(filter, &MethodEndpoint::Route(Route::new(svc)))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":888,"symbol":"on_endpoint","kind":"function","lang":"rust","code":"fn on_endpoint(mut self, filter: MethodFilter, endpoint: &MethodEndpoint) -> Self {\n // written as a separate function to generate less IR\n #[track_caller]\n fn set_endpoint(\n method_name: &str,\n out: &mut MethodEndpoint,\n endpoint: &MethodEndpoint,\n endpoint_filter: MethodFilter,\n filter: MethodFilter,\n allow_header: &mut AllowHeader,\n methods: &[&'static str],\n ) where\n MethodEndpoint: Clone,\n S: Clone,\n {\n if endpoint_filter.contains(filter) {\n if out.is_some() {\n panic!(\n \"Overlapping method route. Cannot add two method routes that both handle \\\n `{method_name}`\",\n );\n }\n *out = endpoint.clone();\n for method in methods {\n append_allow_header(allow_header, method);\n }\n }\n }\n\n set_endpoint(\n \"GET\",\n &mut self.get,\n endpoint,\n filter,\n MethodFilter::GET,\n "} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":891,"symbol":"set_endpoint","kind":"function","lang":"rust","doc":"written as a separate function to generate less IR","code":"fn set_endpoint(\n method_name: &str,\n out: &mut MethodEndpoint,\n endpoint: &MethodEndpoint,\n endpoint_filter: MethodFilter,\n filter: MethodFilter,\n allow_header: &mut AllowHeader,\n methods: &[&'static str],\n ) where\n MethodEndpoint: Clone,\n S: Clone,\n {\n if endpoint_filter.contains(filter) {\n if out.is_some() {\n panic!(\n \"Overlapping method route. Cannot add two method routes that both handle \\\n `{method_name}`\",\n );\n }\n *out = endpoint.clone();\n for method in methods {\n append_allow_header(allow_header, method);\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1032,"symbol":"fallback_service","kind":"function","lang":"rust","code":"pub fn fallback_service(mut self, svc: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse + 'static,\n T::Future: Send + 'static,\n {\n self.fallback = Fallback::Service(Route::new(svc));\n self\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1043,"symbol":"layer","kind":"function","lang":"rust","code":"pub fn layer(self, layer: L) -> MethodRouter\n where\n L: Layer> + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n E: 'static,\n S: 'static,\n NewError: 'static,\n {\n let layer_fn = move |route: Route| route.layer(layer.clone());\n\n MethodRouter {\n get: self.get.map(layer_fn.clone()),\n head: self.head.map(layer_fn.clone()),\n delete: self.delete.map(layer_fn.clone()),\n options: self.options.map(layer_fn.clone()),\n patch: self.patch.map(layer_fn.clone()),\n post: self.post.map(layer_fn.clone()),\n put: self.put.map(layer_fn.clone()),\n trace: self.trace.map(layer_fn.clone()),\n connect: self.connect.map(layer_fn.clone()),\n query: self.query.map(layer_fn.clone()),\n fallback: self.fallback.map(layer_fn),\n allow_head"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1074,"symbol":"route_layer","kind":"function","lang":"rust","code":"pub fn route_layer(mut self, layer: L) -> Self\n where\n L: Layer> + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Future: Send + 'static,\n E: 'static,\n S: 'static,\n {\n if self.get.is_none()\n && self.head.is_none()\n && self.delete.is_none()\n && self.options.is_none()\n && self.patch.is_none()\n && self.post.is_none()\n && self.put.is_none()\n && self.trace.is_none()\n && self.connect.is_none()\n && self.query.is_none()\n {\n panic!(\n \"Adding a route_layer before any routes is a no-op. \\\n Add the routes you want the layer to apply to first.\"\n );\n }\n\n let layer_fn = move |svc| Route::new(layer.layer(svc));\n\n self.get = self.get.map(layer_fn.clone());\n self.head = self.head.map(layer_fn.clone());\n self.delete = self.delete.map(layer_fn.clone());\n self.options = self.optio"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1116,"symbol":"merge_for_path","kind":"function","lang":"rust","code":"pub(crate) fn merge_for_path(\n mut self,\n path: Option<&str>,\n other: Self,\n ) -> Result> {\n // written using inner functions to generate less IR\n fn merge_inner(\n path: Option<&str>,\n name: &str,\n first: MethodEndpoint,\n second: MethodEndpoint,\n ) -> Result, Cow<'static, str>> {\n match (first, second) {\n (MethodEndpoint::None, MethodEndpoint::None) => Ok(MethodEndpoint::None),\n (pick, MethodEndpoint::None) | (MethodEndpoint::None, pick) => Ok(pick),\n _ => {\n if let Some(path) = path {\n Err(format!(\n \"Overlapping method route. Handler for `{name} {path}` already exists\"\n )\n .into())\n } else {\n Err(format!(\n \"Overlapping method route. Cannot merge two method routes that both \\\n define `{name}`\"\n )\n .into())\n "} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1122,"symbol":"merge_inner","kind":"function","lang":"rust","doc":"written using inner functions to generate less IR","code":"fn merge_inner(\n path: Option<&str>,\n name: &str,\n first: MethodEndpoint,\n second: MethodEndpoint,\n ) -> Result, Cow<'static, str>> {\n match (first, second) {\n (MethodEndpoint::None, MethodEndpoint::None) => Ok(MethodEndpoint::None),\n (pick, MethodEndpoint::None) | (MethodEndpoint::None, pick) => Ok(pick),\n _ => {\n if let Some(path) = path {\n Err(format!(\n \"Overlapping method route. Handler for `{name} {path}` already exists\"\n )\n .into())\n } else {\n Err(format!(\n \"Overlapping method route. Cannot merge two method routes that both \\\n define `{name}`\"\n )\n .into())\n }\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1171,"symbol":"merge","kind":"function","lang":"rust","code":"pub fn merge(self, other: Self) -> Self {\n match self.merge_for_path(None, other) {\n Ok(t) => t,\n // not using unwrap or unwrap_or_else to get a clean panic message + the right location\n Err(e) => panic!(\"{e}\"),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1182,"symbol":"handle_error","kind":"function","lang":"rust","doc":"Apply a [`HandleErrorLayer`]. This is a convenience method for doing `self.layer(HandleErrorLayer::new(f))`.","code":"pub fn handle_error(self, f: F) -> MethodRouter\n where\n F: Clone + Send + Sync + 'static,\n HandleError, F, T>: Service,\n , F, T> as Service>::Future: Send,\n , F, T> as Service>::Response: IntoResponse + Send,\n T: 'static,\n E: 'static,\n S: 'static,\n {\n self.layer(HandleErrorLayer::new(f))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1195,"symbol":"skip_allow_header","kind":"function","lang":"rust","code":"fn skip_allow_header(mut self) -> Self {\n self.allow_header = AllowHeader::Skip;\n self\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1200,"symbol":"call_with_state","kind":"function","lang":"rust","code":"pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture {\n macro_rules! call {\n (\n $req:expr,\n $method_variant:ident,\n $svc:expr\n ) => {\n if *req.method() == Method::$method_variant {\n match $svc {\n MethodEndpoint::None => {}\n MethodEndpoint::Route(route) => {\n return route.clone().oneshot_inner_owned($req);\n }\n MethodEndpoint::BoxedHandler(handler) => {\n let route = handler.clone().into_route(state);\n return route.oneshot_inner_owned($req);\n }\n }\n }\n };\n }\n\n // written with a pattern match like this to ensure we call all routes\n let Self {\n get,\n head,\n delete,\n options,\n patch,\n post,\n put,\n trace,\n connect,\n query,\n fallback,\n allow_header,\n } = self;\n\n "} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1260,"symbol":"append_allow_header","kind":"function","lang":"rust","code":"fn append_allow_header(allow_header: &mut AllowHeader, method: &str) {\n match allow_header {\n AllowHeader::None => {\n *allow_header = AllowHeader::Bytes(BytesMut::from(method));\n }\n AllowHeader::Skip => {}\n AllowHeader::Bytes(allow_header) => {\n if let Ok(s) = std::str::from_utf8(allow_header) {\n if !s.contains(method) {\n allow_header.extend_from_slice(b\",\");\n allow_header.extend_from_slice(method.as_bytes());\n }\n } else {\n #[cfg(debug_assertions)]\n panic!(\"`allow_header` contained invalid utf-8. This should never happen\")\n }\n }\n }\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1281,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n get: self.get.clone(),\n head: self.head.clone(),\n delete: self.delete.clone(),\n options: self.options.clone(),\n patch: self.patch.clone(),\n post: self.post.clone(),\n put: self.put.clone(),\n trace: self.trace.clone(),\n connect: self.connect.clone(),\n query: self.query.clone(),\n fallback: self.fallback.clone(),\n allow_header: self.allow_header.clone(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1303,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self::new()\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1308,"symbol":"MethodEndpoint","kind":"type","lang":"rust","code":"enum MethodEndpoint {\n None,\n Route(Route),\n BoxedHandler(BoxedIntoRoute),\n}"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1318,"symbol":"is_some","kind":"function","lang":"rust","code":"fn is_some(&self) -> bool {\n matches!(self, Self::Route(_) | Self::BoxedHandler(_))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1322,"symbol":"is_none","kind":"function","lang":"rust","code":"fn is_none(&self) -> bool {\n matches!(self, Self::None)\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1326,"symbol":"map","kind":"function","lang":"rust","code":"fn map(self, f: F) -> MethodEndpoint\n where\n S: 'static,\n E: 'static,\n F: FnOnce(Route) -> Route + Clone + Send + Sync + 'static,\n E2: 'static,\n {\n match self {\n Self::None => MethodEndpoint::None,\n Self::Route(route) => MethodEndpoint::Route(f(route)),\n Self::BoxedHandler(handler) => MethodEndpoint::BoxedHandler(handler.map(f)),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1340,"symbol":"with_state","kind":"function","lang":"rust","code":"fn with_state(self, state: &S) -> MethodEndpoint {\n match self {\n Self::None => MethodEndpoint::None,\n Self::Route(route) => MethodEndpoint::Route(route),\n Self::BoxedHandler(handler) => MethodEndpoint::Route(handler.into_route(state.clone())),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1350,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n match self {\n Self::None => Self::None,\n Self::Route(inner) => Self::Route(inner.clone()),\n Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1360,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::None => f.debug_tuple(\"None\").finish(),\n Self::Route(inner) => inner.fmt(f),\n Self::BoxedHandler(_) => f.debug_tuple(\"BoxedHandler\").finish(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1379,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1384,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n let req = req.map(Body::new);\n self.call_with_state(req, ())\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1397,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, req: Request, state: S) -> Self::Future {\n InfallibleRouteFuture::new(self.call_with_state(req, state))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1415,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1419,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {\n std::future::ready(Ok(self.clone().with_state(())))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1438,"symbol":"method_not_allowed_by_default","kind":"function","lang":"rust","code":"async fn method_not_allowed_by_default() {\n let mut svc = MethodRouter::new();\n let (status, _, body) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert!(body.is_empty());\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1446,"symbol":"get_service_fn","kind":"function","lang":"rust","code":"async fn get_service_fn() {\n async fn handle(_req: Request) -> Result, Infallible> {\n Ok(Response::new(Body::from(\"ok\")))\n }\n\n let mut svc = get_service(service_fn(handle));\n\n let (status, _, body) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n assert_eq!(body, \"ok\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1447,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(_req: Request) -> Result, Infallible> {\n Ok(Response::new(Body::from(\"ok\")))\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1459,"symbol":"get_handler","kind":"function","lang":"rust","code":"async fn get_handler() {\n let mut svc = MethodRouter::new().get(ok);\n let (status, _, body) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n assert_eq!(body, \"ok\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1467,"symbol":"get_accepts_head","kind":"function","lang":"rust","code":"async fn get_accepts_head() {\n let mut svc = MethodRouter::new().get(ok);\n let (status, _, body) = call(Method::HEAD, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n assert!(body.is_empty());\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1475,"symbol":"head_takes_precedence_over_get","kind":"function","lang":"rust","code":"async fn head_takes_precedence_over_get() {\n let mut svc = MethodRouter::new().head(created).get(ok);\n let (status, _, body) = call(Method::HEAD, &mut svc).await;\n assert_eq!(status, StatusCode::CREATED);\n assert!(body.is_empty());\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1483,"symbol":"merge","kind":"function","lang":"rust","code":"async fn merge() {\n let mut svc = get(ok).merge(post(ok)).merge(connect(ok));\n\n let (status, _, _) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n\n let (status, _, _) = call(Method::POST, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n\n let (status, _, _) = call(Method::CONNECT, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1498,"symbol":"layer","kind":"function","lang":"rust","code":"async fn layer() {\n let mut svc = MethodRouter::new()\n .get(|| async { std::future::pending::<()>().await })\n .layer(ValidateRequestHeaderLayer::bearer(\"password\"));\n\n // method with route\n let (status, _, _) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::UNAUTHORIZED);\n\n // method without route\n let (status, _, _) = call(Method::DELETE, &mut svc).await;\n assert_eq!(status, StatusCode::UNAUTHORIZED);\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1514,"symbol":"route_layer","kind":"function","lang":"rust","code":"async fn route_layer() {\n let mut svc = MethodRouter::new()\n .get(|| async { std::future::pending::<()>().await })\n .route_layer(ValidateRequestHeaderLayer::bearer(\"password\"));\n\n // method with route\n let (status, _, _) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::UNAUTHORIZED);\n\n // method without route\n let (status, _, _) = call(Method::DELETE, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1529,"symbol":"building_complex_router","kind":"function","lang":"rust","code":"async fn building_complex_router() {\n let app = crate::Router::new().route(\n \"/\",\n // use the all the things 💣️\n get(ok)\n .post(ok)\n .route_layer(ValidateRequestHeaderLayer::bearer(\"password\"))\n .merge(delete_service(ServeDir::new(\".\")))\n .fallback(|| async { StatusCode::NOT_FOUND })\n .put(ok)\n .layer(TimeoutLayer::with_status_code(\n StatusCode::REQUEST_TIMEOUT,\n Duration::from_secs(10),\n )),\n );\n\n let listener = tokio::net::TcpListener::bind(\"0.0.0.0:0\").await.unwrap();\n crate::serve(listener, app).await;\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1550,"symbol":"sets_allow_header","kind":"function","lang":"rust","code":"async fn sets_allow_header() {\n let mut svc = MethodRouter::new().put(ok).patch(ok);\n let (status, headers, _) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"PUT,PATCH\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1558,"symbol":"sets_allow_header_get_head","kind":"function","lang":"rust","code":"async fn sets_allow_header_get_head() {\n let mut svc = MethodRouter::new().get(ok).head(ok);\n let (status, headers, _) = call(Method::PUT, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"GET,HEAD\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1566,"symbol":"empty_allow_header_by_default","kind":"function","lang":"rust","code":"async fn empty_allow_header_by_default() {\n let mut svc = MethodRouter::new();\n let (status, headers, _) = call(Method::PATCH, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1574,"symbol":"allow_header_when_merging","kind":"function","lang":"rust","code":"async fn allow_header_when_merging() {\n let a = put(ok).patch(ok);\n let b = get(ok).head(ok);\n let mut svc = a.merge(b);\n\n let (status, headers, _) = call(Method::DELETE, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"PUT,PATCH,GET,HEAD\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1585,"symbol":"allow_header_merging_get_into_head","kind":"function","lang":"rust","code":"async fn allow_header_merging_get_into_head() {\n let a = get(ok);\n let b = head(created);\n let mut svc = a.merge(b);\n\n let (status, headers, _) = call(Method::DELETE, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"GET,HEAD\");\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1596,"symbol":"allow_header_any","kind":"function","lang":"rust","code":"async fn allow_header_any() {\n let mut svc = any(ok);\n\n let (status, headers, _) = call(Method::GET, &mut svc).await;\n assert_eq!(status, StatusCode::OK);\n assert!(!headers.contains_key(ALLOW));\n }"} {"repo":"axum","file":"axum/src/routing/method_routing.rs","line":1605,"symbol":"allow_header_with_fallback","kind":"function","lang":"rust","code":"async fn allow_header_with_fallback() {\n let mut svc = MethodRouter::new()\n .get(ok)\n .fallback(|| async { (StatusCode::METHOD_NOT_ALLOWED, \"Method not allowed\") });\n\n let (status, headers, _) = call(Method::DELETE, &mut svc).await;\n assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(headers[ALLOW], \"GET,HEAD\");\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":63,"symbol":"take_route_or_internal_error","kind":"function","lang":"rust","code":"fn take_route_or_internal_error(service: &mut Option) -> Route {\n service.take().unwrap_or_else(|| {\n if cfg!(debug_assertions) {\n panic!(\"{TAKE_ONCE_ROUTE_PANIC_MSG}\");\n }\n\n Route::new(service_fn(|_req: Request| async move {\n Ok::<_, Infallible>(http::StatusCode::INTERNAL_SERVER_ERROR.into_response())\n }))\n })\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":76,"symbol":"RouteId","kind":"type","lang":"rust","code":"pub(crate) struct RouteId(usize);"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":86,"symbol":"Router","kind":"type","lang":"rust","doc":"`Router` means a router that is _missing_ a state of type `S` to be able to handle requests. Thus, only `Router<()>` (i.e. without missing state) can be passed to [`serve`]. See [`Router::with_state`] for more details. [`serve`]: crate::serve()","code":"pub struct Router {\n inner: Arc>,\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":91,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n inner: Arc::clone(&self.inner),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":98,"symbol":"RouterInner","kind":"type","lang":"rust","code":"struct RouterInner {\n path_router: PathRouter,\n default_fallback: bool,\n catch_all_fallback: Fallback,\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":108,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self::new()\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":114,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Router\")\n .field(\"path_router\", &self.inner.path_router)\n .field(\"default_fallback\", &self.inner.default_fallback)\n .field(\"catch_all_fallback\", &self.inner.catch_all_fallback)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":162,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `Router`. Unless you add additional routes this will respond with `404 Not Found` to all requests.","code":"pub fn new() -> Self {\n Self {\n inner: Arc::new(RouterInner {\n path_router: Default::default(),\n default_fallback: true,\n catch_all_fallback: Fallback::Default(Route::new(NotFound)),\n }),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":172,"symbol":"into_inner","kind":"function","lang":"rust","code":"fn into_inner(self) -> RouterInner {\n match Arc::try_unwrap(self.inner) {\n Ok(inner) => inner,\n Err(arc) => RouterInner {\n path_router: arc.path_router.clone(),\n default_fallback: arc.default_fallback,\n catch_all_fallback: arc.catch_all_fallback.clone(),\n },\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":185,"symbol":"route","kind":"function","lang":"rust","code":"pub fn route(self, path: &str, method_router: MethodRouter) -> Self {\n tap_inner!(self, mut this => {\n panic_on_err!(this.path_router.route(path, method_router));\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":192,"symbol":"route_service","kind":"function","lang":"rust","code":"pub fn route_service(self, path: &str, service: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n {\n let Err(service) = try_downcast::(service) else {\n panic!(\n \"Invalid route: `Router::route_service` cannot be used with `Router`s. \\\n Use `Router::nest` instead\"\n );\n };\n\n tap_inner!(self, mut this => {\n panic_on_err!(this.path_router.route_service(path, service));\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":213,"symbol":"nest","kind":"function","lang":"rust","code":"pub fn nest(self, path: &str, router: Self) -> Self {\n if path.is_empty() || path == \"/\" {\n panic!(\"Nesting at the root is no longer supported. Use merge instead.\");\n }\n\n let RouterInner {\n path_router,\n default_fallback: _,\n // we don't need to inherit the catch-all fallback. It is only used for CONNECT\n // requests with an empty path. If we were to inherit the catch-all fallback\n // it would end up matching `/{path}/*` which doesn't match empty paths.\n catch_all_fallback: _,\n } = router.into_inner();\n\n tap_inner!(self, mut this => {\n panic_on_err!(this.path_router.nest(path, path_router));\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":234,"symbol":"nest_service","kind":"function","lang":"rust","doc":"Like [`nest`](Self::nest), but accepts an arbitrary `Service`.","code":"pub fn nest_service(self, path: &str, service: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n {\n if path.is_empty() || path == \"/\" {\n panic!(\"Nesting at the root is no longer supported. Use fallback_service instead.\");\n }\n\n tap_inner!(self, mut this => {\n panic_on_err!(this.path_router.nest_service(path, service));\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":251,"symbol":"merge","kind":"function","lang":"rust","code":"pub fn merge(self, other: R) -> Self\n where\n R: Into,\n {\n let other: Self = other.into();\n let RouterInner {\n path_router,\n default_fallback,\n catch_all_fallback,\n } = other.into_inner();\n\n map_inner!(self, mut this => {\n match (this.default_fallback, default_fallback) {\n // other has a default fallback\n // use the one from other\n (_, true) => {}\n // this has default fallback, other has a custom fallback\n (true, false) => {\n this.default_fallback = false;\n }\n // both have a custom fallback, not allowed\n (false, false) => {\n panic!(\"Cannot merge two `Router`s that both have a fallback\")\n }\n };\n\n panic_on_err!(this.path_router.merge(path_router));\n\n this.catch_all_fallback = this\n .catch_all_fallback\n .merge(catch_all_fallback)\n .unwrap_or_else(|| panic!(\"Cannot merge two `Router`s that both have a fallback\"));\n\n this\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":289,"symbol":"layer","kind":"function","lang":"rust","code":"pub fn layer(self, layer: L) -> Self\n where\n L: Layer + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n {\n map_inner!(self, this => RouterInner {\n path_router: this.path_router.layer(layer.clone()),\n default_fallback: this.default_fallback,\n catch_all_fallback: this.catch_all_fallback.map(|route| route.layer(layer)),\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":306,"symbol":"route_layer","kind":"function","lang":"rust","code":"pub fn route_layer(self, layer: L) -> Self\n where\n L: Layer + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n {\n map_inner!(self, this => RouterInner {\n path_router: this.path_router.route_layer(layer),\n default_fallback: this.default_fallback,\n catch_all_fallback: this.catch_all_fallback,\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":323,"symbol":"has_routes","kind":"function","lang":"rust","doc":"True if the router currently has at least one route added.","code":"pub fn has_routes(&self) -> bool {\n self.inner.path_router.has_routes()\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":329,"symbol":"fallback","kind":"function","lang":"rust","code":"pub fn fallback(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n tap_inner!(self, mut this => {\n this.catch_all_fallback =\n Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler.clone()));\n })\n .fallback_endpoint(Endpoint::MethodRouter(any(handler)))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":344,"symbol":"fallback_service","kind":"function","lang":"rust","doc":"Add a fallback [`Service`] to the router. See [`Router::fallback`] for more details.","code":"pub fn fallback_service(self, service: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n {\n let route = Route::new(service);\n tap_inner!(self, mut this => {\n this.catch_all_fallback = Fallback::Service(route.clone());\n })\n .fallback_endpoint(Endpoint::Route(route))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":359,"symbol":"method_not_allowed_fallback","kind":"function","lang":"rust","code":"pub fn method_not_allowed_fallback(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n tap_inner!(self, mut this => {\n this.path_router\n .method_not_allowed_fallback(&handler);\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":377,"symbol":"reset_fallback","kind":"function","lang":"rust","doc":"Useful to merge two routers with fallbacks, as [`merge`] doesn't allow both routers to have an explicit fallback. Use this method to remove the one you want to discard before merging. [`merge`]: Self::merge","code":"pub fn reset_fallback(self) -> Self {\n tap_inner!(self, mut this => {\n this.default_fallback = true;\n this.catch_all_fallback = Fallback::Default(Route::new(NotFound));\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":384,"symbol":"fallback_endpoint","kind":"function","lang":"rust","code":"fn fallback_endpoint(self, endpoint: Endpoint) -> Self {\n // TODO make this better.\n // We need the returned `Service` to be `Clone` and the function inside `service_fn` to be\n // `FnMut` so instead of just using the owned service, we do this trick with `Option`. We\n // know this will be called just once so it's fine. We're doing that so that we avoid one\n // clone inside `oneshot_inner` so that the `Router` and subsequently the `State` is not\n // cloned too much.\n tap_inner!(self, mut this => {\n _ = this.path_router.route_endpoint(\n \"/\",\n endpoint.clone().layer(\n layer_fn(\n |service: Route| {\n let mut service = Some(service);\n service_fn(\n #[cfg_attr(not(feature = \"matched-path\"), allow(unused_mut))]\n move |mut request: Request| {\n #[cfg(feature = \"matched-path\")]\n request.extensions_mut().remove::();\n let route = take"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":437,"symbol":"with_state","kind":"function","lang":"rust","code":"pub fn with_state(self, state: S) -> Router {\n map_inner!(self, this => RouterInner {\n path_router: this.path_router.with_state(state.clone()),\n default_fallback: this.default_fallback,\n catch_all_fallback: this.catch_all_fallback.with_state(state),\n })\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":445,"symbol":"call_with_state","kind":"function","lang":"rust","code":"pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture {\n let (req, state) = match self.inner.path_router.call_with_state(req, state) {\n Ok(future) => return future,\n Err((req, state)) => (req, state),\n };\n\n self.inner\n .catch_all_fallback\n .clone()\n .call_with_state(req, state)\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":510,"symbol":"as_service","kind":"function","lang":"rust","doc":"# Ok(()) # } ``` This is mainly used when calling `Router` in tests. It shouldn't be necessary when running the `Router` normally via [`Router::into_make_service`].","code":"pub fn as_service(&mut self) -> RouterAsService<'_, B, S> {\n RouterAsService {\n router: self,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":523,"symbol":"into_service","kind":"function","lang":"rust","doc":"Convert the router into an owned [`Service`] with a fixed request body type, to aid type inference. This is the same as [`Router::as_service`] instead it returns an owned [`Service`]. See that method for more details.","code":"pub fn into_service(self) -> RouterIntoService {\n RouterIntoService {\n router: self,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":551,"symbol":"into_make_service","kind":"function","lang":"rust","doc":"let listener = tokio::net::TcpListener::bind(\"0.0.0.0:3000\").await.unwrap(); axum::serve(listener, app).await; # }; ``` [`MakeService`]: tower::make::MakeService","code":"pub fn into_make_service(self) -> IntoMakeService {\n // call `Router::with_state` such that everything is turned into `Route` eagerly\n // rather than doing that per request\n IntoMakeService::new(self.with_state(()))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":560,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","code":"pub fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo {\n // call `Router::with_state` such that everything is turned into `Route` eagerly\n // rather than doing that per request\n IntoMakeServiceWithConnectInfo::new(self.with_state(()))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":580,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":584,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {\n // call `Router::with_state` such that everything is turned into `Route` eagerly\n // rather than doing that per request\n std::future::ready(Ok(self.clone().with_state(())))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":602,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":607,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n let req = req.map(Body::new);\n self.call_with_state(req, ())\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":616,"symbol":"RouterAsService","kind":"type","lang":"rust","doc":"A [`Router`] converted into a borrowed [`Service`] with a fixed body type. See [`Router::as_service`] for more details.","code":"pub struct RouterAsService<'a, B, S = ()> {\n router: &'a mut Router,\n _marker: PhantomData,\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":631,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n >>::poll_ready(self.router, cx)\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":636,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n self.router.call(req)\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":645,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"RouterAsService\")\n .field(\"router\", &self.router)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":655,"symbol":"RouterIntoService","kind":"type","lang":"rust","doc":"A [`Router`] converted into an owned [`Service`] with a fixed body type. See [`Router::into_service`] for more details.","code":"pub struct RouterIntoService {\n router: Router,\n _marker: PhantomData,\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":664,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n router: self.router.clone(),\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":682,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n >>::poll_ready(&mut self.router, cx)\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":687,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n self.router.call(req)\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":696,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"RouterIntoService\")\n .field(\"router\", &self.router)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":703,"symbol":"Fallback","kind":"type","lang":"rust","code":"enum Fallback {\n Default(Route),\n Service(Route),\n BoxedHandler(BoxedIntoRoute),\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":713,"symbol":"merge","kind":"function","lang":"rust","code":"fn merge(self, other: Self) -> Option {\n match (self, other) {\n // If either are `Default`, return the opposite one.\n (Self::Default(_), pick) | (pick, Self::Default(_)) => Some(pick),\n // Otherwise, return None\n _ => None,\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":722,"symbol":"map","kind":"function","lang":"rust","code":"fn map(self, f: F) -> Fallback\n where\n S: 'static,\n E: 'static,\n F: FnOnce(Route) -> Route + Clone + Send + Sync + 'static,\n E2: 'static,\n {\n match self {\n Self::Default(route) => Fallback::Default(f(route)),\n Self::Service(route) => Fallback::Service(f(route)),\n Self::BoxedHandler(handler) => Fallback::BoxedHandler(handler.map(f)),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":736,"symbol":"with_state","kind":"function","lang":"rust","code":"fn with_state(self, state: S) -> Fallback {\n match self {\n Self::Default(route) => Fallback::Default(route),\n Self::Service(route) => Fallback::Service(route),\n Self::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":744,"symbol":"call_with_state","kind":"function","lang":"rust","code":"fn call_with_state(self, req: Request, state: S) -> RouteFuture {\n match self {\n Self::Default(route) | Self::Service(route) => route.oneshot_inner_owned(req),\n Self::BoxedHandler(handler) => {\n let route = handler.into_route(state);\n route.oneshot_inner_owned(req)\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":754,"symbol":"is_default","kind":"function","lang":"rust","code":"fn is_default(&self) -> bool {\n matches!(self, Self::Default(..))\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":760,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n match self {\n Self::Default(inner) => Self::Default(inner.clone()),\n Self::Service(inner) => Self::Service(inner.clone()),\n Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":770,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::Default(inner) => f.debug_tuple(\"Default\").field(inner).finish(),\n Self::Service(inner) => f.debug_tuple(\"Service\").field(inner).finish(),\n Self::BoxedHandler(_) => f.debug_tuple(\"BoxedHandler\").finish(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":780,"symbol":"Endpoint","kind":"type","lang":"rust","code":"enum Endpoint {\n MethodRouter(MethodRouter),\n Route(Route),\n}"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":789,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(self, layer: L) -> Self\n where\n L: Layer + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n {\n match self {\n Self::MethodRouter(method_router) => Self::MethodRouter(method_router.layer(layer)),\n Self::Route(route) => Self::Route(route.layer(layer)),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":805,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n match self {\n Self::MethodRouter(inner) => Self::MethodRouter(inner.clone()),\n Self::Route(inner) => Self::Route(inner.clone()),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":814,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MethodRouter(method_router) => {\n f.debug_tuple(\"MethodRouter\").field(method_router).finish()\n }\n Self::Route(route) => f.debug_tuple(\"Route\").field(route).finish(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/mod.rs","line":825,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n assert_send::>();\n assert_sync::>();\n assert_send::>();\n assert_sync::>();\n assert_send::>();\n assert_sync::>();\n}"} {"repo":"axum","file":"axum/src/routing/not_found.rs","line":16,"symbol":"NotFound","kind":"type","lang":"rust","doc":"A [`Service`] that responds with `404 Not Found` to all requests. This is used as the bottom service in a method router. You shouldn't have to use it manually.","code":"pub(super) struct NotFound;"} {"repo":"axum","file":"axum/src/routing/not_found.rs","line":27,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/not_found.rs","line":31,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _req: Request) -> Self::Future {\n ready(Ok(StatusCode::NOT_FOUND.into_response()))\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":16,"symbol":"PathRouter","kind":"type","lang":"rust","code":"pub(super) struct PathRouter {\n routes: Vec>,\n node: Arc,\n}"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":21,"symbol":"validate_path","kind":"function","lang":"rust","code":"fn validate_path(path: &str) -> Result<(), &'static str> {\n if path.is_empty() {\n return Err(\"Paths must start with a `/`. Use \\\"/\\\" for root routes\");\n } else if !path.starts_with('/') {\n return Err(\"Paths must start with a `/`\");\n }\n\n Ok(())\n}"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":35,"symbol":"route","kind":"function","lang":"rust","code":"pub(super) fn route(\n &mut self,\n path: &str,\n method_router: MethodRouter,\n ) -> Result<(), Cow<'static, str>> {\n validate_path(path)?;\n\n if let Some((route_id, Endpoint::MethodRouter(prev_method_router))) = self\n .node\n .path_to_route_id\n .get(path)\n .and_then(|route_id| self.routes.get(route_id.0).map(|svc| (*route_id, svc)))\n {\n // if we're adding a new `MethodRouter` to a route that already has one just\n // merge them. This makes `.route(\"/\", get(_)).route(\"/\", post(_))` work\n let service = Endpoint::MethodRouter(\n prev_method_router\n .clone()\n .merge_for_path(Some(path), method_router)?,\n );\n self.routes[route_id.0] = service;\n } else {\n let endpoint = Endpoint::MethodRouter(method_router);\n self.new_route(path, endpoint)?;\n }\n\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":64,"symbol":"method_not_allowed_fallback","kind":"function","lang":"rust","code":"pub(super) fn method_not_allowed_fallback(&mut self, handler: &H)\n where\n H: Handler,\n T: 'static,\n {\n for endpoint in self.routes.iter_mut() {\n if let Endpoint::MethodRouter(rt) = endpoint {\n *rt = rt.clone().default_fallback(handler.clone());\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":76,"symbol":"route_service","kind":"function","lang":"rust","code":"pub(super) fn route_service(\n &mut self,\n path: &str,\n service: T,\n ) -> Result<(), Cow<'static, str>>\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n {\n self.route_endpoint(path, Endpoint::Route(Route::new(service)))\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":89,"symbol":"route_endpoint","kind":"function","lang":"rust","code":"pub(super) fn route_endpoint(\n &mut self,\n path: &str,\n endpoint: Endpoint,\n ) -> Result<(), Cow<'static, str>> {\n validate_path(path)?;\n\n self.new_route(path, endpoint)?;\n\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":101,"symbol":"set_node","kind":"function","lang":"rust","code":"fn set_node(&mut self, path: &str, id: RouteId) -> Result<(), String> {\n let node = Arc::make_mut(&mut self.node);\n\n node.insert(path, id)\n .map_err(|err| format!(\"Invalid route {path:?}: {err}\"))\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":108,"symbol":"new_route","kind":"function","lang":"rust","code":"fn new_route(&mut self, path: &str, endpoint: Endpoint) -> Result<(), String> {\n let id = RouteId(self.routes.len());\n self.set_node(path, id)?;\n self.routes.push(endpoint);\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":115,"symbol":"merge","kind":"function","lang":"rust","code":"pub(super) fn merge(&mut self, other: Self) -> Result<(), Cow<'static, str>> {\n let Self { routes, node } = other;\n\n for (id, route) in routes.into_iter().enumerate() {\n let route_id = RouteId(id);\n let path = node\n .route_id_to_path\n .get(&route_id)\n .expect(\"no path for route id. This is a bug in axum. Please file an issue\");\n\n match route {\n Endpoint::MethodRouter(method_router) => self.route(path, method_router)?,\n Endpoint::Route(route) => self.route_service(path, route)?,\n }\n }\n\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":134,"symbol":"nest","kind":"function","lang":"rust","code":"pub(super) fn nest(\n &mut self,\n path_to_nest_at: &str,\n router: Self,\n ) -> Result<(), Cow<'static, str>> {\n let prefix = validate_nest_path(path_to_nest_at)?;\n\n let Self { routes, node } = router;\n\n for (id, endpoint) in routes.into_iter().enumerate() {\n let route_id = RouteId(id);\n let inner_path = node\n .route_id_to_path\n .get(&route_id)\n .expect(\"no path for route id. This is a bug in axum. Please file an issue\");\n\n let path = path_for_nested_route(prefix, inner_path);\n\n let layer = (\n StripPrefix::layer(prefix),\n SetNestedPath::layer(path_to_nest_at),\n );\n match endpoint.layer(layer) {\n Endpoint::MethodRouter(method_router) => {\n self.route(&path, method_router)?;\n }\n Endpoint::Route(route) => {\n self.route_endpoint(&path, Endpoint::Route(route))?;\n }\n }\n }\n\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":169,"symbol":"nest_service","kind":"function","lang":"rust","code":"pub(super) fn nest_service(\n &mut self,\n path_to_nest_at: &str,\n svc: T,\n ) -> Result<(), Cow<'static, str>>\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n {\n let path = validate_nest_path(path_to_nest_at)?;\n let prefix = path;\n\n let path = if path.ends_with('/') {\n format!(\"{path}{{*{NEST_TAIL_PARAM}}}\")\n } else {\n format!(\"{path}/{{*{NEST_TAIL_PARAM}}}\")\n };\n\n let layer = (\n StripPrefix::layer(prefix),\n SetNestedPath::layer(path_to_nest_at),\n );\n let endpoint = Endpoint::Route(Route::new(layer.layer(svc)));\n\n self.route_endpoint(&path, endpoint.clone())?;\n\n // `/{*rest}` is not matched by `/` so we need to also register a router at the\n // prefix itself. Otherwise if you were to nest at `/foo` then `/foo` itself\n // wouldn't match, which it should\n self.route_endpoint(prefix, endpoint.clone())?;\n if !prefix.ends_with('/') {\n // same goes for `/foo/`, that should also match\n se"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":208,"symbol":"layer","kind":"function","lang":"rust","code":"pub(super) fn layer(self, layer: L) -> Self\n where\n L: Layer + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n {\n let routes = self\n .routes\n .into_iter()\n .map(|endpoint| endpoint.layer(layer.clone()))\n .collect();\n\n Self {\n routes,\n node: self.node,\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":229,"symbol":"route_layer","kind":"function","lang":"rust","code":"pub(super) fn route_layer(self, layer: L) -> Self\n where\n L: Layer + Clone + Send + Sync + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n {\n if self.routes.is_empty() {\n panic!(\n \"Adding a route_layer before any routes is a no-op. \\\n Add the routes you want the layer to apply to first.\"\n );\n }\n\n let routes = self\n .routes\n .into_iter()\n .map(|endpoint| endpoint.layer(layer.clone()))\n .collect();\n\n Self {\n routes,\n node: self.node,\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":256,"symbol":"has_routes","kind":"function","lang":"rust","code":"pub(super) fn has_routes(&self) -> bool {\n !self.routes.is_empty()\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":260,"symbol":"with_state","kind":"function","lang":"rust","code":"pub(super) fn with_state(self, state: S) -> PathRouter {\n let routes = self\n .routes\n .into_iter()\n .map(|endpoint| match endpoint {\n Endpoint::MethodRouter(method_router) => {\n Endpoint::MethodRouter(method_router.with_state(state.clone()))\n }\n Endpoint::Route(route) => Endpoint::Route(route),\n })\n .collect();\n\n PathRouter {\n routes,\n node: self.node,\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":279,"symbol":"call_with_state","kind":"function","lang":"rust","code":"pub(super) fn call_with_state(\n &self,\n #[cfg_attr(not(feature = \"original-uri\"), allow(unused_mut))] mut req: Request,\n state: S,\n ) -> Result, (Request, S)> {\n #[cfg(feature = \"original-uri\")]\n {\n use crate::extract::OriginalUri;\n\n if req.extensions().get::().is_none() {\n let original_uri = OriginalUri(req.uri().clone());\n req.extensions_mut().insert(original_uri);\n }\n }\n\n let (mut parts, body) = req.into_parts();\n\n match self.node.at(parts.uri.path()) {\n Ok(match_) => {\n let id = *match_.value;\n\n #[cfg(feature = \"matched-path\")]\n crate::extract::matched_path::set_matched_path_for_request(\n id,\n &self.node.route_id_to_path,\n &mut parts.extensions,\n );\n\n url_params::insert_url_params(&mut parts.extensions, &match_.params);\n\n let endpoint = self\n .routes\n .get(id.0)\n .expect(\"no route for id. This is a bug in axum."} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":330,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self {\n routes: Default::default(),\n node: Default::default(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":339,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"PathRouter\")\n .field(\"routes\", &self.routes)\n .field(\"node\", &self.node)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":348,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n routes: self.routes.clone(),\n node: self.node.clone(),\n }\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":358,"symbol":"Node","kind":"type","lang":"rust","doc":"Wrapper around `matchit::Router` that supports merging two `Router`s.","code":"struct Node {\n inner: matchit::Router,\n route_id_to_path: HashMap>,\n path_to_route_id: HashMap, RouteId>,\n}"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":365,"symbol":"insert","kind":"function","lang":"rust","code":"fn insert(\n &mut self,\n path: impl Into,\n val: RouteId,\n ) -> Result<(), matchit::InsertError> {\n let path = path.into();\n\n self.inner.insert(&path, val)?;\n\n let shared_path: Arc = path.into();\n self.route_id_to_path.insert(val, shared_path.clone());\n self.path_to_route_id.insert(shared_path, val);\n\n Ok(())\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":381,"symbol":"at","kind":"function","lang":"rust","code":"fn at<'n, 'p>(\n &'n self,\n path: &'p str,\n ) -> Result, MatchError> {\n self.inner.at(path)\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":390,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Node\")\n .field(\"paths\", &self.route_id_to_path)\n .finish()\n }"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":397,"symbol":"validate_nest_path","kind":"function","lang":"rust","code":"fn validate_nest_path(path: &str) -> Result<&str, &'static str> {\n if !path.starts_with('/') {\n return Err(\"Nesting paths must start with a `/`.\");\n }\n if path.len() < 2 {\n return Err(\"Nesting at `/` is not supported.\");\n }\n\n if path.split('/').any(|segment| {\n segment.starts_with(\"{*\") && segment.ends_with('}') && !segment.ends_with(\"}}\")\n }) {\n return Err(\"Invalid route: nested routes cannot contain wildcards (*)\");\n }\n\n Ok(path)\n}"} {"repo":"axum","file":"axum/src/routing/path_router.rs","line":414,"symbol":"path_for_nested_route","kind":"function","lang":"rust","code":"pub(crate) fn path_for_nested_route<'a>(prefix: &'a str, path: &'a str) -> Cow<'a, str> {\n debug_assert!(prefix.starts_with('/'));\n debug_assert!(path.starts_with('/'));\n\n if prefix.ends_with('/') {\n format!(\"{prefix}{}\", path.trim_start_matches('/')).into()\n } else if path == \"/\" {\n prefix.into()\n } else {\n format!(\"{prefix}{path}\").into()\n }\n}"} {"repo":"axum","file":"axum/src/routing/route.rs","line":31,"symbol":"Route","kind":"type","lang":"rust","doc":"How routes are stored inside a [`Router`](super::Router). You normally shouldn't need to care about this type. It's used in [`Router::layer`](super::Router::layer).","code":"pub struct Route(BoxCloneSyncService);"} {"repo":"axum","file":"axum/src/routing/route.rs","line":34,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(svc: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse + 'static,\n T::Future: Send + 'static,\n {\n Self(BoxCloneSyncService::new(MapIntoResponse::new(svc)))\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":44,"symbol":"call_owned","kind":"function","lang":"rust","doc":"Variant of [`Route::call`] that takes ownership of the route to avoid cloning.","code":"pub(crate) fn call_owned(self, req: Request) -> RouteFuture {\n let req = req.map(Body::new);\n self.oneshot_inner_owned(req).not_top_level()\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":49,"symbol":"oneshot_inner","kind":"function","lang":"rust","code":"pub(crate) fn oneshot_inner(&self, req: Request) -> RouteFuture {\n let method = req.method().clone();\n RouteFuture::new(method, self.0.clone().oneshot(req))\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":55,"symbol":"oneshot_inner_owned","kind":"function","lang":"rust","doc":"Variant of [`Route::oneshot_inner`] that takes ownership of the route to avoid cloning.","code":"pub(crate) fn oneshot_inner_owned(self, req: Request) -> RouteFuture {\n let method = req.method().clone();\n RouteFuture::new(method, self.0.oneshot(req))\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":60,"symbol":"layer","kind":"function","lang":"rust","code":"pub(crate) fn layer(self, layer: L) -> Route\n where\n L: Layer + Clone + Send + 'static,\n L::Service: Service + Clone + Send + Sync + 'static,\n >::Response: IntoResponse + 'static,\n >::Error: Into + 'static,\n >::Future: Send + 'static,\n NewError: 'static,\n {\n let layer = (MapErrLayer::new(Into::into), layer);\n\n Route::new(layer.layer(self))\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":77,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self(self.0.clone())\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":83,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Route\").finish()\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":98,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":103,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: Request) -> Self::Future {\n self.oneshot_inner(req.map(Body::new)).not_top_level()\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":120,"symbol":"new","kind":"function","lang":"rust","code":"fn new(\n method: Method,\n inner: Oneshot, Request>,\n ) -> Self {\n Self {\n inner,\n method,\n allow_header: None,\n top_level: true,\n }\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":132,"symbol":"allow_header","kind":"function","lang":"rust","code":"pub(crate) fn allow_header(mut self, allow_header: Bytes) -> Self {\n self.allow_header = Some(allow_header);\n self\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":137,"symbol":"not_top_level","kind":"function","lang":"rust","code":"pub(crate) fn not_top_level(mut self) -> Self {\n self.top_level = false;\n self\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":147,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n let mut res = ready!(this.inner.poll(cx))?;\n\n if *this.method == Method::CONNECT && res.status().is_success() {\n // From https://httpwg.org/specs/rfc9110.html#CONNECT:\n // > A server MUST NOT send any Transfer-Encoding or\n // > Content-Length header fields in a 2xx (Successful)\n // > response to CONNECT.\n if res.headers().contains_key(&CONTENT_LENGTH)\n || res.headers().contains_key(&header::TRANSFER_ENCODING)\n || res.size_hint().lower() != 0\n {\n error!(\"response to CONNECT with nonempty body\");\n res = res.map(|_| Body::empty());\n }\n } else if *this.top_level {\n if res.status() == http::StatusCode::METHOD_NOT_ALLOWED {\n // From https://httpwg.org/specs/rfc9110.html#field.allow:\n // An origin server MUST generate an `Allow` header field in a 405 (Method Not Allowed) response and MAY do so in any other response.\n set_allow_header(res.headers_mut(), this.allow_heade"} {"repo":"axum","file":"axum/src/routing/route.rs","line":182,"symbol":"set_allow_header","kind":"function","lang":"rust","code":"fn set_allow_header(headers: &mut HeaderMap, allow_header: &mut Option) {\n match allow_header.take() {\n Some(allow_header) if !headers.contains_key(header::ALLOW) => {\n headers.insert(\n header::ALLOW,\n HeaderValue::from_maybe_shared(allow_header).expect(\"invalid `Allow` header\"),\n );\n }\n _ => {}\n }\n}"} {"repo":"axum","file":"axum/src/routing/route.rs","line":194,"symbol":"set_content_length","kind":"function","lang":"rust","code":"fn set_content_length(size_hint: &http_body::SizeHint, headers: &mut HeaderMap) {\n if headers.contains_key(CONTENT_LENGTH) {\n return;\n }\n\n if let Some(size) = size_hint.exact() {\n let header_value = if size == 0 {\n #[allow(clippy::declare_interior_mutable_const)]\n const ZERO: HeaderValue = HeaderValue::from_static(\"0\");\n\n ZERO\n } else {\n let mut buffer = itoa::Buffer::new();\n HeaderValue::from_str(buffer.format(size)).unwrap()\n };\n\n headers.insert(CONTENT_LENGTH, header_value);\n }\n}"} {"repo":"axum","file":"axum/src/routing/route.rs","line":223,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(future: RouteFuture) -> Self {\n Self { future }\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":231,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().future.poll(cx)) {\n Ok(response) => Poll::Ready(response),\n Err(err) => match err {},\n }\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":245,"symbol":"traits","kind":"function","lang":"rust","code":"fn traits() {\n use crate::test_helpers::*;\n assert_send::>();\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":251,"symbol":"regression_3741","kind":"function","lang":"rust","code":"async fn regression_3741() {\n const BODY: &str = \"Very expensive body.\";\n let content_length: HeaderValue = HeaderValue::from_str(&BODY.len().to_string()).unwrap();\n\n async fn handler(method: http::Method) -> Response {\n if method == http::Method::HEAD {\n ().into_response()\n } else {\n BODY.into_response()\n }\n }\n\n let client = TestClient::new(Router::new().route(\"/\", get(handler)));\n\n let get = client.get(\"/\").await;\n assert_eq!(get.status(), http::StatusCode::OK);\n assert_eq!(get.headers().get(CONTENT_LENGTH), Some(&content_length));\n\n let head = client.head(\"/\").await;\n assert_eq!(get.status(), http::StatusCode::OK);\n assert_eq!(head.headers().get(CONTENT_LENGTH), None);\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":255,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(method: http::Method) -> Response {\n if method == http::Method::HEAD {\n ().into_response()\n } else {\n BODY.into_response()\n }\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":275,"symbol":"head_content_length_default","kind":"function","lang":"rust","code":"async fn head_content_length_default() {\n const BODY: &str = \"Hello world!\";\n let content_length: HeaderValue = HeaderValue::from_str(&BODY.len().to_string()).unwrap();\n\n async fn handler() -> Response {\n BODY.into_response()\n }\n\n let client = TestClient::new(Router::new().route(\"/\", get(handler)));\n\n let get = client.get(\"/\").await;\n assert_eq!(get.status(), http::StatusCode::OK);\n assert_eq!(get.headers().get(CONTENT_LENGTH), Some(&content_length));\n\n let head = client.head(\"/\").await;\n assert_eq!(head.status(), http::StatusCode::OK);\n assert_eq!(head.headers().get(CONTENT_LENGTH), Some(&content_length));\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":279,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Response {\n BODY.into_response()\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":295,"symbol":"unit_content_length_zero","kind":"function","lang":"rust","code":"async fn unit_content_length_zero() {\n let content_length: HeaderValue = HeaderValue::from_static(\"0\");\n\n async fn handler() -> Response {\n ().into_response()\n }\n\n let client = TestClient::new(Router::new().route(\"/\", get(handler)));\n\n let get = client.get(\"/\").await;\n assert_eq!(get.status(), http::StatusCode::OK);\n assert_eq!(get.headers().get(CONTENT_LENGTH), Some(&content_length));\n }"} {"repo":"axum","file":"axum/src/routing/route.rs","line":298,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Response {\n ().into_response()\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":12,"symbol":"StripPrefix","kind":"type","lang":"rust","code":"pub(super) struct StripPrefix {\n inner: S,\n prefix: Arc,\n captures_count: usize,\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":19,"symbol":"layer","kind":"function","lang":"rust","code":"pub(super) fn layer(prefix: &str) -> impl Layer + Clone {\n let captures_count = count_captures(prefix);\n let prefix = Arc::from(prefix);\n layer_fn(move |inner| Self {\n inner,\n prefix: Arc::clone(&prefix),\n captures_count,\n })\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":39,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":43,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, mut req: Request) -> Self::Future {\n if let Some(new_uri) = strip_prefix(req.uri(), &self.prefix) {\n *req.uri_mut() = new_uri;\n }\n url_params::advance_inner_start(req.extensions_mut(), self.captures_count);\n self.inner.call(req)\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":52,"symbol":"count_captures","kind":"function","lang":"rust","code":"fn count_captures(path: &str) -> usize {\n segments(path).filter_map(capture_prefix_suffix).count()\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":56,"symbol":"strip_prefix","kind":"function","lang":"rust","code":"fn strip_prefix(uri: &Uri, prefix: &str) -> Option {\n let path_and_query = uri.path_and_query()?;\n\n // Check whether the prefix matches the path and if so how long the matching prefix is.\n //\n // For example:\n //\n // prefix = /api\n // path = /api/users\n // ^^^^ this much is matched and the length is 4. Thus if we chop off the first 4\n // characters we get the remainder\n //\n // prefix = /api/{version}\n // path = /api/v0/users\n // ^^^^^^^ this much is matched and the length is 7.\n let mut matching_prefix_length = Some(0);\n for item in zip_longest(segments(path_and_query.path()), segments(prefix)) {\n // count the `/`\n *matching_prefix_length.as_mut().unwrap() += 1;\n\n match item {\n Item::Both(path_segment, prefix_segment) => {\n if prefix_matches(prefix_segment, path_segment) {\n // the prefix segment is either a param, which matches anything, or\n // it actually matches the path segment\n *matching_prefix_length.as_mut().unwrap() += path_segment.len();\n } else if prefix_segment.is_empty() {\n "} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":133,"symbol":"segments","kind":"function","lang":"rust","code":"fn segments(s: &str) -> impl Iterator {\n assert!(\n s.starts_with('/'),\n \"path didn't start with '/'. axum should have caught this higher up.\"\n );\n\n s.split('/')\n // skip one because paths always start with `/` so `/a/b` would become [\"\", \"a\", \"b\"]\n // otherwise\n .skip(1)\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":145,"symbol":"zip_longest","kind":"function","lang":"rust","code":"fn zip_longest(a: I, b: I2) -> impl Iterator>\nwhere\n I: Iterator,\n I2: Iterator,\n{\n let a = a.map(Some).chain(std::iter::repeat_with(|| None));\n let b = b.map(Some).chain(std::iter::repeat_with(|| None));\n a.zip(b).map_while(|(a, b)| match (a, b) {\n (Some(a), Some(b)) => Some(Item::Both(a, b)),\n (Some(a), None) => Some(Item::First(a)),\n (None, Some(b)) => Some(Item::Second(b)),\n (None, None) => None,\n })\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":160,"symbol":"prefix_matches","kind":"function","lang":"rust","code":"fn prefix_matches(prefix_segment: &str, path_segment: &str) -> bool {\n if let Some((prefix, suffix)) = capture_prefix_suffix(prefix_segment) {\n path_segment.starts_with(prefix) && path_segment.ends_with(suffix)\n } else {\n prefix_segment == path_segment\n }\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":171,"symbol":"capture_prefix_suffix","kind":"function","lang":"rust","doc":"Takes a segment and returns prefix and suffix of the path, omitting the capture. Currently, matchit supports only one capture so this can be a pair. If there is no capture, `None` is returned.","code":"fn capture_prefix_suffix(segment: &str) -> Option<(&str, &str)> {\n fn find_first_not_double(needle: u8, haystack: &[u8]) -> Option {\n let mut possible_capture = 0;\n while let Some(index) = haystack\n .get(possible_capture..)\n .and_then(|haystack| haystack.iter().position(|byte| byte == &needle))\n {\n let index = index + possible_capture;\n\n if haystack.get(index + 1) == Some(&needle) {\n possible_capture = index + 2;\n continue;\n }\n\n return Some(index);\n }\n\n None\n }\n\n let capture_start = find_first_not_double(b'{', segment.as_bytes())?;\n\n let Some(capture_end) = find_first_not_double(b'}', segment.as_bytes()) else {\n if cfg!(debug_assertions) {\n panic!(\n \"Segment `{segment}` is malformed. It seems to contain a capture start but no \\\n capture end. This should have been rejected at application start, please file a \\\n bug in axum repository.\"\n );\n } else {\n // This is very bad but let's not panic in production. This will most likely not match.\n "} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":172,"symbol":"find_first_not_double","kind":"function","lang":"rust","code":"fn find_first_not_double(needle: u8, haystack: &[u8]) -> Option {\n let mut possible_capture = 0;\n while let Some(index) = haystack\n .get(possible_capture..)\n .and_then(|haystack| haystack.iter().position(|byte| byte == &needle))\n {\n let index = index + possible_capture;\n\n if haystack.get(index + 1) == Some(&needle) {\n possible_capture = index + 2;\n continue;\n }\n\n return Some(index);\n }\n\n None\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":224,"symbol":"Item","kind":"type","lang":"rust","code":"enum Item {\n Both(T, T),\n First(T),\n Second(T),\n}"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":448,"symbol":"does_not_panic","kind":"function","lang":"rust","code":"fn does_not_panic(uri_and_prefix: UriAndPrefix) -> bool {\n let UriAndPrefix { uri, prefix } = uri_and_prefix;\n strip_prefix(&uri, &prefix);\n true\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":455,"symbol":"count_captures_counts_correctly","kind":"function","lang":"rust","code":"fn count_captures_counts_correctly() {\n assert_eq!(count_captures(\"/index.html\"), 0);\n assert_eq!(count_captures(\"/api/v{version}\"), 1);\n assert_eq!(count_captures(\"/api/{version}/users/{id}\"), 2);\n assert_eq!(count_captures(\"/{{brackets}}/{version}/users/{id}\"), 2);\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":463,"symbol":"UriAndPrefix","kind":"type","lang":"rust","code":"struct UriAndPrefix {\n uri: Uri,\n prefix: String,\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":469,"symbol":"arbitrary","kind":"function","lang":"rust","code":"fn arbitrary(g: &mut quickcheck::Gen) -> Self {\n let mut uri = String::new();\n let mut prefix = String::new();\n\n let size = u8_between(1, 20, g);\n\n for _ in 0..size {\n let segment = ascii_alphanumeric(g);\n\n uri.push('/');\n uri.push_str(&segment);\n\n prefix.push('/');\n\n let make_matching_segment = bool::arbitrary(g);\n let make_capture = bool::arbitrary(g);\n\n match (make_matching_segment, make_capture) {\n (_, true) => {\n prefix.push_str(\":a\");\n }\n (true, false) => {\n prefix.push_str(&segment);\n }\n (false, false) => {\n prefix.push_str(&ascii_alphanumeric(g));\n }\n }\n }\n\n if bool::arbitrary(g) {\n uri.push('/');\n }\n\n if bool::arbitrary(g) {\n prefix.push('/');\n }\n\n Self {\n uri: uri.parse().unwrap(),\n prefix,\n }\n "} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":514,"symbol":"ascii_alphanumeric","kind":"function","lang":"rust","code":"fn ascii_alphanumeric(g: &mut quickcheck::Gen) -> String {\n #[derive(Clone)]\n struct AsciiAlphanumeric(String);\n\n impl Arbitrary for AsciiAlphanumeric {\n fn arbitrary(g: &mut quickcheck::Gen) -> Self {\n let mut out = String::new();\n\n let size = u8_between(1, 20, g) as usize;\n\n while out.len() < size {\n let c = char::arbitrary(g);\n if c.is_ascii_alphanumeric() {\n out.push(c);\n }\n }\n Self(out)\n }\n }\n\n let out = AsciiAlphanumeric::arbitrary(g).0;\n assert!(!out.is_empty());\n out\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":516,"symbol":"AsciiAlphanumeric","kind":"type","lang":"rust","code":"struct AsciiAlphanumeric(String);"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":519,"symbol":"arbitrary","kind":"function","lang":"rust","code":"fn arbitrary(g: &mut quickcheck::Gen) -> Self {\n let mut out = String::new();\n\n let size = u8_between(1, 20, g) as usize;\n\n while out.len() < size {\n let c = char::arbitrary(g);\n if c.is_ascii_alphanumeric() {\n out.push(c);\n }\n }\n Self(out)\n }"} {"repo":"axum","file":"axum/src/routing/strip_prefix.rs","line":539,"symbol":"u8_between","kind":"function","lang":"rust","code":"fn u8_between(lower: u8, upper: u8, g: &mut quickcheck::Gen) -> u8 {\n loop {\n let size = u8::arbitrary(g);\n if size > lower && size <= upper {\n break size;\n }\n }\n }"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":5,"symbol":"basic","kind":"function","lang":"rust","code":"async fn basic() {\n let app = Router::new()\n .route(\"/foo\", get(|| async {}))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/foo\").await.status(), StatusCode::OK);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":20,"symbol":"nest","kind":"function","lang":"rust","code":"async fn nest() {\n let app = Router::new()\n .nest(\"/foo\", Router::new().route(\"/bar\", get(|| async {})))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/foo/bar\").await.status(), StatusCode::OK);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":35,"symbol":"two","kind":"function","lang":"rust","code":"async fn two() {\n let app = Router::new()\n .route(\"/first\", get(|| async {}))\n .route(\"/second\", get(|| async {}))\n .fallback(get(|| async { \"fallback\" }));\n let client = TestClient::new(app);\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":47,"symbol":"or","kind":"function","lang":"rust","code":"async fn or() {\n let one = Router::new().route(\"/one\", get(|| async {}));\n let two = Router::new().route(\"/two\", get(|| async {}));\n\n let app = one.merge(two).fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/one\").await.status(), StatusCode::OK);\n assert_eq!(client.get(\"/two\").await.status(), StatusCode::OK);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":64,"symbol":"fallback_accessing_state","kind":"function","lang":"rust","code":"async fn fallback_accessing_state() {\n let app = Router::new()\n .fallback(|State(state): State<&'static str>| async move { state })\n .with_state(\"state\");\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"state\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":76,"symbol":"inner_fallback","kind":"function","lang":"rust","code":"async fn inner_fallback() -> impl IntoResponse {\n (StatusCode::NOT_FOUND, \"inner\")\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":80,"symbol":"outer_fallback","kind":"function","lang":"rust","code":"async fn outer_fallback() -> impl IntoResponse {\n (StatusCode::NOT_FOUND, \"outer\")\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":85,"symbol":"nested_router_inherits_fallback","kind":"function","lang":"rust","code":"async fn nested_router_inherits_fallback() {\n let inner = Router::new();\n let app = Router::new().nest(\"/foo\", inner).fallback(outer_fallback);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":97,"symbol":"doesnt_inherit_fallback_if_overridden","kind":"function","lang":"rust","code":"async fn doesnt_inherit_fallback_if_overridden() {\n let inner = Router::new().fallback(inner_fallback);\n let app = Router::new().nest(\"/foo\", inner).fallback(outer_fallback);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":113,"symbol":"deeply_nested_inherit_from_top","kind":"function","lang":"rust","code":"async fn deeply_nested_inherit_from_top() {\n let app = Router::new()\n .nest(\"/foo\", Router::new().nest(\"/bar\", Router::new()))\n .fallback(outer_fallback);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":126,"symbol":"deeply_nested_inherit_from_middle","kind":"function","lang":"rust","code":"async fn deeply_nested_inherit_from_middle() {\n let app = Router::new().nest(\n \"/foo\",\n Router::new()\n .nest(\"/bar\", Router::new())\n .fallback(outer_fallback),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":142,"symbol":"with_middleware_on_inner_fallback","kind":"function","lang":"rust","code":"async fn with_middleware_on_inner_fallback() {\n async fn never_called(_: Request) -> Request {\n panic!(\"should never be called\")\n }\n\n let inner = Router::new().layer(map_request(never_called));\n let app = Router::new().nest(\"/foo\", inner).fallback(outer_fallback);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":143,"symbol":"never_called","kind":"function","lang":"rust","code":"async fn never_called(_: Request) -> Request {\n panic!(\"should never be called\")\n }"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":158,"symbol":"also_inherits_default_layered_fallback","kind":"function","lang":"rust","code":"async fn also_inherits_default_layered_fallback() {\n async fn set_header(mut res: Response) -> Response {\n res.headers_mut()\n .insert(\"x-from-fallback\", \"1\".parse().unwrap());\n res\n }\n\n let inner = Router::new();\n let app = Router::new()\n .nest(\"/foo\", inner)\n .fallback(outer_fallback)\n .layer(map_response(set_header));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.headers()[\"x-from-fallback\"], \"1\");\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":159,"symbol":"set_header","kind":"function","lang":"rust","code":"async fn set_header(mut res: Response) -> Response {\n res.headers_mut()\n .insert(\"x-from-fallback\", \"1\".parse().unwrap());\n res\n }"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":180,"symbol":"nest_fallback_on_inner","kind":"function","lang":"rust","code":"async fn nest_fallback_on_inner() {\n let app = Router::new()\n .nest(\n \"/foo\",\n Router::new()\n .route(\"/\", get(|| async {}))\n .fallback(|| async { (StatusCode::NOT_FOUND, \"inner fallback\") }),\n )\n .fallback(|| async { (StatusCode::NOT_FOUND, \"outer fallback\") });\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/not-found\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":199,"symbol":"doesnt_panic_if_used_with_nested_router","kind":"function","lang":"rust","doc":"https://github.com/tokio-rs/axum/issues/1931","code":"async fn doesnt_panic_if_used_with_nested_router() {\n async fn handler() {}\n\n let routes_static =\n Router::new().nest_service(\"/foo\", crate::routing::get_service(handler.into_service()));\n\n let routes_all = Router::new().fallback_service(routes_static);\n\n let client = TestClient::new(routes_all);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":200,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":214,"symbol":"issue_2072","kind":"function","lang":"rust","code":"async fn issue_2072() {\n let nested_routes = Router::new().fallback(inner_fallback);\n\n let app = Router::new()\n .nest(\"/nested\", nested_routes)\n .merge(Router::new());\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/nested/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":233,"symbol":"issue_2072_outer_fallback_before_merge","kind":"function","lang":"rust","code":"async fn issue_2072_outer_fallback_before_merge() {\n let nested_routes = Router::new().fallback(inner_fallback);\n\n let app = Router::new()\n .nest(\"/nested\", nested_routes)\n .fallback(outer_fallback)\n .merge(Router::new());\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/nested/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":253,"symbol":"issue_2072_outer_fallback_after_merge","kind":"function","lang":"rust","code":"async fn issue_2072_outer_fallback_after_merge() {\n let nested_routes = Router::new().fallback(inner_fallback);\n\n let app = Router::new()\n .nest(\"/nested\", nested_routes)\n .merge(Router::new())\n .fallback(outer_fallback);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/nested/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":273,"symbol":"merge_router_with_fallback_into_nested_router_with_fallback","kind":"function","lang":"rust","code":"async fn merge_router_with_fallback_into_nested_router_with_fallback() {\n let nested_routes = Router::new().fallback(inner_fallback);\n\n let app = Router::new()\n .nest(\"/nested\", nested_routes)\n .merge(Router::new().fallback(outer_fallback));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/nested/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":292,"symbol":"merging_nested_router_with_fallback_into_router_with_fallback","kind":"function","lang":"rust","code":"async fn merging_nested_router_with_fallback_into_router_with_fallback() {\n let nested_routes = Router::new().fallback(inner_fallback);\n\n let app = Router::new()\n .fallback(outer_fallback)\n .merge(Router::new().nest(\"/nested\", nested_routes));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/nested/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"inner\");\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":311,"symbol":"merge_empty_into_router_with_fallback","kind":"function","lang":"rust","code":"async fn merge_empty_into_router_with_fallback() {\n let app = Router::new().fallback(outer_fallback).merge(Router::new());\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":322,"symbol":"merge_router_with_fallback_into_empty","kind":"function","lang":"rust","code":"async fn merge_router_with_fallback_into_empty() {\n let app = Router::new().merge(Router::new().fallback(outer_fallback));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/does-not-exist\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n assert_eq!(res.text().await, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":333,"symbol":"mna_fallback_not_405","kind":"function","lang":"rust","code":"async fn mna_fallback_not_405() {\n let app = Router::new()\n .route(\"/path\", get(|| async { \"path\" }))\n .method_not_allowed_fallback(|| async { (http::StatusCode::NOT_FOUND, \"Not Found\") });\n\n let client = TestClient::new(app);\n let method_not_allowed_fallback = client.post(\"/path\").await;\n\n assert_eq!(\n method_not_allowed_fallback.status(),\n http::StatusCode::NOT_FOUND\n );\n assert_eq!(method_not_allowed_fallback.headers().get(ALLOW), None);\n assert_eq!(method_not_allowed_fallback.text().await, \"Not Found\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":350,"symbol":"mna_fallback_with_existing_fallback","kind":"function","lang":"rust","code":"async fn mna_fallback_with_existing_fallback() {\n let app = Router::new()\n .route(\n \"/\",\n get(|| async { \"test\" }).fallback(|| async { \"index fallback\" }),\n )\n .route(\"/path\", get(|| async { \"path\" }))\n .method_not_allowed_fallback(|| async { \"method not allowed fallback\" });\n\n let client = TestClient::new(app);\n let index_fallback = client.post(\"/\").await;\n let method_not_allowed_fallback = client.post(\"/path\").await;\n\n assert_eq!(index_fallback.text().await, \"index fallback\");\n assert_eq!(\n method_not_allowed_fallback.text().await,\n \"method not allowed fallback\"\n );\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":371,"symbol":"mna_fallback_with_state","kind":"function","lang":"rust","code":"async fn mna_fallback_with_state() {\n let app = Router::new()\n .route(\"/\", get(|| async { \"index\" }))\n .method_not_allowed_fallback(|State(state): State<&'static str>| async move { state })\n .with_state(\"state\");\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").await;\n assert_eq!(res.text().await, \"state\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":383,"symbol":"mna_fallback_with_unused_state","kind":"function","lang":"rust","code":"async fn mna_fallback_with_unused_state() {\n let app = Router::new()\n .route(\"/\", get(|| async { \"index\" }))\n .with_state(())\n .method_not_allowed_fallback(|| async move { \"bla\" });\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").await;\n assert_eq!(res.text().await, \"bla\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/fallback.rs","line":395,"symbol":"state_isnt_cloned_too_much_with_fallback","kind":"function","lang":"rust","code":"async fn state_isnt_cloned_too_much_with_fallback() {\n let state = CountingCloneableState::new();\n\n let app = Router::new()\n .fallback(|_: State| async {})\n .with_state(state.clone());\n\n let client = TestClient::new(app);\n\n // ignore clones made during setup\n state.setup_done();\n\n client.get(\"/does-not-exist\").await;\n\n assert_eq!(state.count(), 3);\n}"} {"repo":"axum","file":"axum/src/routing/tests/get_to_head.rs","line":8,"symbol":"get_handles_head","kind":"function","lang":"rust","code":"async fn get_handles_head() {\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let mut headers = HeaderMap::new();\n headers.insert(\"x-some-header\", \"foobar\".parse().unwrap());\n (headers, \"you shouldn't see this\")\n }),\n );\n\n // don't use reqwest because it always strips bodies from HEAD responses\n let res = app\n .oneshot(\n Request::builder()\n .uri(\"/\")\n .method(Method::HEAD)\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.headers()[\"x-some-header\"], \"foobar\");\n\n let body = BodyExt::collect(res.into_body()).await.unwrap().to_bytes();\n assert_eq!(body.len(), 0);\n }"} {"repo":"axum","file":"axum/src/routing/tests/get_to_head.rs","line":42,"symbol":"get_handles_head","kind":"function","lang":"rust","code":"async fn get_handles_head() {\n let app = Router::new().route(\n \"/\",\n get_service(service_fn(|_req: Request| async move {\n Ok::<_, Infallible>(\n ([(\"x-some-header\", \"foobar\")], \"you shouldn't see this\").into_response(),\n )\n })),\n );\n\n // don't use reqwest because it always strips bodies from HEAD responses\n let res = app\n .oneshot(\n Request::builder()\n .uri(\"/\")\n .method(Method::HEAD)\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.headers()[\"x-some-header\"], \"foobar\");\n\n let body = BodyExt::collect(res.into_body()).await.unwrap().to_bytes();\n assert_eq!(body.len(), 0);\n }"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":5,"symbol":"unit","kind":"function","lang":"rust","code":"async fn unit() {}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":7,"symbol":"forever","kind":"function","lang":"rust","code":"async fn forever() {\n pending().await\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":11,"symbol":"timeout","kind":"function","lang":"rust","code":"fn timeout() -> TimeoutLayer {\n TimeoutLayer::new(Duration::from_millis(10))\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":16,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {\n let app = Router::new().route(\n \"/\",\n get(forever.layer((\n HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }),\n timeout(),\n ))),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":32,"symbol":"handler_multiple_methods_first","kind":"function","lang":"rust","code":"async fn handler_multiple_methods_first() {\n let app = Router::new().route(\n \"/\",\n get(forever.layer((\n HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }),\n timeout(),\n )))\n .post(unit),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":49,"symbol":"handler_multiple_methods_middle","kind":"function","lang":"rust","code":"async fn handler_multiple_methods_middle() {\n let app = Router::new().route(\n \"/\",\n delete(unit)\n .get(forever.layer((\n HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }),\n timeout(),\n )))\n .post(unit),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":67,"symbol":"handler_multiple_methods_last","kind":"function","lang":"rust","code":"async fn handler_multiple_methods_last() {\n let app = Router::new().route(\n \"/\",\n delete(unit).get(forever.layer((\n HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT }),\n timeout(),\n ))),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n}"} {"repo":"axum","file":"axum/src/routing/tests/handle_error.rs","line":83,"symbol":"handler_service_ext","kind":"function","lang":"rust","code":"async fn handler_service_ext() {\n let fallible_service = tower::service_fn(|_| async { Err::<(), ()>(()) });\n let handle_error_service =\n fallible_service.handle_error(|_| async { StatusCode::INTERNAL_SERVER_ERROR });\n\n let app = Router::new().route(\"/\", get_service(handle_error_service));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":7,"symbol":"basic","kind":"function","lang":"rust","code":"async fn basic() {\n let one = Router::new()\n .route(\"/foo\", get(|| async {}))\n .route(\"/bar\", get(|| async {}));\n let two = Router::new().route(\"/baz\", get(|| async {}));\n let app = one.merge(two);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/qux\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":30,"symbol":"multiple_ors_balanced_differently","kind":"function","lang":"rust","code":"async fn multiple_ors_balanced_differently() {\n let one = Router::new().route(\"/one\", get(|| async { \"one\" }));\n let two = Router::new().route(\"/two\", get(|| async { \"two\" }));\n let three = Router::new().route(\"/three\", get(|| async { \"three\" }));\n let four = Router::new().route(\"/four\", get(|| async { \"four\" }));\n\n test(\n \"one\",\n one.clone()\n .merge(two.clone())\n .merge(three.clone())\n .merge(four.clone()),\n )\n .await;\n\n test(\n \"two\",\n one.clone()\n .merge(two.clone())\n .merge(three.clone().merge(four.clone())),\n )\n .await;\n\n test(\n \"three\",\n one.clone()\n .merge(two.clone().merge(three.clone()).merge(four.clone())),\n )\n .await;\n\n test(\"four\", one.merge(two.merge(three.merge(four)))).await;\n\n async fn test(name: &str, app: Router) {\n let client = TestClient::new(app);\n\n for n in [\"one\", \"two\", \"three\", \"four\"].iter() {\n println!(\"running: {name} / {n}\");\n let res = client.get(&format!(\"/{n}\")).await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, *n)"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":62,"symbol":"test","kind":"function","lang":"rust","code":"async fn test(name: &str, app: Router) {\n let client = TestClient::new(app);\n\n for n in [\"one\", \"two\", \"three\", \"four\"].iter() {\n println!(\"running: {name} / {n}\");\n let res = client.get(&format!(\"/{n}\")).await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, *n);\n }\n }"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":75,"symbol":"nested_or","kind":"function","lang":"rust","code":"async fn nested_or() {\n let bar = Router::new().route(\"/bar\", get(|| async { \"bar\" }));\n let baz = Router::new().route(\"/baz\", get(|| async { \"baz\" }));\n\n let bar_or_baz = bar.merge(baz);\n\n let client = TestClient::new(bar_or_baz.clone());\n assert_eq!(client.get(\"/bar\").await.text().await, \"bar\");\n assert_eq!(client.get(\"/baz\").await.text().await, \"baz\");\n\n let client = TestClient::new(Router::new().nest(\"/foo\", bar_or_baz));\n assert_eq!(client.get(\"/foo/bar\").await.text().await, \"bar\");\n assert_eq!(client.get(\"/foo/baz\").await.text().await, \"baz\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":91,"symbol":"or_with_route_following","kind":"function","lang":"rust","code":"async fn or_with_route_following() {\n let one = Router::new().route(\"/one\", get(|| async { \"one\" }));\n let two = Router::new().route(\"/two\", get(|| async { \"two\" }));\n let app = one.merge(two).route(\"/three\", get(|| async { \"three\" }));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/one\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/two\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/three\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":109,"symbol":"layer","kind":"function","lang":"rust","code":"async fn layer() {\n let one = Router::new().route(\"/foo\", get(|| async {}));\n let two = Router::new()\n .route(\"/bar\", get(|| async {}))\n .layer(ConcurrencyLimitLayer::new(10));\n let app = one.merge(two);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":126,"symbol":"layer_and_handle_error","kind":"function","lang":"rust","code":"async fn layer_and_handle_error() {\n let one = Router::new().route(\"/foo\", get(|| async {}));\n let two = Router::new()\n .route(\"/timeout\", get(std::future::pending::<()>))\n .layer(TimeoutLayer::with_status_code(\n StatusCode::REQUEST_TIMEOUT,\n Duration::from_millis(10),\n ));\n let app = one.merge(two);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/timeout\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":145,"symbol":"nesting","kind":"function","lang":"rust","code":"async fn nesting() {\n let one = Router::new().route(\"/foo\", get(|| async {}));\n let two = Router::new().nest(\"/bar\", Router::new().route(\"/baz\", get(|| async {})));\n let app = one.merge(two);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":157,"symbol":"boxed","kind":"function","lang":"rust","code":"async fn boxed() {\n let one = Router::new().route(\"/foo\", get(|| async {}));\n let two = Router::new().route(\"/bar\", get(|| async {}));\n let app = one.merge(two);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":169,"symbol":"many_ors","kind":"function","lang":"rust","code":"async fn many_ors() {\n let app = Router::new()\n .route(\"/r1\", get(|| async {}))\n .merge(Router::new().route(\"/r2\", get(|| async {})))\n .merge(Router::new().route(\"/r3\", get(|| async {})))\n .merge(Router::new().route(\"/r4\", get(|| async {})))\n .merge(Router::new().route(\"/r5\", get(|| async {})))\n .merge(Router::new().route(\"/r6\", get(|| async {})))\n .merge(Router::new().route(\"/r7\", get(|| async {})));\n\n let client = TestClient::new(app);\n\n for n in 1..=7 {\n let res = client.get(&format!(\"/r{n}\")).await;\n assert_eq!(res.status(), StatusCode::OK);\n }\n\n let res = client.get(\"/r8\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":191,"symbol":"services","kind":"function","lang":"rust","code":"async fn services() {\n use crate::routing::get_service;\n\n let app = Router::new()\n .route(\n \"/foo\",\n get_service(service_fn(|_: Request| async {\n Ok::<_, Infallible>(Response::new(Body::empty()))\n })),\n )\n .merge(Router::new().route(\n \"/bar\",\n get_service(service_fn(|_: Request| async {\n Ok::<_, Infallible>(Response::new(Body::empty()))\n })),\n ));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":217,"symbol":"all_the_uris","kind":"function","lang":"rust","code":"async fn all_the_uris(\n uri: Uri,\n OriginalUri(original_uri): OriginalUri,\n req: Request,\n) -> impl IntoResponse {\n Json(json!({\n \"uri\": uri.to_string(),\n \"request_uri\": req.uri().to_string(),\n \"original_uri\": original_uri.to_string(),\n }))\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":230,"symbol":"nesting_and_seeing_the_right_uri","kind":"function","lang":"rust","code":"async fn nesting_and_seeing_the_right_uri() {\n let one = Router::new().nest(\"/foo/\", Router::new().route(\"/bar\", get(all_the_uris)));\n let two = Router::new().route(\"/foo\", get(all_the_uris));\n\n let client = TestClient::new(one.merge(two));\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/bar\",\n \"request_uri\": \"/bar\",\n \"original_uri\": \"/foo/bar\",\n })\n );\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/foo\",\n \"request_uri\": \"/foo\",\n \"original_uri\": \"/foo\",\n })\n );\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":260,"symbol":"nesting_and_seeing_the_right_uri_at_more_levels_of_nesting","kind":"function","lang":"rust","code":"async fn nesting_and_seeing_the_right_uri_at_more_levels_of_nesting() {\n let one = Router::new().nest(\n \"/foo/\",\n Router::new().nest(\"/bar\", Router::new().route(\"/baz\", get(all_the_uris))),\n );\n let two = Router::new().route(\"/foo\", get(all_the_uris));\n\n let client = TestClient::new(one.merge(two));\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/baz\",\n \"request_uri\": \"/baz\",\n \"original_uri\": \"/foo/bar/baz\",\n })\n );\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/foo\",\n \"request_uri\": \"/foo\",\n \"original_uri\": \"/foo\",\n })\n );\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":293,"symbol":"nesting_and_seeing_the_right_uri_ors_with_nesting","kind":"function","lang":"rust","code":"async fn nesting_and_seeing_the_right_uri_ors_with_nesting() {\n let one = Router::new().nest(\n \"/one\",\n Router::new().nest(\"/bar\", Router::new().route(\"/baz\", get(all_the_uris))),\n );\n let two = Router::new().nest(\"/two\", Router::new().route(\"/qux\", get(all_the_uris)));\n let three = Router::new().route(\"/three\", get(all_the_uris));\n\n let client = TestClient::new(one.merge(two).merge(three));\n\n let res = client.get(\"/one/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/baz\",\n \"request_uri\": \"/baz\",\n \"original_uri\": \"/one/bar/baz\",\n })\n );\n\n let res = client.get(\"/two/qux\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/qux\",\n \"request_uri\": \"/qux\",\n \"original_uri\": \"/two/qux\",\n })\n );\n\n let res = client.get(\"/three\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/three\",\n \"request_uri\": "} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":338,"symbol":"nesting_and_seeing_the_right_uri_ors_with_multi_segment_uris","kind":"function","lang":"rust","code":"async fn nesting_and_seeing_the_right_uri_ors_with_multi_segment_uris() {\n let one = Router::new().nest(\n \"/one\",\n Router::new().nest(\"/foo\", Router::new().route(\"/bar\", get(all_the_uris))),\n );\n let two = Router::new().route(\"/two/foo\", get(all_the_uris));\n\n let client = TestClient::new(one.merge(two));\n\n let res = client.get(\"/one/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/bar\",\n \"request_uri\": \"/bar\",\n \"original_uri\": \"/one/foo/bar\",\n })\n );\n\n let res = client.get(\"/two/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(\n res.json::().await,\n json!({\n \"uri\": \"/two/foo\",\n \"request_uri\": \"/two/foo\",\n \"original_uri\": \"/two/foo\",\n })\n );\n}"} {"repo":"axum","file":"axum/src/routing/tests/merge.rs","line":372,"symbol":"middleware_that_return_early","kind":"function","lang":"rust","code":"async fn middleware_that_return_early() {\n let private = Router::new()\n .route(\"/\", get(|| async {}))\n .layer(ValidateRequestHeaderLayer::bearer(\"password\"));\n\n let public = Router::new().route(\"/public\", get(|| async {}));\n\n let client = TestClient::new(private.merge(public));\n\n assert_eq!(client.get(\"/\").await.status(), StatusCode::UNAUTHORIZED);\n assert_eq!(\n client\n .get(\"/\")\n .header(\"authorization\", \"Bearer password\")\n .await\n .status(),\n StatusCode::OK\n );\n assert_eq!(\n client.get(\"/doesnt-exist\").await.status(),\n StatusCode::NOT_FOUND\n );\n assert_eq!(client.get(\"/public\").await.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":50,"symbol":"take_route_or_internal_error_panics_on_second_call","kind":"function","lang":"rust","code":"fn take_route_or_internal_error_panics_on_second_call() {\n let route = super::Route::new(service_fn(|_req: Request| async move {\n Ok::<_, Infallible>(\"ok\")\n }));\n\n let mut service = Some(route);\n let _ = super::take_route_or_internal_error(&mut service);\n\n let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\n let _ = super::take_route_or_internal_error(&mut service);\n }))\n .expect_err(\"take_route_or_internal_error should panic on the second call in debug mode\");\n\n let panic_message = panic\n .downcast_ref::<&str>()\n .copied()\n .or_else(|| panic.downcast_ref::().map(String::as_str))\n .unwrap_or(\"\");\n\n assert_eq!(panic_message, super::TAKE_ONCE_ROUTE_PANIC_MSG);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":73,"symbol":"hello_world","kind":"function","lang":"rust","code":"async fn hello_world() {\n async fn root(_: Request) -> &'static str {\n \"Hello, World!\"\n }\n\n async fn foo(_: Request) -> &'static str {\n \"foo\"\n }\n\n async fn users_create(_: Request) -> &'static str {\n \"users#create\"\n }\n\n let app = Router::new()\n .route(\"/\", get(root).post(foo))\n .route(\"/users\", post(users_create));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"Hello, World!\");\n\n let res = client.post(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"foo\");\n\n let res = client.post(\"/users\").await;\n let body = res.text().await;\n assert_eq!(body, \"users#create\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":74,"symbol":"root","kind":"function","lang":"rust","code":"async fn root(_: Request) -> &'static str {\n \"Hello, World!\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":78,"symbol":"foo","kind":"function","lang":"rust","code":"async fn foo(_: Request) -> &'static str {\n \"foo\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":82,"symbol":"users_create","kind":"function","lang":"rust","code":"async fn users_create(_: Request) -> &'static str {\n \"users#create\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":106,"symbol":"routing","kind":"function","lang":"rust","code":"async fn routing() {\n let app = Router::new()\n .route(\n \"/users\",\n get(|_: Request| async { \"users#index\" }).post(|_: Request| async { \"users#create\" }),\n )\n .route(\"/users/{id}\", get(|_: Request| async { \"users#show\" }))\n .route(\n \"/users/{id}/action\",\n get(|_: Request| async { \"users#action\" }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"users#index\");\n\n let res = client.post(\"/users\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"users#create\");\n\n let res = client.get(\"/users/1\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"users#show\");\n\n let res = client.get(\"/users/1/action\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"users#action\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":141,"symbol":"router_type_doesnt_change","kind":"function","lang":"rust","code":"async fn router_type_doesnt_change() {\n let app: Router = Router::new()\n .route(\n \"/\",\n on(MethodFilter::GET, |_: Request| async { \"hi from GET\" })\n .on(MethodFilter::POST, |_: Request| async { \"hi from POST\" }),\n )\n .layer(tower_http::trace::TraceLayer::new_for_http());\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"hi from GET\");\n\n let res = client.post(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"hi from POST\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":162,"symbol":"routing_between_services","kind":"function","lang":"rust","code":"async fn routing_between_services() {\n use std::convert::Infallible;\n use tower::service_fn;\n\n async fn handle(_: Request) -> &'static str {\n \"handler\"\n }\n\n let app = Router::new()\n .route(\n \"/one\",\n get_service(service_fn(|_: Request| async {\n Ok::<_, Infallible>(Response::new(Body::from(\"one get\")))\n }))\n .post_service(service_fn(|_: Request| async {\n Ok::<_, Infallible>(Response::new(Body::from(\"one post\")))\n }))\n .on_service(\n MethodFilter::PUT,\n service_fn(|_: Request| async {\n Ok::<_, Infallible>(Response::new(Body::from(\"one put\")))\n }),\n ),\n )\n .route(\"/two\", on_service(MethodFilter::GET, handle.into_service()));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/one\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"one get\");\n\n let res = client.post(\"/one\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"one post\");\n\n let res = client.put(\"/one\").await;\n assert"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":166,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(_: Request) -> &'static str {\n \"handler\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":208,"symbol":"middleware_on_single_route","kind":"function","lang":"rust","code":"async fn middleware_on_single_route() {\n use tower_http::trace::TraceLayer;\n\n async fn handle(_: Request) -> &'static str {\n \"Hello, World!\"\n }\n\n let app = Router::new().route(\"/\", get(handle.layer(TraceLayer::new_for_http())));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n\n assert_eq!(body, \"Hello, World!\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":211,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(_: Request) -> &'static str {\n \"Hello, World!\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":226,"symbol":"service_in_bottom","kind":"function","lang":"rust","code":"async fn service_in_bottom() {\n async fn handler(_req: Request) -> Result, Infallible> {\n Ok(Response::new(Body::empty()))\n }\n\n let app = Router::new().route(\"/\", get_service(service_fn(handler)));\n\n TestClient::new(app);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":227,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_req: Request) -> Result, Infallible> {\n Ok(Response::new(Body::empty()))\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":237,"symbol":"wrong_method_handler","kind":"function","lang":"rust","code":"async fn wrong_method_handler() {\n let app = Router::new()\n .route(\"/\", get(|| async {}).post(|| async {}))\n .route(\"/foo\", patch(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.patch(\"/\").await;\n assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(res.headers()[ALLOW], \"GET,HEAD,POST\");\n\n let res = client.patch(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(res.headers()[ALLOW], \"PATCH\");\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":260,"symbol":"wrong_method_service","kind":"function","lang":"rust","code":"async fn wrong_method_service() {\n #[derive(Clone)]\n struct Svc;\n\n impl Service for Svc {\n type Response = Response;\n type Error = Infallible;\n type Future = Ready>;\n\n fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }\n\n fn call(&mut self, _req: R) -> Self::Future {\n ready(Ok(().into_response()))\n }\n }\n\n let app = Router::new()\n .route(\"/\", get_service(Svc).post_service(Svc))\n .route(\"/foo\", patch_service(Svc));\n\n let client = TestClient::new(app);\n\n let res = client.patch(\"/\").await;\n assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(res.headers()[ALLOW], \"GET,HEAD,POST\");\n\n let res = client.patch(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(res.headers()[ALLOW], \"PATCH\");\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":262,"symbol":"Svc","kind":"type","lang":"rust","code":"struct Svc;"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":269,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {\n Poll::Ready(Ok(()))\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":273,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, _req: R) -> Self::Future {\n ready(Ok(().into_response()))\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":300,"symbol":"multiple_methods_for_one_handler","kind":"function","lang":"rust","code":"async fn multiple_methods_for_one_handler() {\n async fn root(_: Request) -> &'static str {\n \"Hello, World!\"\n }\n\n let app = Router::new().route(\"/\", on(MethodFilter::GET.or(MethodFilter::POST), root));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":301,"symbol":"root","kind":"function","lang":"rust","code":"async fn root(_: Request) -> &'static str {\n \"Hello, World!\"\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":317,"symbol":"wildcard_sees_whole_url","kind":"function","lang":"rust","code":"async fn wildcard_sees_whole_url() {\n let app = Router::new().route(\n \"/api/{*rest}\",\n get(|uri: Uri| async move { uri.to_string() }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/api/foo/bar\").await;\n assert_eq!(res.text().await, \"/api/foo/bar\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":330,"symbol":"middleware_applies_to_routes_above","kind":"function","lang":"rust","code":"async fn middleware_applies_to_routes_above() {\n let app = Router::new()\n .route(\"/one\", get(std::future::pending::<()>))\n .layer(TimeoutLayer::with_status_code(\n StatusCode::REQUEST_TIMEOUT,\n Duration::ZERO,\n ))\n .route(\"/two\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/one\").await;\n assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);\n\n let res = client.get(\"/two\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":349,"symbol":"not_found_for_extra_trailing_slash","kind":"function","lang":"rust","code":"async fn not_found_for_extra_trailing_slash() {\n let app = Router::new().route(\"/foo\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":362,"symbol":"not_found_for_missing_trailing_slash","kind":"function","lang":"rust","code":"async fn not_found_for_missing_trailing_slash() {\n let app = Router::new().route(\"/foo/\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":372,"symbol":"with_and_without_trailing_slash","kind":"function","lang":"rust","code":"async fn with_and_without_trailing_slash() {\n let app = Router::new()\n .route(\"/foo\", get(|| async { \"without tsr\" }))\n .route(\"/foo/\", get(|| async { \"with tsr\" }));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"with tsr\");\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"without tsr\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":390,"symbol":"wildcard_doesnt_match_just_trailing_slash","kind":"function","lang":"rust","doc":"for https://github.com/tokio-rs/axum/issues/420","code":"async fn wildcard_doesnt_match_just_trailing_slash() {\n let app = Router::new().route(\n \"/x/{*path}\",\n get(|Path(path): Path| async move { path }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/x\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/x/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/x/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"foo/bar\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":410,"symbol":"what_matches_wildcard","kind":"function","lang":"rust","code":"async fn what_matches_wildcard() {\n let app = Router::new()\n .route(\"/{*key}\", get(|| async { \"root\" }))\n .route(\"/x/{*key}\", get(|| async { \"x\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n let get = |path| {\n let f = client.get(path);\n async move { f.await.text().await }\n };\n\n assert_eq!(get(\"/\").await, \"fallback\");\n assert_eq!(get(\"/a\").await, \"root\");\n assert_eq!(get(\"/a/\").await, \"root\");\n assert_eq!(get(\"/a/b\").await, \"root\");\n assert_eq!(get(\"/a/b/\").await, \"root\");\n\n assert_eq!(get(\"/x\").await, \"root\");\n assert_eq!(get(\"/x/\").await, \"root\");\n assert_eq!(get(\"/x/a\").await, \"x\");\n assert_eq!(get(\"/x/a/\").await, \"x\");\n assert_eq!(get(\"/x/a/b\").await, \"x\");\n assert_eq!(get(\"/x/a/b/\").await, \"x\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":438,"symbol":"prefix_match","kind":"function","lang":"rust","code":"async fn prefix_match() {\n let app = Router::new()\n .route(\"/{picture}.png\", get(|| async { \"picture\" }))\n .route(\"/{picture}.txt\", get(|| async { \"text\" }))\n .route(\"/logo.svg\", get(|| async { \"logo\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n let get = |path| {\n let f = client.get(path);\n async move { f.await.text().await }\n };\n\n assert_eq!(get(\"/\").await, \"fallback\");\n assert_eq!(get(\"/a/b.png\").await, \"fallback\");\n assert_eq!(get(\"/a.png/\").await, \"fallback\");\n assert_eq!(get(\"//a.png\").await, \"fallback\");\n\n // Empty capture is not allowed\n assert_eq!(get(\"/.png\").await, \"fallback\");\n assert_eq!(get(\"/..png\").await, \"picture\");\n assert_eq!(get(\"/a.png\").await, \"picture\");\n assert_eq!(get(\"/b.png\").await, \"picture\");\n\n assert_eq!(get(\"/.txt\").await, \"fallback\");\n assert_eq!(get(\"/..txt\").await, \"text\");\n assert_eq!(get(\"/a.txt\").await, \"text\");\n assert_eq!(get(\"/b.txt\").await, \"text\");\n\n assert_eq!(get(\"/logo.svg\").await, \"logo\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":472,"symbol":"suffix_match","kind":"function","lang":"rust","code":"async fn suffix_match() {\n let app = Router::new()\n .route(\"/new-{id}\", get(|| async { \"new\" }))\n .route(\"/old-{id}\", get(|| async { \"old\" }))\n .route(\"/any\", get(|| async { \"any\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n let get = |path| {\n let f = client.get(path);\n async move { f.await.text().await }\n };\n\n assert_eq!(get(\"/\").await, \"fallback\");\n assert_eq!(get(\"/a/new-1\").await, \"fallback\");\n assert_eq!(get(\"/new-1/\").await, \"fallback\");\n assert_eq!(get(\"//new-1/\").await, \"fallback\");\n\n // Empty capture is not allowed\n assert_eq!(get(\"/new-\").await, \"fallback\");\n assert_eq!(get(\"/new-1\").await, \"new\");\n\n assert_eq!(get(\"/old-\").await, \"fallback\");\n assert_eq!(get(\"/old-1\").await, \"old\");\n\n assert_eq!(get(\"/any\").await, \"any\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":502,"symbol":"prefix_suffix_match","kind":"function","lang":"rust","code":"async fn prefix_suffix_match() {\n let app = Router::new()\n .route(\"/start-{regex}-end\", get(|| async { \"regex\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n let get = |path| {\n let f = client.get(path);\n async move { f.await.text().await }\n };\n\n assert_eq!(get(\"/\").await, \"fallback\");\n\n // Empty capture is not allowed\n assert_eq!(get(\"/start--end\").await, \"fallback\");\n\n assert_eq!(get(\"/start-regex-end\").await, \"regex\");\n assert_eq!(get(\"/foo/start-regex-end\").await, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":524,"symbol":"prefix_suffix_nested_match","kind":"function","lang":"rust","code":"async fn prefix_suffix_nested_match() {\n let app = Router::new()\n .route(\"/{a}/a\", get(|| async { \"a\" }))\n .route(\"/{b}/b\", get(|| async { \"b\" }))\n .route(\"/a{c}c/a\", get(|| async { \"c\" }))\n .route(\"/a{d}c/{*anything}\", get(|| async { \"d\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(app);\n\n let get = |path| {\n let f = client.get(path);\n async move { f.await.text().await }\n };\n\n assert_eq!(get(\"/ac/a\").await, \"a\");\n assert_eq!(get(\"/ac/b\").await, \"b\");\n assert_eq!(get(\"/abc/a\").await, \"c\");\n assert_eq!(get(\"/abc/b\").await, \"d\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":549,"symbol":"colliding_fallback_with_wildcard","kind":"function","lang":"rust","code":"fn colliding_fallback_with_wildcard() {\n _ = Router::<()>::new()\n .fallback(|| async { \"fallback\" })\n .route(\"/{*wild}\", get(|| async { \"wildcard\" }));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":559,"symbol":"colliding_prefix_suffix","kind":"function","lang":"rust","code":"fn colliding_prefix_suffix() {\n _ = Router::<()>::new()\n .route(\"/foo-{wild}\", get(|| async { \"wildcard\" }))\n .route(\"/foo\", get(|| async { \"wildcard\" }))\n .route(\"/{wild}\", get(|| async { \"wildcard\" }))\n .route(\"/{wild}-bar\", get(|| async { \"wildcard\" }));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":571,"symbol":"colliding_prefixsuffix_prefix","kind":"function","lang":"rust","code":"fn colliding_prefixsuffix_prefix() {\n _ = Router::<()>::new()\n .route(\"/foo-{wild}-bar\", get(|| async { \"wildcard\" }))\n .route(\"/foo\", get(|| async { \"wildcard\" }))\n .route(\"/{wild}\", get(|| async { \"wildcard\" }))\n .route(\"/foo-{wild}\", get(|| async { \"wildcard\" }));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":583,"symbol":"colliding_prefixsuffix_suffix","kind":"function","lang":"rust","code":"fn colliding_prefixsuffix_suffix() {\n _ = Router::<()>::new()\n .route(\"/foo-{wild}-bar\", get(|| async { \"wildcard\" }))\n .route(\"/foo\", get(|| async { \"wildcard\" }))\n .route(\"/{wild}\", get(|| async { \"wildcard\" }))\n .route(\"/{wild}-bar\", get(|| async { \"wildcard\" }));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":593,"symbol":"colliding_wildcard_with_fallback","kind":"function","lang":"rust","doc":"We might want to reject this too","code":"async fn colliding_wildcard_with_fallback() {\n let router = Router::new()\n .route(\"/{*wild}\", get(|| async { \"wildcard\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"fallback\");\n\n let res = client.get(\"/x\").await;\n let body = res.text().await;\n assert_eq!(body, \"wildcard\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":611,"symbol":"colliding_fallback_with_fallback","kind":"function","lang":"rust","doc":"We might want to reject this too","code":"async fn colliding_fallback_with_fallback() {\n let router = Router::new()\n .fallback(|| async { \"fallback1\" })\n .fallback(|| async { \"fallback2\" });\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"fallback1\");\n\n let res = client.get(\"/x\").await;\n let body = res.text().await;\n assert_eq!(body, \"fallback1\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":628,"symbol":"colliding_root_with_fallback","kind":"function","lang":"rust","code":"async fn colliding_root_with_fallback() {\n let router = Router::new()\n .route(\"/\", get(|| async { \"root\" }))\n .fallback(|| async { \"fallback\" });\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"root\");\n\n let res = client.get(\"/x\").await;\n let body = res.text().await;\n assert_eq!(body, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":645,"symbol":"colliding_fallback_with_root","kind":"function","lang":"rust","code":"async fn colliding_fallback_with_root() {\n let router = Router::new()\n .fallback(|| async { \"fallback\" })\n .route(\"/\", get(|| async { \"root\" }));\n\n let client = TestClient::new(router);\n\n // This works because fallback registers `any` so the `get` gets merged into it.\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"root\");\n\n let res = client.get(\"/x\").await;\n let body = res.text().await;\n assert_eq!(body, \"fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":663,"symbol":"static_and_dynamic_paths","kind":"function","lang":"rust","code":"async fn static_and_dynamic_paths() {\n let app = Router::new()\n .route(\n \"/{key}\",\n get(|Path(key): Path| async move { format!(\"dynamic: {key}\") }),\n )\n .route(\"/foo\", get(|| async { \"static\" }));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.text().await, \"dynamic: bar\");\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.text().await, \"static\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":682,"symbol":"empty_route","kind":"function","lang":"rust","code":"async fn empty_route() {\n let app = Router::new().route(\"\", get(|| async {}));\n TestClient::new(app);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":688,"symbol":"middleware_still_run_for_unmatched_requests","kind":"function","lang":"rust","code":"async fn middleware_still_run_for_unmatched_requests() {\n #[derive(Clone)]\n struct CountMiddleware(S);\n\n static COUNT: AtomicUsize = AtomicUsize::new(0);\n\n impl Service for CountMiddleware\n where\n S: Service,\n {\n type Response = S::Response;\n type Error = S::Error;\n type Future = S::Future;\n\n fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.0.poll_ready(cx)\n }\n\n fn call(&mut self, req: R) -> Self::Future {\n COUNT.fetch_add(1, Ordering::SeqCst);\n self.0.call(req)\n }\n }\n\n let app = Router::new()\n .route(\"/\", get(|| async {}))\n .layer(tower::layer::layer_fn(CountMiddleware));\n\n let client = TestClient::new(app);\n\n assert_eq!(COUNT.load(Ordering::SeqCst), 0);\n\n client.get(\"/\").await;\n assert_eq!(COUNT.load(Ordering::SeqCst), 1);\n\n client.get(\"/not-found\").await;\n assert_eq!(COUNT.load(Ordering::SeqCst), 2);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":690,"symbol":"CountMiddleware","kind":"type","lang":"rust","code":"struct CountMiddleware(S);"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":702,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.0.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":706,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: R) -> Self::Future {\n COUNT.fetch_add(1, Ordering::SeqCst);\n self.0.call(req)\n }"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":732,"symbol":"routing_to_router_panics","kind":"function","lang":"rust","code":"async fn routing_to_router_panics() {\n TestClient::new(Router::new().route_service(\"/\", Router::new()));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":738,"symbol":"route_layer","kind":"function","lang":"rust","code":"async fn route_layer() {\n let app = Router::new()\n .route(\"/foo\", get(|| async {}))\n .route_layer(ValidateRequestHeaderLayer::bearer(\"password\"));\n\n let client = TestClient::new(app);\n\n let res = client\n .get(\"/foo\")\n .header(\"authorization\", \"Bearer password\")\n .await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::UNAUTHORIZED);\n\n let res = client.get(\"/not-found\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n // it would be nice if this would return `405 Method Not Allowed`\n // but that requires knowing more about which method route we're calling, which we\n // don't know currently since it's just a generic `Service`\n let res = client.post(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::UNAUTHORIZED);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":765,"symbol":"different_methods_added_in_different_routes","kind":"function","lang":"rust","code":"async fn different_methods_added_in_different_routes() {\n let app = Router::new()\n .route(\"/\", get(|| async { \"GET\" }))\n .route(\"/\", post(|| async { \"POST\" }));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"GET\");\n\n let res = client.post(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"POST\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":783,"symbol":"merging_routers_with_fallbacks_panics","kind":"function","lang":"rust","code":"async fn merging_routers_with_fallbacks_panics() {\n async fn fallback() {}\n let one = Router::new().fallback(fallback);\n let two = Router::new().fallback(fallback);\n TestClient::new(one.merge(two));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":784,"symbol":"fallback","kind":"function","lang":"rust","code":"async fn fallback() {}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":792,"symbol":"routes_with_overlapping_method_routes","kind":"function","lang":"rust","code":"fn routes_with_overlapping_method_routes() {\n async fn handler() {}\n let _: Router = Router::new()\n .route(\"/foo/bar\", get(handler))\n .route(\"/foo/bar\", get(handler));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":793,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":801,"symbol":"merging_with_overlapping_method_routes","kind":"function","lang":"rust","code":"fn merging_with_overlapping_method_routes() {\n async fn handler() {}\n let app: Router = Router::new().route(\"/foo/bar\", get(handler));\n _ = app.clone().merge(app);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":802,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":808,"symbol":"merging_routers_with_same_paths_but_different_methods","kind":"function","lang":"rust","code":"async fn merging_routers_with_same_paths_but_different_methods() {\n let one = Router::new().route(\"/\", get(|| async { \"GET\" }));\n let two = Router::new().route(\"/\", post(|| async { \"POST\" }));\n\n let client = TestClient::new(one.merge(two));\n\n let res = client.get(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"GET\");\n\n let res = client.post(\"/\").await;\n let body = res.text().await;\n assert_eq!(body, \"POST\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":824,"symbol":"head_content_length_through_hyper_server","kind":"function","lang":"rust","code":"async fn head_content_length_through_hyper_server() {\n let app = Router::new()\n .route(\"/\", get(|| async { \"foo\" }))\n .route(\"/json\", get(|| async { Json(json!({ \"foo\": 1 })) }));\n\n let client = TestClient::new(app);\n\n let res = client.head(\"/\").await;\n assert_eq!(res.headers()[\"content-length\"], \"3\");\n assert!(res.text().await.is_empty());\n\n let res = client.head(\"/json\").await;\n assert_eq!(res.headers()[\"content-length\"], \"9\");\n assert!(res.text().await.is_empty());\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":841,"symbol":"head_content_length_through_hyper_server_that_hits_fallback","kind":"function","lang":"rust","code":"async fn head_content_length_through_hyper_server_that_hits_fallback() {\n let app = Router::new().fallback(|| async { \"foo\" });\n\n let client = TestClient::new(app);\n\n let res = client.head(\"/\").await;\n assert_eq!(res.headers()[\"content-length\"], \"3\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":851,"symbol":"head_with_middleware_applied","kind":"function","lang":"rust","code":"async fn head_with_middleware_applied() {\n use tower_http::compression::{predicate::SizeAbove, CompressionLayer};\n\n let app = Router::new()\n .nest(\n \"/foo\",\n Router::new().route(\"/\", get(|| async { \"Hello, World!\" })),\n )\n .layer(CompressionLayer::new().compress_when(SizeAbove::new(0)));\n\n let client = TestClient::new(app);\n\n // send GET request\n let res = client.get(\"/foo\").header(\"accept-encoding\", \"gzip\").await;\n assert_eq!(res.headers()[\"transfer-encoding\"], \"chunked\");\n // cannot have `transfer-encoding: chunked` and `content-length`\n assert!(!res.headers().contains_key(\"content-length\"));\n\n // send HEAD request\n let res = client.head(\"/foo\").header(\"accept-encoding\", \"gzip\").await;\n // no response body so no `transfer-encoding`\n assert!(!res.headers().contains_key(\"transfer-encoding\"));\n // no content-length since we cannot know it since the response\n // is compressed\n assert!(!res.headers().contains_key(\"content-length\"));\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":880,"symbol":"routes_must_start_with_slash","kind":"function","lang":"rust","code":"async fn routes_must_start_with_slash() {\n let app = Router::new().route(\":foo\", get(|| async {}));\n TestClient::new(app);\n}"} {"repo":"axum","file":"axum/src/routing/tests/mod.rs","line":886,"symbol":"body_limited_by_default","kind":"function","lang":"rust","code":"async fn body_limited_by_default() {\n let app = Router::new()\n .route(\"/bytes\", post(|_: Bytes| async {}))\n .route(\"/string\", post(|_: String| async {}))\n .route(\"/json\", post(|_: Json| async {}));\n\n let client = TestClient::new(app);\n\n for uri in [\"/bytes\", \"/string\", \"/json\"] {\n println!(\"calling {uri}\");\n\n let stream = futures_util::stream::repeat(\"a\".repeat(1000)).map(Ok::<_, hyper::Error>);\n let body = reqwest::Body::wrap_stream(stream);\n\n let res_future = client\n .post(uri)\n .header(\"content-type\", \"application/json\")\n .body(body)\n .into_future();\n let res = tokio::time::timeout(Duration::from_secs(3), res_future)\n .await\n .expect(\"never got response\");\n\n assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);\n }\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":6,"symbol":"nesting_apps","kind":"function","lang":"rust","code":"async fn nesting_apps() {\n let api_routes = Router::new()\n .route(\n \"/users\",\n get(|| async { \"users#index\" }).post(|| async { \"users#create\" }),\n )\n .route(\n \"/users/{id}\",\n get(\n |params: extract::Path>| async move {\n format!(\n \"{}: users#show ({})\",\n params.get(\"version\").unwrap(),\n params.get(\"id\").unwrap()\n )\n },\n ),\n )\n .route(\n \"/games/{id}\",\n get(\n |params: extract::Path>| async move {\n format!(\n \"{}: games#show ({})\",\n params.get(\"version\").unwrap(),\n params.get(\"id\").unwrap()\n )\n },\n ),\n );\n\n let app = Router::new()\n .route(\"/\", get(|| async { \"hi\" }))\n .nest(\"/{version}/api\", api_routes);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":61,"symbol":"wrong_method_nest","kind":"function","lang":"rust","code":"async fn wrong_method_nest() {\n let nested_app = Router::new().route(\"/\", get(|| async {}));\n let app = Router::new().nest(\"/foo\", nested_app);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.post(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);\n assert_eq!(res.headers()[ALLOW], \"GET,HEAD\");\n\n let res = client.patch(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":80,"symbol":"nest_router_at_root","kind":"function","lang":"rust","code":"fn nest_router_at_root() {\n let nested = Router::new().route(\"/foo\", get(|| async {}));\n let _: Router = Router::new().nest(\"/\", nested);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":87,"symbol":"nest_router_at_empty_path","kind":"function","lang":"rust","code":"fn nest_router_at_empty_path() {\n let nested = Router::new().route(\"/foo\", get(|| async {}));\n let _: Router = Router::new().nest(\"\", nested);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":96,"symbol":"nest_service_at_root","kind":"function","lang":"rust","code":"fn nest_service_at_root() {\n let _: Router = Router::new().nest_service(\"/\", get(|| async {}));\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":104,"symbol":"nest_service_at_empty_path","kind":"function","lang":"rust","code":"fn nest_service_at_empty_path() {\n let _: Router = Router::new().nest_service(\"\", get(|| async {}));\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":110,"symbol":"nest_no_slash","kind":"function","lang":"rust","code":"fn nest_no_slash() {\n let _: Router = Router::new().nest(\"x\", Router::new());\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":116,"symbol":"nest_service_no_slash","kind":"function","lang":"rust","code":"fn nest_service_no_slash() {\n let _: Router = Router::new().nest_service(\"x\", get(|| async {}));\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":121,"symbol":"nested_url_extractor","kind":"function","lang":"rust","code":"async fn nested_url_extractor() {\n let app = Router::new().nest(\n \"/foo\",\n Router::new().nest(\n \"/bar\",\n Router::new()\n .route(\"/baz\", get(|uri: Uri| async move { uri.to_string() }))\n .route(\n \"/qux\",\n get(|req: Request| async move { req.uri().to_string() }),\n ),\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/baz\");\n\n let res = client.get(\"/foo/bar/qux\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/qux\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":147,"symbol":"nested_url_original_extractor","kind":"function","lang":"rust","code":"async fn nested_url_original_extractor() {\n let app = Router::new().nest(\n \"/foo\",\n Router::new().nest(\n \"/bar\",\n Router::new().route(\n \"/baz\",\n get(|uri: extract::OriginalUri| async move { uri.0.to_string() }),\n ),\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/foo/bar/baz\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":167,"symbol":"nested_service_sees_stripped_uri","kind":"function","lang":"rust","code":"async fn nested_service_sees_stripped_uri() {\n let app = Router::new().nest(\n \"/foo\",\n Router::new().nest(\n \"/bar\",\n Router::new().route_service(\n \"/baz\",\n service_fn(|req: Request| async move {\n let body = Body::from(req.uri().to_string());\n Ok::<_, Infallible>(Response::new(body))\n }),\n ),\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar/baz\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"/baz\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":190,"symbol":"nest_static_file_server","kind":"function","lang":"rust","code":"async fn nest_static_file_server() {\n let app = Router::new().nest_service(\"/static\", ServeDir::new(\".\"));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/static/README.md\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":200,"symbol":"nested_multiple_routes","kind":"function","lang":"rust","code":"async fn nested_multiple_routes() {\n let app = Router::new()\n .nest(\n \"/api\",\n Router::new()\n .route(\"/users\", get(|| async { \"users\" }))\n .route(\"/teams\", get(|| async { \"teams\" })),\n )\n .route(\"/\", get(|| async { \"root\" }));\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/\").await.text().await, \"root\");\n assert_eq!(client.get(\"/api/users\").await.text().await, \"users\");\n assert_eq!(client.get(\"/api/teams\").await.text().await, \"teams\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":218,"symbol":"multiple_top_level_nests","kind":"function","lang":"rust","code":"async fn multiple_top_level_nests() {\n let app = Router::new()\n .nest(\n \"/one\",\n Router::new().route(\"/route\", get(|| async { \"one\" })),\n )\n .nest(\n \"/two\",\n Router::new().route(\"/route\", get(|| async { \"two\" })),\n );\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/one/route\").await.text().await, \"one\");\n assert_eq!(client.get(\"/two/route\").await.text().await, \"two\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":237,"symbol":"nest_cannot_contain_wildcards","kind":"function","lang":"rust","code":"async fn nest_cannot_contain_wildcards() {\n _ = Router::<()>::new().nest(\"/one/{*rest}\", Router::new());\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":242,"symbol":"outer_middleware_still_see_whole_url","kind":"function","lang":"rust","code":"async fn outer_middleware_still_see_whole_url() {\n #[derive(Clone)]\n struct SetUriExtension(S);\n\n #[derive(Clone)]\n struct Uri(http::Uri);\n\n impl Service> for SetUriExtension\n where\n S: Service>,\n {\n type Response = S::Response;\n type Error = S::Error;\n type Future = S::Future;\n\n fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.0.poll_ready(cx)\n }\n\n fn call(&mut self, mut req: Request) -> Self::Future {\n let uri = Uri(req.uri().clone());\n req.extensions_mut().insert(uri);\n self.0.call(req)\n }\n }\n\n async fn handler(Extension(Uri(middleware_uri)): Extension) -> impl IntoResponse {\n middleware_uri.to_string()\n }\n\n let app = Router::new()\n .route(\"/\", get(handler))\n .route(\"/foo\", get(handler))\n .route(\"/foo/bar\", get(handler))\n .nest(\"/one\", Router::new().route(\"/two\", get(handler)))\n .fallback(handler)\n .layer(tower::layer::layer_fn(SetUriExtension));\n\n let client = TestClient::new(app);\n\n assert_eq!(client.get(\"/\").awa"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":244,"symbol":"SetUriExtension","kind":"type","lang":"rust","code":"struct SetUriExtension(S);"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":247,"symbol":"Uri","kind":"type","lang":"rust","code":"struct Uri(http::Uri);"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":257,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.0.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":261,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, mut req: Request) -> Self::Future {\n let uri = Uri(req.uri().clone());\n req.extensions_mut().insert(uri);\n self.0.call(req)\n }"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":268,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(Extension(Uri(middleware_uri)): Extension) -> impl IntoResponse {\n middleware_uri.to_string()\n }"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":290,"symbol":"nest_at_capture","kind":"function","lang":"rust","code":"async fn nest_at_capture() {\n let api_routes = Router::new().route(\n \"/{b}\",\n get(|Path((a, b)): Path<(String, String)>| async move { format!(\"a={a} b={b}\") }),\n );\n\n let app = Router::new().nest(\"/{a}\", api_routes);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"a=foo b=bar\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":307,"symbol":"nest_at_prefix_capture","kind":"function","lang":"rust","doc":"Not `crate::test` because `nest_service` would fail.","code":"async fn nest_at_prefix_capture() {\n let empty_routes = Router::new();\n let api_routes = Router::new().route(\n \"/{b}\",\n get(|Path((a, b)): Path<(String, String)>| async move { format!(\"a={a} b={b}\") }),\n );\n\n let app = Router::new()\n .nest(\"/x{a}x\", api_routes)\n .nest(\"/xax\", empty_routes);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/xax/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"a=a b=bar\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":326,"symbol":"nest_service_at_prefix_capture","kind":"function","lang":"rust","code":"async fn nest_service_at_prefix_capture() {\n let empty_routes = Router::new();\n let api_routes = Router::new().route(\n \"/{b}\",\n get(|Path((a, b)): Path<(String, String)>| async move { format!(\"a={a} b={b}\") }),\n );\n\n let app = Router::new()\n .nest_service(\"/x{a}\", api_routes)\n .nest_service(\"/xa\", empty_routes);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/xa/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":344,"symbol":"nest_service_at_prefix_suffix_capture","kind":"function","lang":"rust","code":"async fn nest_service_at_prefix_suffix_capture() {\n let empty_routes = Router::new();\n let api_routes = Router::new().route(\n \"/{b}\",\n get(|Path((a, b)): Path<(String, String)>| async move { format!(\"a={a} b={b}\") }),\n );\n\n let app = Router::new()\n .nest_service(\"/x{a}x\", api_routes)\n .nest_service(\"/xax\", empty_routes);\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/xax/bar\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":362,"symbol":"nest_with_and_without_trailing","kind":"function","lang":"rust","code":"async fn nest_with_and_without_trailing() {\n let app = Router::new().nest_service(\"/foo\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/foo/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/foo/bar\").await;\n assert_eq!(res.status(), StatusCode::OK);\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":378,"symbol":"nesting_with_root_inner_router","kind":"function","lang":"rust","code":"async fn nesting_with_root_inner_router() {\n let app = Router::new()\n .nest_service(\"/service\", Router::new().route(\"/\", get(|| async {})))\n .nest(\"/router\", Router::new().route(\"/\", get(|| async {})))\n .nest(\"/router-slash/\", Router::new().route(\"/\", get(|| async {})));\n\n let client = TestClient::new(app);\n\n // `/service/` does match the `/service` prefix and the remaining path is technically\n // empty, which is the same as `/` which matches `.route(\"/\", _)`\n let res = client.get(\"/service\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n // `/service/` does match the `/service` prefix and the remaining path is `/`\n // which matches `.route(\"/\", _)`\n //\n // this is perhaps a little surprising but don't think there is much we can do\n let res = client.get(\"/service/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n // at least it does work like you'd expect when using `nest`\n\n let res = client.get(\"/router\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/router/\").await;\n assert_eq!(res.status(), StatusCode::NOT_FOUND);\n\n let res = client.get(\"/router-slash\").await;\n ass"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":444,"symbol":"colon_in_nested_route","kind":"function","lang":"rust","code":"async fn colon_in_nested_route() {\n let router = Router::<()>::new().nest(\n \"/:foo\",\n Router::new().route(\"/foo\", get(|| async { \"foo\" })),\n );\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/:foo/foo\").await;\n let body = res.text().await;\n assert_eq!(body, \"foo\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":458,"symbol":"asterisk_in_nested_route","kind":"function","lang":"rust","code":"async fn asterisk_in_nested_route() {\n let router = Router::<()>::new().nest(\n \"/*foo\",\n Router::new().route(\"/foo\", get(|| async { \"foo\" })),\n );\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/*foo/foo\").await;\n let body = res.text().await;\n assert_eq!(body, \"foo\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":472,"symbol":"nesting_router_with_fallback","kind":"function","lang":"rust","code":"async fn nesting_router_with_fallback() {\n let nested = Router::new().fallback(|| async { \"nested\" });\n let router = Router::new().route(\"/{x}/{y}\", get(|| async { \"two segments\" }));\n\n let client = TestClient::new(router.nest(\"/nest\", nested));\n\n let res = client.get(\"/a/b\").await;\n let body = res.text().await;\n assert_eq!(body, \"two segments\");\n\n let res = client.get(\"/nest/b\").await;\n let body = res.text().await;\n assert_eq!(body, \"nested\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":488,"symbol":"defining_missing_routes_in_nested_router","kind":"function","lang":"rust","code":"async fn defining_missing_routes_in_nested_router() {\n let router = Router::new()\n .route(\"/nest/before\", get(|| async { \"before\" }))\n .nest(\n \"/nest\",\n Router::new()\n .route(\"/mid\", get(|| async { \"nested mid\" }))\n .fallback(|| async { \"nested fallback\" }),\n )\n .route(\"/nest/after\", get(|| async { \"after\" }));\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/nest/before\").await;\n let body = res.text().await;\n assert_eq!(body, \"before\");\n\n let res = client.get(\"/nest/after\").await;\n let body = res.text().await;\n assert_eq!(body, \"after\");\n\n let res = client.get(\"/nest/mid\").await;\n let body = res.text().await;\n assert_eq!(body, \"nested mid\");\n\n let res = client.get(\"/nest/fallback\").await;\n let body = res.text().await;\n assert_eq!(body, \"nested fallback\");\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":522,"symbol":"overriding_by_nested_router","kind":"function","lang":"rust","code":"fn overriding_by_nested_router() {\n _ = Router::<()>::new()\n .route(\"/nest/override\", get(|| async { \"outer\" }))\n .nest(\n \"/nest\",\n Router::new().route(\"/override\", get(|| async { \"inner\" })),\n );\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":535,"symbol":"overriding_nested_router_","kind":"function","lang":"rust","code":"fn overriding_nested_router_() {\n _ = Router::<()>::new()\n .nest(\n \"/nest\",\n Router::new().route(\"/override\", get(|| async { \"inner\" })),\n )\n .route(\"/nest/override\", get(|| async { \"outer\" }));\n}"} {"repo":"axum","file":"axum/src/routing/tests/nest.rs","line":546,"symbol":"overriding_nested_service_router","kind":"function","lang":"rust","doc":"This is just documenting current state, not intended behavior.","code":"async fn overriding_nested_service_router() {\n let router = Router::new()\n .route(\"/nest/before\", get(|| async { \"outer\" }))\n .nest_service(\n \"/nest\",\n Router::new()\n .route(\"/before\", get(|| async { \"inner\" }))\n .route(\"/after\", get(|| async { \"inner\" })),\n )\n .route(\"/nest/after\", get(|| async { \"outer\" }));\n\n let client = TestClient::new(router);\n\n let res = client.get(\"/nest/before\").await;\n let body = res.text().await;\n assert_eq!(body, \"outer\");\n\n let res = client.get(\"/nest/after\").await;\n let body = res.text().await;\n assert_eq!(body, \"outer\");\n}"} {"repo":"axum","file":"axum/src/routing/url_params.rs","line":7,"symbol":"UrlParams","kind":"type","lang":"rust","code":"pub(crate) enum UrlParams {\n Params {\n params: Vec<(Arc, PercentDecodedStr)>,\n inner_start: usize,\n },\n InvalidUtf8InPathParam {\n key: Arc,\n },\n}"} {"repo":"axum","file":"axum/src/routing/url_params.rs","line":17,"symbol":"insert_url_params","kind":"function","lang":"rust","code":"pub(super) fn insert_url_params(extensions: &mut Extensions, params: &Params<'_, '_>) {\n let current_params = extensions.get_mut();\n\n if let Some(UrlParams::InvalidUtf8InPathParam { .. }) = current_params {\n // nothing to do here since an error was stored earlier\n return;\n }\n\n let params = params\n .iter()\n .filter(|(key, _)| !key.starts_with(super::NEST_TAIL_PARAM))\n .filter(|(key, _)| !key.starts_with(super::FALLBACK_PARAM))\n .map(|(k, v)| {\n if let Some(decoded) = PercentDecodedStr::new(v) {\n Ok((Arc::from(k), decoded))\n } else {\n Err(Arc::from(k))\n }\n })\n .collect::, _>>();\n\n match (current_params, params) {\n (Some(UrlParams::InvalidUtf8InPathParam { .. }), _) => {\n unreachable!(\"we check for this state earlier in this method\")\n }\n (_, Err(invalid_key)) => {\n extensions.insert(UrlParams::InvalidUtf8InPathParam { key: invalid_key });\n }\n (\n Some(UrlParams::Params {\n params: current, ..\n }),\n Ok(params),\n ) => {\n c"} {"repo":"axum","file":"axum/src/routing/url_params.rs","line":62,"symbol":"advance_inner_start","kind":"function","lang":"rust","code":"pub(super) fn advance_inner_start(extensions: &mut Extensions, count: usize) {\n if let Some(UrlParams::Params { inner_start, .. }) = extensions.get_mut() {\n *inner_start += count;\n }\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":16,"symbol":"Listener","kind":"type","lang":"rust","doc":"Types that can listen for connections.","code":"pub trait Listener: Send + 'static {\n /// The listener's IO type.\n type Io: AsyncRead + AsyncWrite + Unpin + Send + 'static;\n\n /// The listener's address type.\n type Addr: Send;\n\n /// Accept a new incoming connection to this listener.\n ///\n /// If the underlying accept call can return an error, this function must\n /// take care of logging and retrying.\n fn accept(&mut self) -> impl Future + Send;\n\n /// Returns the local address that this listener is bound to.\n fn local_addr(&self) -> io::Result;\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":27,"symbol":"accept","kind":"function","lang":"rust","doc":"Accept a new incoming connection to this listener. If the underlying accept call can return an error, this function must take care of logging and retrying.","code":"fn accept(&mut self) -> impl Future + Send;"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":30,"symbol":"local_addr","kind":"function","lang":"rust","doc":"Returns the local address that this listener is bound to.","code":"fn local_addr(&self) -> io::Result;"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":38,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n loop {\n match Self::accept(self).await {\n Ok(tup) => return tup,\n Err(e) => handle_accept_error(e).await,\n }\n }\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":48,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> io::Result {\n Self::local_addr(self)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":58,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n loop {\n match Self::accept(self).await {\n Ok(tup) => return tup,\n Err(e) => handle_accept_error(e).await,\n }\n }\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":68,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> io::Result {\n Self::local_addr(self)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":74,"symbol":"ListenerExt","kind":"type","lang":"rust","doc":"Extensions to [`Listener`].","code":"pub trait ListenerExt: Listener + Sized {\n /// Limit the number of concurrent connections. Once the limit has\n /// been reached, no additional connections will be accepted until\n /// an existing connection is closed. Listener implementations will\n /// typically continue to queue incoming connections, up to an OS\n /// and implementation-specific listener backlog limit.\n ///\n /// Compare [`tower::limit::concurrency`], which provides ways to\n /// limit concurrent in-flight requests, but does not limit connections\n /// that are idle or in the process of sending request headers.\n ///\n /// [`tower::limit::concurrency`]: https://docs.rs/tower/latest/tower/limit/concurrency/\n fn limit_connections(self, limit: usize) -> ConnLimiter {\n ConnLimiter {\n listener: self,\n sem: Arc::new(Semaphore::new(limit)),\n }\n }\n\n /// Run a mutable closure on every accepted `Io`.\n ///\n /// # Example\n ///\n /// ```\n /// use axum::{Router, routing::get, serve::ListenerExt};\n /// use tracing::trace;\n ///\n /// # async {\n /// let router = Router::new().route(\"/\", get(|| async { \"Hello, World!\" }));\n ///\n"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":86,"symbol":"limit_connections","kind":"function","lang":"rust","doc":"Compare [`tower::limit::concurrency`], which provides ways to limit concurrent in-flight requests, but does not limit connections that are idle or in the process of sending request headers. [`tower::limit::concurrency`]: https://docs.rs/tower/latest/tower/limit/concurrency/","code":"fn limit_connections(self, limit: usize) -> ConnLimiter {\n ConnLimiter {\n listener: self,\n sem: Arc::new(Semaphore::new(limit)),\n }\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":115,"symbol":"tap_io","kind":"function","lang":"rust","doc":"trace!(\"failed to set TCP_NODELAY on incoming connection: {err:#}\"); } }); axum::serve(listener, router).await; # }; ```","code":"fn tap_io(self, tap_fn: F) -> TapIo\n where\n F: FnMut(&mut Self::Io) + Send + 'static,\n {\n TapIo {\n listener: self,\n tap_fn,\n }\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":132,"symbol":"ConnLimiter","kind":"type","lang":"rust","doc":"Return type of [`ListenerExt::limit_connections`]. See that method for details.","code":"pub struct ConnLimiter {\n listener: T,\n sem: Arc,\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":141,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n let permit = self.sem.clone().acquire_owned().await.unwrap();\n let (io, addr) = self.listener.accept().await;\n (ConnLimiterIo { io, permit }, addr)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":147,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> tokio::io::Result {\n self.listener.local_addr()\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":166,"symbol":"poll_read","kind":"function","lang":"rust","code":"fn poll_read(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n buf: &mut io::ReadBuf<'_>,\n ) -> Poll> {\n self.project().io.poll_read(cx, buf)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":177,"symbol":"is_write_vectored","kind":"function","lang":"rust","code":"fn is_write_vectored(&self) -> bool {\n self.io.is_write_vectored()\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":181,"symbol":"poll_flush","kind":"function","lang":"rust","code":"fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.project().io.poll_flush(cx)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":185,"symbol":"poll_shutdown","kind":"function","lang":"rust","code":"fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.project().io.poll_shutdown(cx)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":189,"symbol":"poll_write","kind":"function","lang":"rust","code":"fn poll_write(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n buf: &[u8],\n ) -> Poll> {\n self.project().io.poll_write(cx, buf)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":197,"symbol":"poll_write_vectored","kind":"function","lang":"rust","code":"fn poll_write_vectored(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n bufs: &[std::io::IoSlice<'_>],\n ) -> Poll> {\n self.project().io.poll_write_vectored(cx, bufs)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":209,"symbol":"TapIo","kind":"type","lang":"rust","doc":"Return type of [`ListenerExt::tap_io`]. See that method for details.","code":"pub struct TapIo {\n listener: L,\n tap_fn: F,\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":218,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"TapIo\")\n .field(\"listener\", &self.listener)\n .finish_non_exhaustive()\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":233,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n let (mut io, addr) = self.listener.accept().await;\n (self.tap_fn)(&mut io);\n (io, addr)\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":239,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> io::Result {\n self.listener.local_addr()\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":245,"symbol":"handle_accept_error","kind":"function","lang":"rust","code":"async fn handle_accept_error(e: io::Error) {\n if is_connection_error(&e) {\n return;\n }\n\n // [From `hyper::Server` in 0.14](https://github.com/hyperium/hyper/blob/v0.14.27/src/server/tcp.rs#L186)\n //\n // > A possible scenario is that the process has hit the max open files\n // > allowed, and so trying to accept a new connection will fail with\n // > `EMFILE`. In some cases, it's preferable to just wait for some time, if\n // > the application will likely close some files (or connections), and try\n // > to accept the connection again. If this option is `true`, the error\n // > will be logged at the `error` level, since it is still a big deal,\n // > and then the listener will sleep for 1 second.\n //\n // hyper allowed customizing this but axum does not.\n error!(\"accept error: {e}\");\n tokio::time::sleep(std::time::Duration::from_secs(1)).await;\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":266,"symbol":"is_connection_error","kind":"function","lang":"rust","code":"fn is_connection_error(e: &io::Error) -> bool {\n matches!(\n e.kind(),\n io::ErrorKind::ConnectionRefused\n | io::ErrorKind::ConnectionAborted\n | io::ErrorKind::ConnectionReset\n )\n}"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":284,"symbol":"limit_connections","kind":"function","lang":"rust","code":"async fn limit_connections() {\n static COUNT: AtomicUsize = AtomicUsize::new(0);\n\n struct MyListener;\n\n impl Listener for MyListener {\n type Io = io::DuplexStream;\n type Addr = ();\n\n async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n COUNT.fetch_add(1, Ordering::SeqCst);\n (io::duplex(0).0, ()) // dummy connection\n }\n\n fn local_addr(&self) -> io::Result {\n Ok(())\n }\n }\n\n let mut listener = MyListener.limit_connections(1);\n\n assert_eq!(COUNT.load(Ordering::SeqCst), 0);\n\n // First 'accept' succeeds immediately.\n let conn1 = listener.accept().await;\n assert_eq!(COUNT.load(Ordering::SeqCst), 1);\n\n time::timeout(time::Duration::from_secs(1), listener.accept())\n .await\n .expect_err(\"Second 'accept' should time out.\");\n // It never reaches MyListener::accept to be counted.\n assert_eq!(COUNT.load(Ordering::SeqCst), 1);\n\n // Close the first connection.\n drop(conn1);\n\n // Now 'accept' again succeeds immediately.\n let _conn2 = listener."} {"repo":"axum","file":"axum/src/serve/listener.rs","line":287,"symbol":"MyListener","kind":"type","lang":"rust","code":"struct MyListener;"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":293,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n COUNT.fetch_add(1, Ordering::SeqCst);\n (io::duplex(0).0, ()) // dummy connection\n }"} {"repo":"axum","file":"axum/src/serve/listener.rs","line":298,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> io::Result {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":110,"symbol":"serve","kind":"function","lang":"rust","doc":"[`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info [`MethodRouter`]: crate::routing::MethodRouter [`MethodRouter::into_make_service_with_connect_info`]: crate::routing::MethodRouter::into_make_service_with_connect_info [`Handler`]: crate::handler::Handler [`HandlerWithoutStateExt::into_make_service_with_connect_info`]: crate::handler::HandlerWithoutStateExt::into_make_service_with_connect_info [`HandlerService::into_make_service_with_connect_info`]: crate::handler::HandlerService::into_make_service_with_connect_info","code":"pub fn serve(listener: L, make_service: M) -> Serve\nwhere\n L: Listener,\n M: for<'a> Service, Error = Infallible, Response = S>,\n S: Service, Error = Infallible> + Clone + Send + 'static,\n S::Future: Send,\n B: HttpBody + Send + 'static,\n B::Data: Send,\n B::Error: Into>,\n{\n Serve {\n listener,\n make_service,\n executor: TokioExecutor,\n connection_lifetime_limits: ConnectionLifetimeLimits::default(),\n _marker: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":170,"symbol":"ConnectionLifetimeLimits","kind":"type","lang":"rust","doc":"axum::serve(listener, router) .connection_lifetime_limits(limits) .await; # }; ```","code":"pub struct ConnectionLifetimeLimits {\n max_connection_age: Option,\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":176,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new [`ConnectionLifetimeLimits`] with no limits set.","code":"pub fn new() -> Self {\n Self::default()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":195,"symbol":"max_connection_age","kind":"function","lang":"rust","doc":"This limit does not apply to connections that have been upgraded, e.g. to a WebSocket or via `CONNECT`. Once an HTTP/1 connection is upgraded, hyper hands the socket off to the upgrade handler and [`serve`] stops tracking it, so neither the age limit nor the grace period affect it. An HTTP/2 upgrade stays a stream on the tracked connection and is treated like any other in-flight stream.","code":"pub fn max_connection_age(mut self, age: MaxConnectionAge) -> Self {\n self.max_connection_age = Some(age);\n self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":224,"symbol":"MaxConnectionAge","kind":"type","lang":"rust","doc":"[`grace`] is set: once the grace period elapses the connection is closed even if a request is still in flight. See [`grace`] for the trade-off. [`new`]: MaxConnectionAge::new [`jitter`]: MaxConnectionAge::jitter [`grace`]: MaxConnectionAge::grace","code":"pub struct MaxConnectionAge {\n age: Duration,\n jitter: Duration,\n grace: Option,\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":238,"symbol":"new","kind":"function","lang":"rust","doc":"new requests once it has been open for `age`. Consider also setting [`jitter`] to avoid all connections opened around the same time tearing down simultaneously. [`jitter`]: MaxConnectionAge::jitter","code":"pub fn new(age: Duration) -> Self {\n Self {\n age,\n jitter: Duration::ZERO,\n grace: None,\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":255,"symbol":"jitter","kind":"function","lang":"rust","doc":"This is important for avoiding synchronized reconnect storms when many connections were established at the same time (e.g. right after a deploy): without it, every connection opened in the same instant tears down in the same instant once the age limit elapses. Defaults to `Duration::ZERO`, i.e. no jitter.","code":"pub fn jitter(mut self, jitter: Duration) -> Self {\n self.jitter = jitter;\n self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":275,"symbol":"grace","kind":"function","lang":"rust","doc":"handler that runs longer than the age limit plus the grace period will never complete successfully. Only set a grace period if bounding connection lifetime matters more than letting slow requests finish. `None` waits for in-flight work for as long as it takes, which is the default.","code":"pub fn grace(mut self, grace: impl Into>) -> Self {\n self.grace = grace.into();\n self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":282,"symbol":"random_duration","kind":"function","lang":"rust","doc":"Returns a pseudo-random [`Duration`] in `[Duration::ZERO, max]`.","code":"fn random_duration(max: Duration) -> Duration {\n if max.is_zero() {\n return Duration::ZERO;\n }\n\n // Each `RandomState` is seeded with fresh random keys, so hashing empty\n // input still yields a different value per call.\n let rand = std::collections::hash_map::RandomState::new()\n .build_hasher()\n .finish();\n\n let max_nanos = u64::try_from(max.as_nanos()).unwrap_or(u64::MAX);\n Duration::from_nanos(rand % max_nanos.saturating_add(1))\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":301,"symbol":"sleep_or_pending","kind":"function","lang":"rust","doc":"Sleeps for `duration`, or never completes if it's `None`. Used to model an unset timer without having to poll a future that would otherwise complete immediately.","code":"fn sleep_or_pending(duration: Option) -> Either> {\n match duration {\n Some(duration) => Either::Left(tokio::time::sleep(duration)),\n None => Either::Right(std::future::pending()),\n }\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":346,"symbol":"Executor","kind":"type","lang":"rust","doc":"} } ``` If your executor is expensive to clone, wrap it in an `Arc`. A blanket implementation is provided for `Arc` where `T: Executor`.","code":"pub trait Executor: Clone + Send + Sync + 'static {\n /// Execute a task.\n fn execute(&self, fut: Fut) -> JoinHandle\n where\n Fut: Future + Send + 'static,\n Fut::Output: Send + 'static;\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":348,"symbol":"execute","kind":"function","lang":"rust","doc":"Execute a task.","code":"fn execute(&self, fut: Fut) -> JoinHandle\n where\n Fut: Future + Send + 'static,\n Fut::Output: Send + 'static;"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":357,"symbol":"TokioExecutor","kind":"type","lang":"rust","doc":"The default executor, which uses [`tokio::spawn`].","code":"pub struct TokioExecutor;"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":361,"symbol":"execute","kind":"function","lang":"rust","code":"fn execute(&self, fut: Fut) -> JoinHandle\n where\n Fut: Future + Send + 'static,\n Fut::Output: Send + 'static,\n {\n tokio::spawn(fut)\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":375,"symbol":"execute","kind":"function","lang":"rust","code":"fn execute(&self, fut: Fut) -> JoinHandle\n where\n Fut: Future + Send + 'static,\n Fut::Output: Send + 'static,\n {\n self.as_ref().execute(fut)\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":387,"symbol":"Serve","kind":"type","lang":"rust","doc":"Future returned by [`serve`].","code":"pub struct Serve {\n listener: L,\n make_service: M,\n executor: E,\n connection_lifetime_limits: ConnectionLifetimeLimits,\n _marker: PhantomData S>,\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":425,"symbol":"with_graceful_shutdown","kind":"function","lang":"rust","doc":"``` # Return Value Similarly to [`serve`], although this future resolves to `io::Result<()>`, it will never error. It returns `Ok(())` only after the `signal` future completes.","code":"pub fn with_graceful_shutdown(self, signal: F) -> WithGracefulShutdown\n where\n F: Future + Send + 'static,\n {\n WithGracefulShutdown {\n listener: self.listener,\n make_service: self.make_service,\n executor: self.executor,\n connection_lifetime_limits: self.connection_lifetime_limits,\n signal,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":440,"symbol":"local_addr","kind":"function","lang":"rust","doc":"Returns the local address this server is bound to.","code":"pub fn local_addr(&self) -> io::Result {\n self.listener.local_addr()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":455,"symbol":"connection_lifetime_limits","kind":"function","lang":"rust","doc":"This method can be called before or after [`with_graceful_shutdown`] and [`with_executor`]. [`with_graceful_shutdown`]: Serve::with_graceful_shutdown [`with_executor`]: Serve::with_executor","code":"pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {\n self.connection_lifetime_limits = limits;\n self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":499,"symbol":"with_executor","kind":"function","lang":"rust","doc":".with_executor(MyExecutor) .await; # }; ``` [`with_graceful_shutdown`]: Serve::with_graceful_shutdown","code":"pub fn with_executor(self, executor: E2) -> Serve\n where\n E2: Executor,\n {\n Serve {\n listener: self.listener,\n make_service: self.make_service,\n executor,\n connection_lifetime_limits: self.connection_lifetime_limits,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":527,"symbol":"run","kind":"function","lang":"rust","code":"async fn run(self) -> ! {\n let Self {\n mut listener,\n mut make_service,\n executor,\n connection_lifetime_limits,\n _marker,\n } = self;\n\n let (_signal_tx, signal_rx) = watch::channel(());\n let (_close_tx, close_rx) = watch::channel(());\n\n loop {\n let (io, remote_addr) = listener.accept().await;\n handle_connection(\n &mut make_service,\n &signal_rx,\n &close_rx,\n io,\n remote_addr,\n &executor,\n &connection_lifetime_limits,\n )\n .await;\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":562,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let Self {\n listener,\n make_service,\n executor,\n connection_lifetime_limits,\n _marker: _,\n } = self;\n\n let mut s = f.debug_struct(\"Serve\");\n s.field(\"listener\", listener)\n .field(\"make_service\", make_service)\n .field(\"executor\", executor)\n .field(\"connection_lifetime_limits\", connection_lifetime_limits);\n\n s.finish()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":598,"symbol":"into_future","kind":"function","lang":"rust","code":"fn into_future(self) -> Self::IntoFuture {\n private::ServeFuture(Box::pin(async move { self.run().await }))\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":606,"symbol":"WithGracefulShutdown","kind":"type","lang":"rust","doc":"Serve future with graceful shutdown enabled.","code":"pub struct WithGracefulShutdown {\n listener: L,\n make_service: M,\n executor: E,\n connection_lifetime_limits: ConnectionLifetimeLimits,\n signal: F,\n _marker: PhantomData S>,\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":621,"symbol":"local_addr","kind":"function","lang":"rust","doc":"Returns the local address this server is bound to.","code":"pub fn local_addr(&self) -> io::Result {\n self.listener.local_addr()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":629,"symbol":"with_executor","kind":"function","lang":"rust","doc":"Provide a custom [`Executor`] to use for spawning connection tasks and hyper's internal tasks (e.g. HTTP/2). See [`Serve::with_executor`] for details.","code":"pub fn with_executor(self, executor: E2) -> WithGracefulShutdown\n where\n E2: Executor,\n {\n WithGracefulShutdown {\n listener: self.listener,\n make_service: self.make_service,\n executor,\n connection_lifetime_limits: self.connection_lifetime_limits,\n signal: self.signal,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":647,"symbol":"connection_lifetime_limits","kind":"function","lang":"rust","doc":"Apply per-connection [`ConnectionLifetimeLimits`], bounding the lifetime of individual connections. See [`Serve::connection_lifetime_limits`] and [`ConnectionLifetimeLimits`] for details.","code":"pub fn connection_lifetime_limits(mut self, limits: ConnectionLifetimeLimits) -> Self {\n self.connection_lifetime_limits = limits;\n self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":668,"symbol":"run","kind":"function","lang":"rust","code":"async fn run(self) {\n let Self {\n mut listener,\n mut make_service,\n executor,\n connection_lifetime_limits,\n signal,\n _marker,\n } = self;\n\n let (signal_tx, mut signal_rx) = watch::channel(());\n executor.execute(async move {\n signal.await;\n trace!(\"received graceful shutdown signal. Telling tasks to shutdown\");\n drop(signal_tx);\n });\n\n let (close_tx, close_rx) = watch::channel(());\n\n loop {\n let (io, remote_addr) =\n match select(pin!(listener.accept()), pin!(signal_rx.changed())).await {\n Either::Left((conn, _)) => conn,\n Either::Right((Err(_), _)) => {\n trace!(\"signal received, not accepting new connections\");\n break;\n }\n Either::Right((Ok(()), _)) => {\n unreachable!(\"shutdown channel never sends values\")\n }\n };\n\n handle_connection(\n &mut make_service,\n &signal_rx,\n &close_rx,\n "} {"repo":"axum","file":"axum/src/serve/mod.rs","line":732,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let Self {\n listener,\n make_service,\n executor: _,\n connection_lifetime_limits,\n signal,\n _marker: _,\n } = self;\n\n f.debug_struct(\"WithGracefulShutdown\")\n .field(\"listener\", listener)\n .field(\"make_service\", make_service)\n .field(\"connection_lifetime_limits\", connection_lifetime_limits)\n .field(\"signal\", signal)\n .finish()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":769,"symbol":"into_future","kind":"function","lang":"rust","code":"fn into_future(self) -> Self::IntoFuture {\n private::ServeFuture(Box::pin(async move { self.run().await }))\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":776,"symbol":"HyperExecutor","kind":"type","lang":"rust","doc":"Adapts axum's [`Executor`] to hyper's [`hyper::rt::Executor`].","code":"struct HyperExecutor(E);"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":783,"symbol":"execute","kind":"function","lang":"rust","code":"fn execute(&self, fut: Fut) {\n drop(self.0.execute(fut));\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":788,"symbol":"handle_connection","kind":"function","lang":"rust","code":"async fn handle_connection(\n make_service: &mut M,\n signal_rx: &watch::Receiver<()>,\n close_rx: &watch::Receiver<()>,\n io: ::Io,\n remote_addr: ::Addr,\n executor: &E,\n connection_lifetime_limits: &ConnectionLifetimeLimits,\n) where\n L: Listener,\n L::Addr: Debug,\n M: for<'a> Service, Error = Infallible, Response = S> + Send + 'static,\n for<'a> >>::Future: Send,\n S: Service, Error = Infallible> + Clone + Send + 'static,\n S::Future: Send,\n B: HttpBody + Send + 'static,\n B::Data: Send,\n B::Error: Into>,\n E: Executor,\n{\n let mut signal_rx = signal_rx.clone();\n let connection_lifetime_limits = connection_lifetime_limits.clone();\n let io = TokioIo::new(io);\n\n trace!(\"connection {remote_addr:?} accepted\");\n\n make_service\n .ready()\n .await\n .unwrap_or_else(|err| match err {});\n\n let tower_service = make_service\n .call(IncomingStream {\n io: &io,\n remote_addr,\n })\n .await\n .unwrap_or_else(|err|"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":902,"symbol":"IncomingStream","kind":"type","lang":"rust","doc":"An incoming stream. Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`]. [`IntoMakeServiceWithConnectInfo`]: crate::extract::connect_info::IntoMakeServiceWithConnectInfo","code":"pub struct IncomingStream<'a, L>\nwhere\n L: Listener,\n{\n io: &'a TokioIo,\n remote_addr: L::Addr,\n}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":915,"symbol":"io","kind":"function","lang":"rust","doc":"Get a reference to the inner IO type.","code":"pub fn io(&self) -> &L::Io {\n self.io.inner()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":920,"symbol":"remote_addr","kind":"function","lang":"rust","doc":"Returns the remote address that this stream is bound to.","code":"pub fn remote_addr(&self) -> &L::Addr {\n &self.remote_addr\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":933,"symbol":"ServeFuture","kind":"type","lang":"rust","code":"pub struct ServeFuture(pub(super) futures_core::future::BoxFuture<'static, T>);"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":939,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n self.0.as_mut().poll(cx)\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":945,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ServeFuture\").finish_non_exhaustive()\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":986,"symbol":"ReadyListener","kind":"type","lang":"rust","code":"struct ReadyListener(Option);"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":995,"symbol":"accept","kind":"function","lang":"rust","code":"async fn accept(&mut self) -> (Self::Io, Self::Addr) {\n match self.0.take() {\n Some(server) => (server, ()),\n None => std::future::pending().await,\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1002,"symbol":"local_addr","kind":"function","lang":"rust","code":"fn local_addr(&self) -> io::Result {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1008,"symbol":"if_it_compiles_it_works","kind":"function","lang":"rust","code":"async fn if_it_compiles_it_works() {\n #[derive(Clone, Debug)]\n struct UdsConnectInfo;\n\n #[cfg(unix)]\n impl Connected> for UdsConnectInfo {\n fn connect_info(_stream: IncomingStream<'_, UnixListener>) -> Self {\n Self\n }\n }\n\n let router: Router = Router::new();\n\n let addr = \"0.0.0.0:0\";\n\n let tcp_nodelay_listener = || async {\n TcpListener::bind(addr).await.unwrap().tap_io(|tcp_stream| {\n if let Err(err) = tcp_stream.set_nodelay(true) {\n eprintln!(\"failed to set TCP_NODELAY on incoming connection: {err:#}\");\n }\n })\n };\n\n // router\n serve(TcpListener::bind(addr).await.unwrap(), router.clone());\n serve(tcp_nodelay_listener().await, router.clone()).await;\n #[cfg(unix)]\n serve(UnixListener::bind(\"\").unwrap(), router.clone());\n\n serve(\n TcpListener::bind(addr).await.unwrap(),\n router.clone().into_make_service(),\n );\n serve(\n tcp_nodelay_listener().await,\n router.clone().into_make_service(),\n "} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1010,"symbol":"UdsConnectInfo","kind":"type","lang":"rust","code":"struct UdsConnectInfo;"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1014,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(_stream: IncomingStream<'_, UnixListener>) -> Self {\n Self\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1178,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1181,"symbol":"TestExecutor","kind":"type","lang":"rust","code":"struct TestExecutor(std::sync::Arc);"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1184,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> Self {\n Self(std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)))\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1188,"symbol":"count","kind":"function","lang":"rust","code":"fn count(&self) -> usize {\n self.0.load(std::sync::atomic::Ordering::SeqCst)\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1194,"symbol":"execute","kind":"function","lang":"rust","code":"fn execute(&self, fut: Fut) -> JoinHandle\n where\n Fut: std::future::Future + Send + 'static,\n Fut::Output: Send + 'static,\n {\n self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);\n tokio::spawn(fut)\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1205,"symbol":"test_serve_local_addr","kind":"function","lang":"rust","code":"async fn test_serve_local_addr() {\n let router: Router = Router::new();\n let addr = \"0.0.0.0:0\";\n\n let server = serve(TcpListener::bind(addr).await.unwrap(), router.clone());\n let address = server.local_addr().unwrap();\n\n assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));\n assert_ne!(address.port(), 0);\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1217,"symbol":"test_with_graceful_shutdown_local_addr","kind":"function","lang":"rust","code":"async fn test_with_graceful_shutdown_local_addr() {\n let router: Router = Router::new();\n let addr = \"0.0.0.0:0\";\n\n let server = serve(TcpListener::bind(addr).await.unwrap(), router.clone())\n .with_graceful_shutdown(pending());\n let address = server.local_addr().unwrap();\n\n assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));\n assert_ne!(address.port(), 0);\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1230,"symbol":"test_with_graceful_shutdown_request_header_timeout","kind":"function","lang":"rust","code":"async fn test_with_graceful_shutdown_request_header_timeout() {\n for (timeout, req) in [\n // Idle connections (between requests) are closed immediately\n // when a graceful shutdown is triggered.\n (0, \"\"), // idle before request sent\n (0, \"GET / HTTP/1.1\\r\\n\\r\\n\"), // idle after complete exchange\n // hyper times stalled request lines/headers out after 30 sec,\n // after which the graceful shutdown can be completed.\n (30, \"GET / HT\"), // stall during request line\n (30, \"GET / HTTP/1.0\\r\\nAccept: \"), // stall during request headers\n ] {\n let (mut client, server) = io::duplex(1024);\n client.write_all(req.as_bytes()).await.unwrap();\n\n let server_task = async {\n serve(ReadyListener(Some(server)), Router::new())\n .with_graceful_shutdown(tokio::time::sleep(Duration::from_secs(1)))\n .await;\n };\n\n tokio::time::timeout(Duration::from_secs(timeout + 2), server_task)\n .await\n .expect(\"server_task didn't exit in time\");\n "} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1257,"symbol":"test_hyper_header_read_timeout_is_enabled","kind":"function","lang":"rust","code":"async fn test_hyper_header_read_timeout_is_enabled() {\n let header_read_timeout_default = 30;\n for req in [\n \"GET / HT\", // stall during request line\n \"GET / HTTP/1.0\\r\\nAccept: \", // stall during request headers\n ] {\n let (mut client, server) = io::duplex(1024);\n client.write_all(req.as_bytes()).await.unwrap();\n\n let server_task = async {\n serve(ReadyListener(Some(server)), Router::new()).await;\n };\n\n let wait_for_server_to_close_conn = async {\n tokio::time::timeout(\n Duration::from_secs(header_read_timeout_default + 1),\n client.read_to_end(&mut Vec::new()),\n )\n .await\n .expect(\"timeout: server didn't close connection in time\")\n .expect(\"read_to_end\");\n };\n\n match select(pin!(server_task), pin!(wait_for_server_to_close_conn)).await {\n Either::Left(_) => unreachable!(),\n Either::Right(_) => (),\n };\n }\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1288,"symbol":"into_future_outside_tokio","kind":"function","lang":"rust","code":"fn into_future_outside_tokio() {\n let router: Router = Router::new();\n let addr = \"0.0.0.0:0\";\n\n let rt = tokio::runtime::Builder::new_multi_thread()\n .enable_all()\n .build()\n .unwrap();\n\n let listener = rt.block_on(tokio::net::TcpListener::bind(addr)).unwrap();\n\n // Call Serve::into_future outside of a tokio context. This used to panic.\n _ = serve(listener, router).into_future();\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1304,"symbol":"serving_on_custom_io_type","kind":"function","lang":"rust","code":"async fn serving_on_custom_io_type() {\n let (client, server) = io::duplex(1024);\n let listener = ReadyListener(Some(server));\n\n let app = Router::new().route(\"/\", get(|| async { \"Hello, World!\" }));\n\n tokio::spawn(serve(listener, app).into_future());\n\n let stream = TokioIo::new(client);\n let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();\n tokio::spawn(conn);\n\n let request = Request::builder().body(Body::empty()).unwrap();\n\n let response = sender.send_request(request).await.unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = Body::new(response.into_body());\n let body = to_bytes(body, usize::MAX).await.unwrap();\n let body = String::from_utf8(body.to_vec()).unwrap();\n assert_eq!(body, \"Hello, World!\");\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1333,"symbol":"graceful_shutdown_completes_inflight_request","kind":"function","lang":"rust","doc":"Asserts the documented `with_graceful_shutdown` drain semantics: after the signal fires, an already-in-flight request is allowed to run to completion and only then does the `serve` future resolve. The existing `test_with_graceful_shutdown_request_header_timeout` only covers stalled requests being killed by hyper's header read timeout.","code":"async fn graceful_shutdown_completes_inflight_request() {\n use std::sync::Arc;\n\n let started = Arc::new(tokio::sync::Notify::new());\n let release = Arc::new(tokio::sync::Notify::new());\n let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();\n\n let app = Router::new().route(\"/\", {\n let started = started.clone();\n let release = release.clone();\n get(move || {\n let started = started.clone();\n let release = release.clone();\n async move {\n started.notify_one();\n release.notified().await;\n \"done\"\n }\n })\n });\n\n let (client, server) = io::duplex(1024);\n let listener = ReadyListener(Some(server));\n\n let server_task = tokio::spawn(\n serve(listener, app)\n .with_graceful_shutdown(async move {\n shutdown_rx.await.ok();\n })\n .into_future(),\n );\n\n let stream = TokioIo::new(client);\n let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap()"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1409,"symbol":"tap_io_runs_on_each_accepted_connection","kind":"function","lang":"rust","doc":"Asserts that `ListenerExt::tap_io` invokes its closure on every accepted connection when used with `serve`. The sibling `ListenerExt::limit_connections` has a direct unit test (in `serve::listener::tests`); `tap_io` did not have a runtime test, so its documented contract was only covered at the type level by `if_it_compiles_it_works`.","code":"async fn tap_io_runs_on_each_accepted_connection() {\n use std::sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n };\n\n let count = Arc::new(AtomicUsize::new(0));\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let addr = listener.local_addr().unwrap();\n\n let counted = {\n let count = count.clone();\n listener.tap_io(move |_io| {\n count.fetch_add(1, Ordering::SeqCst);\n })\n };\n\n let app = Router::new().route(\"/\", get(|| async { \"ok\" }));\n tokio::spawn(serve(counted, app).into_future());\n\n // Open two distinct TCP connections to force two accepts.\n for _ in 0..2 {\n let stream = tokio::net::TcpStream::connect(addr).await.unwrap();\n let io = TokioIo::new(stream);\n let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();\n let conn_handle = tokio::spawn(conn);\n\n let request = Request::builder().uri(\"/\").body(Body::empty()).unwrap();\n let response = sender.send_request(request).await.unwrap();\n assert_eq!(response.status(), Status"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1448,"symbol":"serving_with_custom_executor","kind":"function","lang":"rust","code":"async fn serving_with_custom_executor() {\n let (client, server) = io::duplex(1024);\n let listener = ReadyListener(Some(server));\n\n let app = Router::new().route(\"/\", get(|| async { \"Hello, World!\" }));\n\n let executor = TestExecutor::new();\n tokio::spawn(\n serve(listener, app)\n .with_executor(executor.clone())\n .into_future(),\n );\n\n let stream = TokioIo::new(client);\n let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();\n tokio::spawn(conn);\n\n let request = Request::builder().body(Body::empty()).unwrap();\n\n let response = sender.send_request(request).await.unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = Body::new(response.into_body());\n let body = to_bytes(body, usize::MAX).await.unwrap();\n let body = String::from_utf8(body.to_vec()).unwrap();\n assert_eq!(body, \"Hello, World!\");\n\n // One task per connection for HTTP/1.\n assert_eq!(executor.count(), 1);\n }"} {"repo":"axum","file":"axum/src/serve/mod.rs","line":1481,"symbol":"serving_with_custom_executor_http2","kind":"function","lang":"rust","code":"async fn serving_with_custom_executor_http2() {\n use hyper_util::rt::TokioExecutor;\n\n let (client, server) = io::duplex(1024);\n let listener = ReadyListener(Some(server));\n\n let app = Router::new().route(\"/\", get(|| async { \"Hello, World!\" }));\n\n let executor = TestExecutor::new();\n tokio::spawn(\n serve(listener, app)\n .with_executor(executor.clone())\n .into_future(),\n );\n\n let io = TokioIo::new(client);\n let (mut sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())\n .handshake(io)\n .await\n .unwrap();\n tokio::spawn(conn);\n\n let request = Request::builder().body(Body::empty()).unwrap();\n\n let response = sender.send_request(request).await.unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = Body::new(response.into_body());\n let body = to_bytes(body, usize::MAX).await.unwrap();\n let body = String::from_utf8(body.to_vec()).unwrap();\n assert_eq!(body, \"Hello, World!\");\n\n // Two tasks: axum's connection, and hyper's internal HTTP/2 task.\n as"} {"repo":"axum","file":"axum/src/service_ext.rs","line":8,"symbol":"ServiceExt","kind":"type","lang":"rust","doc":"Extension trait that adds additional methods to any [`Service`].","code":"pub trait ServiceExt: Service + Sized {\n /// Convert this service into a [`MakeService`], that is a [`Service`] whose\n /// response is another service.\n ///\n /// This is commonly used when applying middleware around an entire [`Router`]. See [\"Rewriting\n /// request URI in middleware\"] for more details.\n ///\n /// [`MakeService`]: tower::make::MakeService\n /// [\"Rewriting request URI in middleware\"]: crate::middleware#rewriting-request-uri-in-middleware\n /// [`Router`]: crate::Router\n fn into_make_service(self) -> IntoMakeService;\n\n /// Convert this service into a [`MakeService`], that will store `C`'s\n /// associated `ConnectInfo` in a request extension such that [`ConnectInfo`]\n /// can extract it.\n ///\n /// This enables extracting things like the client's remote address.\n /// This is commonly used when applying middleware around an entire [`Router`]. See [\"Rewriting\n /// request URI in middleware\"] for more details.\n ///\n /// [`MakeService`]: tower::make::MakeService\n /// [\"Rewriting request URI in middleware\"]: crate::middleware#rewriting-request-uri-in-middleware\n /// [`Router`]: crate::Router\n /// [`"} {"repo":"axum","file":"axum/src/service_ext.rs","line":18,"symbol":"into_make_service","kind":"function","lang":"rust","doc":"This is commonly used when applying middleware around an entire [`Router`]. See [\"Rewriting request URI in middleware\"] for more details. [`MakeService`]: tower::make::MakeService [\"Rewriting request URI in middleware\"]: crate::middleware#rewriting-request-uri-in-middleware [`Router`]: crate::Router","code":"fn into_make_service(self) -> IntoMakeService;"} {"repo":"axum","file":"axum/src/service_ext.rs","line":33,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","doc":"request URI in middleware\"] for more details. [`MakeService`]: tower::make::MakeService [\"Rewriting request URI in middleware\"]: crate::middleware#rewriting-request-uri-in-middleware [`Router`]: crate::Router [`ConnectInfo`]: crate::extract::connect_info::ConnectInfo","code":"fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo;"} {"repo":"axum","file":"axum/src/service_ext.rs","line":42,"symbol":"handle_error","kind":"function","lang":"rust","doc":"by converting them into responses. See [\"error handling model\"] for more details. [`HandleError`]: crate::error_handling::HandleError [\"error handling model\"]: crate::error_handling#axums-error-handling-model","code":"fn handle_error(self, f: F) -> HandleError {\n HandleError::new(self, f)\n }"} {"repo":"axum","file":"axum/src/service_ext.rs","line":51,"symbol":"into_make_service","kind":"function","lang":"rust","code":"fn into_make_service(self) -> IntoMakeService {\n IntoMakeService::new(self)\n }"} {"repo":"axum","file":"axum/src/service_ext.rs","line":56,"symbol":"into_make_service_with_connect_info","kind":"function","lang":"rust","code":"fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo {\n IntoMakeServiceWithConnectInfo::new(self)\n }"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":6,"symbol":"CountingCloneableState","kind":"type","lang":"rust","code":"pub(crate) struct CountingCloneableState {\n state: Arc,\n}"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":10,"symbol":"InnerState","kind":"type","lang":"rust","code":"struct InnerState {\n setup_done: AtomicBool,\n count: AtomicUsize,\n}"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":16,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new() -> Self {\n let inner_state = InnerState {\n setup_done: AtomicBool::new(false),\n count: AtomicUsize::new(0),\n };\n Self {\n state: Arc::new(inner_state),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":26,"symbol":"setup_done","kind":"function","lang":"rust","code":"pub(crate) fn setup_done(&self) {\n self.state.setup_done.store(true, Ordering::SeqCst);\n }"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":30,"symbol":"count","kind":"function","lang":"rust","code":"pub(crate) fn count(&self) -> usize {\n self.state.count.load(Ordering::SeqCst)\n }"} {"repo":"axum","file":"axum/src/test_helpers/counting_cloneable_state.rs","line":36,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n let state = self.state.clone();\n if state.setup_done.load(Ordering::SeqCst) {\n let bt = std::backtrace::Backtrace::force_capture();\n let bt = bt\n .to_string()\n .lines()\n .filter(|line| line.contains(\"axum\") || line.contains(\"./src\"))\n .collect::>()\n .join(\"\\n\");\n println!(\"AppState::Clone:\\n===============\\n{bt}\\n\");\n state.count.fetch_add(1, Ordering::SeqCst);\n }\n\n Self { state }\n }"} {"repo":"axum","file":"axum/src/test_helpers/mod.rs","line":15,"symbol":"assert_send","kind":"function","lang":"rust","code":"pub(crate) fn assert_send() {}"} {"repo":"axum","file":"axum/src/test_helpers/mod.rs","line":17,"symbol":"assert_sync","kind":"function","lang":"rust","code":"pub(crate) fn assert_sync() {}"} {"repo":"axum","file":"axum/src/test_helpers/mod.rs","line":20,"symbol":"NotSendSync","kind":"type","lang":"rust","code":"pub(crate) struct NotSendSync(*const ());"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":11,"symbol":"spawn_service","kind":"function","lang":"rust","code":"pub(crate) fn spawn_service(svc: S) -> SocketAddr\nwhere\n S: Service + Clone + Send + 'static,\n S::Future: Send,\n{\n let std_listener = std::net::TcpListener::bind(\"127.0.0.1:0\").unwrap();\n std_listener.set_nonblocking(true).unwrap();\n let listener = TcpListener::from_std(std_listener).unwrap();\n\n let addr = listener.local_addr().unwrap();\n println!(\"Listening on {addr}\");\n\n tokio::spawn(async move {\n serve(listener, Shared::new(svc)).await;\n });\n\n addr\n}"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":30,"symbol":"TestClient","kind":"type","lang":"rust","code":"pub struct TestClient {\n client: reqwest::Client,\n addr: SocketAddr,\n}"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":36,"symbol":"new","kind":"function","lang":"rust","code":"pub fn new(svc: S) -> Self\n where\n S: Service + Clone + Send + 'static,\n S::Future: Send,\n {\n let addr = spawn_service(svc);\n\n let client = reqwest::Client::builder()\n .redirect(reqwest::redirect::Policy::none())\n .build()\n .unwrap();\n\n Self { client, addr }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":51,"symbol":"get","kind":"function","lang":"rust","code":"pub fn get(&self, url: &str) -> RequestBuilder {\n RequestBuilder {\n builder: self.client.get(format!(\"http://{}{url}\", self.addr)),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":57,"symbol":"head","kind":"function","lang":"rust","code":"pub fn head(&self, url: &str) -> RequestBuilder {\n RequestBuilder {\n builder: self.client.head(format!(\"http://{}{url}\", self.addr)),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":63,"symbol":"post","kind":"function","lang":"rust","code":"pub fn post(&self, url: &str) -> RequestBuilder {\n RequestBuilder {\n builder: self.client.post(format!(\"http://{}{url}\", self.addr)),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":70,"symbol":"put","kind":"function","lang":"rust","code":"pub fn put(&self, url: &str) -> RequestBuilder {\n RequestBuilder {\n builder: self.client.put(format!(\"http://{}{url}\", self.addr)),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":77,"symbol":"patch","kind":"function","lang":"rust","code":"pub fn patch(&self, url: &str) -> RequestBuilder {\n RequestBuilder {\n builder: self.client.patch(format!(\"http://{}{url}\", self.addr)),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":85,"symbol":"server_port","kind":"function","lang":"rust","code":"pub fn server_port(&self) -> u16 {\n self.addr.port()\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":91,"symbol":"RequestBuilder","kind":"type","lang":"rust","code":"pub struct RequestBuilder {\n builder: reqwest::RequestBuilder,\n}"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":96,"symbol":"body","kind":"function","lang":"rust","code":"pub fn body(mut self, body: impl Into) -> Self {\n self.builder = self.builder.body(body);\n self\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":101,"symbol":"json","kind":"function","lang":"rust","code":"pub fn json(mut self, json: &T) -> Self\n where\n T: serde_core::Serialize,\n {\n self.builder = self.builder.json(json);\n self\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":109,"symbol":"header","kind":"function","lang":"rust","code":"pub fn header(mut self, key: K, value: V) -> Self\n where\n HeaderName: TryFrom,\n >::Error: Into,\n HeaderValue: TryFrom,\n >::Error: Into,\n {\n self.builder = self.builder.header(key, value);\n self\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":121,"symbol":"multipart","kind":"function","lang":"rust","code":"pub fn multipart(mut self, form: reqwest::multipart::Form) -> Self {\n self.builder = self.builder.multipart(form);\n self\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":131,"symbol":"into_future","kind":"function","lang":"rust","code":"fn into_future(self) -> Self::IntoFuture {\n Box::pin(async {\n TestResponse {\n response: self.builder.send().await.unwrap(),\n }\n })\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":141,"symbol":"TestResponse","kind":"type","lang":"rust","code":"pub struct TestResponse {\n response: reqwest::Response,\n}"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":148,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Self::Target {\n &self.response\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":155,"symbol":"bytes","kind":"function","lang":"rust","code":"pub async fn bytes(self) -> Bytes {\n self.response.bytes().await.unwrap()\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":159,"symbol":"text","kind":"function","lang":"rust","code":"pub async fn text(self) -> String {\n self.response.text().await.unwrap()\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":164,"symbol":"json","kind":"function","lang":"rust","code":"pub async fn json(self) -> T\n where\n T: serde_core::de::DeserializeOwned,\n {\n self.response.json().await.unwrap()\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":171,"symbol":"chunk","kind":"function","lang":"rust","code":"pub async fn chunk(&mut self) -> Option {\n self.response.chunk().await.unwrap()\n }"} {"repo":"axum","file":"axum/src/test_helpers/test_client.rs","line":175,"symbol":"chunk_text","kind":"function","lang":"rust","code":"pub async fn chunk_text(&mut self) -> Option {\n let chunk = self.chunk().await?;\n Some(String::from_utf8(chunk.to_vec()).unwrap())\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":16,"symbol":"TracingEvent","kind":"type","lang":"rust","code":"pub(crate) struct TracingEvent {\n pub(crate) fields: T,\n pub(crate) target: String,\n pub(crate) level: String,\n}"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":23,"symbol":"capture_tracing","kind":"function","lang":"rust","doc":"Run an async closure and capture the tracing output it produces.","code":"pub(crate) fn capture_tracing(f: F) -> CaptureTracing\nwhere\n T: DeserializeOwned,\n{\n CaptureTracing {\n f,\n filter: None,\n _phantom: PhantomData,\n }\n}"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":34,"symbol":"CaptureTracing","kind":"type","lang":"rust","code":"pub(crate) struct CaptureTracing {\n f: F,\n filter: Option,\n _phantom: PhantomData T>,\n}"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":41,"symbol":"with_filter","kind":"function","lang":"rust","code":"pub(crate) fn with_filter(mut self, filter_string: &str) -> Self {\n self.filter = Some(filter_string.parse().unwrap());\n self\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":56,"symbol":"into_future","kind":"function","lang":"rust","code":"fn into_future(self) -> Self::IntoFuture {\n let Self { f, filter, .. } = self;\n Box::pin(async move {\n let (make_writer, handle) = TestMakeWriter::new();\n\n let filter = filter.unwrap_or_else(|| \"axum=trace\".parse().unwrap());\n let subscriber = tracing_subscriber::registry().with(\n tracing_subscriber::fmt::layer()\n .with_writer(make_writer)\n .with_target(true)\n .without_time()\n .with_ansi(false)\n .json()\n .flatten_event(false)\n .with_filter(filter),\n );\n\n let guard = tracing::subscriber::set_default(subscriber);\n\n f().with_current_subscriber().await;\n\n drop(guard);\n\n handle\n .take()\n .lines()\n .map(|line| serde_json::from_str(line).unwrap())\n .collect()\n })\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":88,"symbol":"TestMakeWriter","kind":"type","lang":"rust","code":"struct TestMakeWriter {\n write: Arc>>>,\n}"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":93,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> (Self, Handle) {\n let write = Arc::new(Mutex::new(Some(Vec::::new())));\n\n (\n Self {\n write: write.clone(),\n },\n Handle { write },\n )\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":108,"symbol":"make_writer","kind":"function","lang":"rust","code":"fn make_writer(&'a self) -> Self::Writer {\n Writer(self)\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":113,"symbol":"Writer","kind":"type","lang":"rust","code":"struct Writer<'a>(&'a TestMakeWriter);"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":116,"symbol":"write","kind":"function","lang":"rust","code":"fn write(&mut self, buf: &[u8]) -> io::Result {\n match &mut *self.0.write.lock().unwrap() {\n Some(vec) => {\n let len = buf.len();\n vec.extend(buf);\n Ok(len)\n }\n None => Err(io::Error::other(\"inner writer has been taken\")),\n }\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":127,"symbol":"flush","kind":"function","lang":"rust","code":"fn flush(&mut self) -> io::Result<()> {\n Ok(())\n }"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":132,"symbol":"Handle","kind":"type","lang":"rust","code":"struct Handle {\n write: Arc>>>,\n}"} {"repo":"axum","file":"axum/src/test_helpers/tracing_helpers.rs","line":137,"symbol":"take","kind":"function","lang":"rust","code":"fn take(self) -> String {\n let vec = self.write.lock().unwrap().take().unwrap();\n String::from_utf8(vec).unwrap()\n }"} {"repo":"axum","file":"axum/src/util.rs","line":13,"symbol":"PercentDecodedStr","kind":"type","lang":"rust","code":"pub(crate) struct PercentDecodedStr(Arc);"} {"repo":"axum","file":"axum/src/util.rs","line":16,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(s: S) -> Option\n where\n S: AsRef,\n {\n percent_encoding::percent_decode(s.as_ref().as_bytes())\n .decode_utf8()\n .ok()\n .map(|decoded| Self(decoded.as_ref().into()))\n }"} {"repo":"axum","file":"axum/src/util.rs","line":26,"symbol":"as_str","kind":"function","lang":"rust","code":"pub(crate) fn as_str(&self) -> &str {\n &self.0\n }"} {"repo":"axum","file":"axum/src/util.rs","line":35,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Self::Target {\n self.as_str()\n }"} {"repo":"axum","file":"axum/src/util.rs","line":49,"symbol":"MapIntoResponse","kind":"type","lang":"rust","code":"pub(crate) struct MapIntoResponse {\n inner: S,\n}"} {"repo":"axum","file":"axum/src/util.rs","line":54,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(inner: S) -> Self {\n Self { inner }\n }"} {"repo":"axum","file":"axum/src/util.rs","line":68,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum/src/util.rs","line":72,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: http::Request) -> Self::Future {\n MapIntoResponseFuture {\n inner: self.inner.call(req),\n }\n }"} {"repo":"axum","file":"axum/src/util.rs","line":93,"symbol":"poll","kind":"function","lang":"rust","code":"fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let res = ready!(self.project().inner.poll(cx)?);\n Poll::Ready(Ok(res.into_response()))\n }"} {"repo":"axum","file":"axum/src/util.rs","line":99,"symbol":"try_downcast","kind":"function","lang":"rust","code":"pub(crate) fn try_downcast(k: K) -> Result\nwhere\n T: 'static,\n K: Send + 'static,\n{\n let mut k = Some(k);\n if let Some(k) = ::downcast_mut::>(&mut k) {\n Ok(k.take().unwrap())\n } else {\n Err(k.unwrap())\n }\n}"} {"repo":"axum","file":"axum/src/util.rs","line":113,"symbol":"test_try_downcast","kind":"function","lang":"rust","code":"fn test_try_downcast() {\n assert_eq!(try_downcast::(5_u32), Err(5_u32));\n assert_eq!(try_downcast::(5_i32), Ok(5_i32));\n}"} {"repo":"axum","file":"axum/tests/panic_location.rs","line":12,"symbol":"routes_with_overlapping_method_routes","kind":"function","lang":"rust","code":"fn routes_with_overlapping_method_routes() {\n static PANIC_LOCATION_FILE: OnceLock = OnceLock::new();\n\n let default_hook = take_hook();\n set_hook(Box::new(|panic_info| {\n if let Some(location) = panic_info.location() {\n _ = PANIC_LOCATION_FILE.set(location.file().to_owned());\n }\n }));\n\n let result = catch_unwind(|| {\n async fn handler() {}\n\n let _: Router = Router::new()\n .route(\"/foo/bar\", get(handler))\n .route(\"/foo/bar\", get(handler));\n });\n set_hook(default_hook);\n\n let panic_payload = result.unwrap_err();\n let panic_msg = panic_payload.downcast_ref::().unwrap();\n\n assert_eq!(\n panic_msg,\n \"Overlapping method route. Handler for `GET /foo/bar` already exists\"\n );\n\n let file = PANIC_LOCATION_FILE.get().unwrap();\n assert_eq!(Path::new(file).file_name().unwrap(), \"panic_location.rs\");\n}"} {"repo":"axum","file":"axum/tests/panic_location.rs","line":23,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":12,"symbol":"Unknown","kind":"type","lang":"rust","doc":"Refer to the documentation of [`super::Body::unknown`] which is `pub`.","code":"pub(crate) struct Unknown {\n _marker: PhantomData D>,\n}"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":17,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) const fn new() -> Self {\n Self {\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":29,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n self: Pin<&mut Self>,\n _cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n Poll::Ready(None)\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":36,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n true\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":40,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> SizeHint {\n SizeHint::default()\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":46,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Unknown\").finish()\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":52,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self::new()\n }"} {"repo":"axum","file":"axum-core/src/body/unknown.rs","line":58,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n *self\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":18,"symbol":"boxed","kind":"function","lang":"rust","code":"fn boxed(body: B) -> BoxBody\nwhere\n B: http_body::Body + Send + 'static,\n B::Error: Into,\n{\n try_downcast(body).unwrap_or_else(|body| body.map_err(Error::new).boxed_unsync())\n}"} {"repo":"axum","file":"axum-core/src/body.rs","line":26,"symbol":"try_downcast","kind":"function","lang":"rust","code":"pub(crate) fn try_downcast(k: K) -> Result\nwhere\n T: 'static,\n K: Send + 'static,\n{\n let mut k = Some(k);\n if let Some(k) = ::downcast_mut::>(&mut k) {\n Ok(k.take().unwrap())\n } else {\n Err(k.unwrap())\n }\n}"} {"repo":"axum","file":"axum-core/src/body.rs","line":42,"symbol":"Body","kind":"type","lang":"rust","doc":"The body type used in axum requests and responses.","code":"pub struct Body(BoxBody);"} {"repo":"axum","file":"axum-core/src/body.rs","line":46,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `Body` that wraps another [`http_body::Body`].","code":"pub fn new(body: B) -> Self\n where\n B: http_body::Body + Send + 'static,\n B::Error: Into,\n {\n try_downcast(body).unwrap_or_else(|body| Self(boxed(body)))\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":55,"symbol":"empty","kind":"function","lang":"rust","doc":"Create an empty body.","code":"pub fn empty() -> Self {\n Self::new(http_body_util::Empty::new())\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":79,"symbol":"unknown","kind":"function","lang":"rust","doc":"Other than the size hint, an unknown body behaves like an empty body, i.e., [`Body::is_end_stream`] returns `true`, and when polled via [`Body::poll_frame`], it immediately returns `Poll::Ready(None)`. [RFC 9110 (Section 9.3.2, Paragraph 2)]: https://datatracker.ietf.org/doc/html/rfc9110#section-9.3.2-2","code":"pub fn unknown() -> Self {\n Self::new(Unknown::new())\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":86,"symbol":"from_stream","kind":"function","lang":"rust","doc":"Create a new `Body` from a [`Stream`]. [`Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html","code":"pub fn from_stream(stream: S) -> Self\n where\n S: TryStream + Send + 'static,\n S::Ok: Into,\n S::Error: Into,\n {\n Self::new(StreamBody {\n stream: SyncWrapper::new(stream),\n })\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":103,"symbol":"into_data_stream","kind":"function","lang":"rust","doc":"Convert the body into a [`Stream`] of data frames. Non-data frames (such as trailers) will be discarded. Use [`http_body_util::BodyStream`] if you need a [`Stream`] of all frame types. [`http_body_util::BodyStream`]: https://docs.rs/http-body-util/latest/http_body_util/struct.BodyStream.html","code":"pub fn into_data_stream(self) -> BodyDataStream {\n BodyDataStream { inner: self }\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":109,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self::empty()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":115,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ()) -> Self {\n Self::empty()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":145,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n mut self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n Pin::new(&mut self.0).poll_frame(cx)\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":153,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> http_body::SizeHint {\n self.0.size_hint()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":158,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n self.0.is_end_stream()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":168,"symbol":"BodyDataStream","kind":"type","lang":"rust","doc":"A stream of data frames. Created with [`Body::into_data_stream`].","code":"pub struct BodyDataStream {\n inner: Body,\n}"} {"repo":"axum","file":"axum-core/src/body.rs","line":176,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n loop {\n match ready!(Pin::new(&mut self.inner).poll_frame(cx)?) {\n Some(frame) => match frame.into_data() {\n Ok(data) => return Poll::Ready(Some(Ok(data))),\n Err(_frame) => {}\n },\n None => return Poll::Ready(None),\n }\n }\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":189,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> (usize, Option) {\n let size_hint = self.inner.size_hint();\n let lower = usize::try_from(size_hint.lower()).unwrap_or_default();\n let upper = size_hint.upper().and_then(|v| usize::try_from(v).ok());\n (lower, upper)\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":202,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n mut self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n Pin::new(&mut self.inner).poll_frame(cx)\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":210,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n self.inner.is_end_stream()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":215,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> http_body::SizeHint {\n self.inner.size_hint()\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":236,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n let stream = self.project().stream.get_pin_mut();\n match ready!(stream.try_poll_next(cx)) {\n Some(Ok(chunk)) => Poll::Ready(Some(Ok(Frame::data(chunk.into())))),\n Some(Err(err)) => Poll::Ready(Some(Err(Error::new(err)))),\n None => Poll::Ready(None),\n }\n }"} {"repo":"axum","file":"axum-core/src/body.rs","line":250,"symbol":"test_try_downcast","kind":"function","lang":"rust","code":"fn test_try_downcast() {\n assert_eq!(try_downcast::(5_u32), Err(5_u32));\n assert_eq!(try_downcast::(5_i32), Ok(5_i32));\n}"} {"repo":"axum","file":"axum-core/src/error.rs","line":6,"symbol":"Error","kind":"type","lang":"rust","doc":"Errors that can happen when using axum.","code":"pub struct Error {\n inner: BoxError,\n}"} {"repo":"axum","file":"axum-core/src/error.rs","line":12,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `Error` from a boxable error.","code":"pub fn new(error: impl Into) -> Self {\n Self {\n inner: error.into(),\n }\n }"} {"repo":"axum","file":"axum-core/src/error.rs","line":20,"symbol":"into_inner","kind":"function","lang":"rust","doc":"Convert an `Error` back into the underlying boxed trait object.","code":"pub fn into_inner(self) -> BoxError {\n self.inner\n }"} {"repo":"axum","file":"axum-core/src/error.rs","line":26,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.inner.fmt(f)\n }"} {"repo":"axum","file":"axum-core/src/error.rs","line":32,"symbol":"source","kind":"function","lang":"rust","code":"fn source(&self) -> Option<&(dyn StdError + 'static)> {\n Some(&*self.inner)\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/mod.rs","line":12,"symbol":"State","kind":"type","lang":"rust","code":"pub(crate) struct State(pub(crate) S);"} {"repo":"axum","file":"axum-core/src/ext_traits/mod.rs","line":21,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n state: &OuterState,\n ) -> Result {\n let inner_state = InnerState::from_ref(state);\n Ok(Self(inner_state))\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/mod.rs","line":32,"symbol":"RequiresState","kind":"type","lang":"rust","doc":"some extractor that requires the state, such as `SignedCookieJar`","code":"pub(crate) struct RequiresState(pub(crate) String);"} {"repo":"axum","file":"axum-core/src/ext_traits/mod.rs","line":41,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n state: &S,\n ) -> Result {\n Ok(Self(String::from_ref(state)))\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":6,"symbol":"Sealed","kind":"type","lang":"rust","code":"pub trait Sealed {}"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":11,"symbol":"RequestExt","kind":"type","lang":"rust","doc":"Extension trait that adds additional methods to [`Request`].","code":"pub trait RequestExt: sealed::Sealed + Sized {\n /// Apply an extractor to this `Request`.\n ///\n /// This is just a convenience for `E::from_request(req, &())`.\n ///\n /// Note this consumes the request. Use [`RequestExt::extract_parts`] if you're not extracting\n /// the body and don't want to consume the request.\n ///\n /// # Example\n ///\n /// ```\n /// use axum::{\n /// extract::{Request, FromRequest},\n /// body::Body,\n /// http::{header::CONTENT_TYPE, StatusCode},\n /// response::{IntoResponse, Response},\n /// Form, Json, RequestExt,\n /// };\n ///\n /// struct FormOrJson(T);\n ///\n /// impl FromRequest for FormOrJson\n /// where\n /// Json: FromRequest<()>,\n /// Form: FromRequest<()>,\n /// T: 'static,\n /// S: Send + Sync,\n /// {\n /// type Rejection = Response;\n ///\n /// async fn from_request(req: Request, _state: &S) -> Result {\n /// let content_type = req\n /// .headers()\n /// .get(CONTENT_TYPE)\n /// .and_then(|value| value.to_str().ok())\n /// ."} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":68,"symbol":"extract","kind":"function","lang":"rust","doc":"} else { Err(StatusCode::BAD_REQUEST.into_response()) } } } ```","code":"fn extract(self) -> impl Future> + Send\n where\n E: FromRequest<(), M> + 'static,\n M: 'static;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":122,"symbol":"extract_with_state","kind":"function","lang":"rust","doc":"# type Rejection = std::convert::Infallible; # async fn from_request(req: Request, _state: &S) -> Result { # todo!() # } } ```","code":"fn extract_with_state(\n self,\n state: &S,\n ) -> impl Future> + Send\n where\n E: FromRequest + 'static,\n S: Send + Sync;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":178,"symbol":"extract_parts","kind":"function","lang":"rust","doc":".map_err(|err| err.into_response())?; Ok(Self { path_params, payload }) } } ```","code":"fn extract_parts(&mut self) -> impl Future> + Send\n where\n E: FromRequestParts<()> + 'static;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":243,"symbol":"extract_parts_with_state","kind":"function","lang":"rust","doc":"# type Rejection = std::convert::Infallible; # async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { # todo!() # } } ```","code":"fn extract_parts_with_state<'a, E, S>(\n &'a mut self,\n state: &'a S,\n ) -> impl Future> + Send + 'a\n where\n E: FromRequestParts + 'static,\n S: Send + Sync;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":254,"symbol":"with_limited_body","kind":"function","lang":"rust","doc":"Apply the [default body limit](crate::extract::DefaultBodyLimit). If it is disabled, the request is returned as-is.","code":"fn with_limited_body(self) -> Request;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":259,"symbol":"into_limited_body","kind":"function","lang":"rust","doc":"Consumes the request, returning the body wrapped in [`http_body_util::Limited`] if a [default limit](crate::extract::DefaultBodyLimit) is in place, or not wrapped if the default limit is disabled.","code":"fn into_limited_body(self) -> Body;"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":263,"symbol":"extract","kind":"function","lang":"rust","code":"fn extract(self) -> impl Future> + Send\n where\n E: FromRequest<(), M> + 'static,\n M: 'static,\n {\n self.extract_with_state(&())\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":271,"symbol":"extract_with_state","kind":"function","lang":"rust","code":"fn extract_with_state(\n self,\n state: &S,\n ) -> impl Future> + Send\n where\n E: FromRequest + 'static,\n S: Send + Sync,\n {\n E::from_request(self, state)\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":282,"symbol":"extract_parts","kind":"function","lang":"rust","code":"fn extract_parts(&mut self) -> impl Future> + Send\n where\n E: FromRequestParts<()> + 'static,\n {\n self.extract_parts_with_state(&())\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":289,"symbol":"extract_parts_with_state","kind":"function","lang":"rust","code":"async fn extract_parts_with_state<'a, E, S>(\n &'a mut self,\n state: &'a S,\n ) -> Result\n where\n E: FromRequestParts + 'static,\n S: Send + Sync,\n {\n let mut req = Request::new(());\n *req.version_mut() = self.version();\n *req.method_mut() = self.method().clone();\n *req.uri_mut() = self.uri().clone();\n *req.headers_mut() = std::mem::take(self.headers_mut());\n *req.extensions_mut() = std::mem::take(self.extensions_mut());\n let (mut parts, ()) = req.into_parts();\n\n let result = E::from_request_parts(&mut parts, state).await;\n\n *self.version_mut() = parts.version;\n *self.method_mut() = parts.method.clone();\n *self.uri_mut() = parts.uri.clone();\n *self.headers_mut() = std::mem::take(&mut parts.headers);\n *self.extensions_mut() = std::mem::take(&mut parts.extensions);\n\n result\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":316,"symbol":"with_limited_body","kind":"function","lang":"rust","code":"fn with_limited_body(self) -> Request {\n // update docs in `axum-core/src/extract/default_body_limit.rs` and\n // `axum/src/docs/extract.md` if this changes\n const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb\n\n match self.extensions().get::().copied() {\n Some(DefaultBodyLimitKind::Disable) => self,\n Some(DefaultBodyLimitKind::Limit(limit)) => {\n self.map(|b| Body::new(http_body_util::Limited::new(b, limit)))\n }\n None => self.map(|b| Body::new(http_body_util::Limited::new(b, DEFAULT_LIMIT))),\n }\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":330,"symbol":"into_limited_body","kind":"function","lang":"rust","code":"fn into_limited_body(self) -> Body {\n self.with_limited_body().into_body()\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":345,"symbol":"extract_without_state","kind":"function","lang":"rust","code":"async fn extract_without_state() {\n let req = Request::new(Body::empty());\n\n let method: Method = req.extract().await.unwrap();\n\n assert_eq!(method, Method::GET);\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":354,"symbol":"extract_body_without_state","kind":"function","lang":"rust","code":"async fn extract_body_without_state() {\n let req = Request::new(Body::from(\"foobar\"));\n\n let body: String = req.extract().await.unwrap();\n\n assert_eq!(body, \"foobar\");\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":363,"symbol":"extract_with_state","kind":"function","lang":"rust","code":"async fn extract_with_state() {\n let req = Request::new(Body::empty());\n\n let state = \"state\".to_owned();\n\n let State(extracted_state): State = req.extract_with_state(&state).await.unwrap();\n\n assert_eq!(extracted_state, state);\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":374,"symbol":"extract_parts_without_state","kind":"function","lang":"rust","code":"async fn extract_parts_without_state() {\n let mut req = Request::builder()\n .header(\"x-foo\", \"foo\")\n .body(Body::empty())\n .unwrap();\n\n let method: Method = req.extract_parts().await.unwrap();\n\n assert_eq!(method, Method::GET);\n assert_eq!(req.headers()[\"x-foo\"], \"foo\");\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":387,"symbol":"extract_parts_with_state","kind":"function","lang":"rust","code":"async fn extract_parts_with_state() {\n let mut req = Request::builder()\n .header(\"x-foo\", \"foo\")\n .body(Body::empty())\n .unwrap();\n\n let state = \"state\".to_owned();\n\n let State(extracted_state): State =\n req.extract_parts_with_state(&state).await.unwrap();\n\n assert_eq!(extracted_state, state);\n assert_eq!(req.headers()[\"x-foo\"], \"foo\");\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":404,"symbol":"WorksForCustomExtractor","kind":"type","lang":"rust","doc":"this stuff just needs to compile","code":"struct WorksForCustomExtractor {\n method: Method,\n from_state: String,\n body: String,\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request.rs","line":417,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(mut req: Request, state: &S) -> Result {\n let RequiresState(from_state) = req.extract_parts_with_state(state).await.unwrap();\n let method = req.extract_parts().await.unwrap();\n let body = req.extract().await?;\n\n Ok(Self {\n method,\n from_state,\n body,\n })\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":6,"symbol":"Sealed","kind":"type","lang":"rust","code":"pub trait Sealed {}"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":11,"symbol":"RequestPartsExt","kind":"type","lang":"rust","doc":"Extension trait that adds additional methods to [`Parts`].","code":"pub trait RequestPartsExt: sealed::Sealed + Sized {\n /// Apply an extractor to this `Parts`.\n ///\n /// This is just a convenience for `E::from_request_parts(parts, &())`.\n ///\n /// # Example\n ///\n /// ```\n /// use axum::{\n /// extract::{Query, Path, FromRequestParts},\n /// response::{Response, IntoResponse},\n /// http::request::Parts,\n /// RequestPartsExt,\n /// };\n /// use std::collections::HashMap;\n ///\n /// struct MyExtractor {\n /// path_params: HashMap,\n /// query_params: HashMap,\n /// }\n ///\n /// impl FromRequestParts for MyExtractor\n /// where\n /// S: Send + Sync,\n /// {\n /// type Rejection = Response;\n ///\n /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n /// let path_params = parts\n /// .extract::>>()\n /// .await\n /// .map(|Path(path_params)| path_params)\n /// .map_err(|err| err.into_response())?;\n ///\n /// let query_params = parts\n /// .extract::<"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":55,"symbol":"extract","kind":"function","lang":"rust","doc":".map_err(|err| err.into_response())?; Ok(MyExtractor { path_params, query_params }) } } ```","code":"fn extract(&mut self) -> impl Future> + Send\n where\n E: FromRequestParts<()> + 'static;"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":108,"symbol":"extract_with_state","kind":"function","lang":"rust","doc":"# type Rejection = std::convert::Infallible; # async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { # unimplemented!() # } } ```","code":"fn extract_with_state<'a, E, S>(\n &'a mut self,\n state: &'a S,\n ) -> impl Future> + Send + 'a\n where\n E: FromRequestParts + 'static,\n S: Send + Sync;"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":118,"symbol":"extract","kind":"function","lang":"rust","code":"fn extract(&mut self) -> impl Future> + Send\n where\n E: FromRequestParts<()> + 'static,\n {\n self.extract_with_state(&())\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":125,"symbol":"extract_with_state","kind":"function","lang":"rust","code":"fn extract_with_state<'a, E, S>(\n &'a mut self,\n state: &'a S,\n ) -> impl Future> + Send + 'a\n where\n E: FromRequestParts + 'static,\n S: Send + Sync,\n {\n E::from_request_parts(self, state)\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":149,"symbol":"extract_without_state","kind":"function","lang":"rust","code":"async fn extract_without_state() {\n let (mut parts, _) = Request::new(()).into_parts();\n\n let method: Method = parts.extract().await.unwrap();\n\n assert_eq!(method, Method::GET);\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":158,"symbol":"extract_with_state","kind":"function","lang":"rust","code":"async fn extract_with_state() {\n let (mut parts, _) = Request::new(()).into_parts();\n\n let state = \"state\".to_owned();\n\n let State(extracted_state): State = parts\n .extract_with_state::, String>(&state)\n .await\n .unwrap();\n\n assert_eq!(extracted_state, state);\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":173,"symbol":"WorksForCustomExtractor","kind":"type","lang":"rust","doc":"this stuff just needs to compile","code":"struct WorksForCustomExtractor {\n method: Method,\n from_state: String,\n }"} {"repo":"axum","file":"axum-core/src/ext_traits/request_parts.rs","line":185,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let RequiresState(from_state) = parts.extract_with_state(state).await?;\n let method = parts.extract().await?;\n\n Ok(Self { method, from_state })\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":78,"symbol":"DefaultBodyLimit","kind":"type","lang":"rust","doc":"[`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html [`FromRequest`]: crate::extract::FromRequest [`RequestBodyLimit`]: tower_http::limit::RequestBodyLimit [`RequestExt::with_limited_body`]: crate::RequestExt::with_limited_body [`RequestExt::into_limited_body`]: crate::RequestExt::into_limited_body","code":"pub struct DefaultBodyLimit {\n kind: DefaultBodyLimitKind,\n}"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":83,"symbol":"DefaultBodyLimitKind","kind":"type","lang":"rust","code":"pub(crate) enum DefaultBodyLimitKind {\n Disable,\n Limit(usize),\n}"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":119,"symbol":"disable","kind":"function","lang":"rust","doc":".layer(RequestBodyLimitLayer::new(10 * 1000 * 1000)); ``` [`Bytes`]: bytes::Bytes [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html","code":"pub const fn disable() -> Self {\n Self {\n kind: DefaultBodyLimitKind::Disable,\n }\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":150,"symbol":"max","kind":"function","lang":"rust","doc":".layer(DefaultBodyLimit::max(1024)); ``` [`Bytes::from_request`]: bytes::Bytes [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html","code":"pub const fn max(limit: usize) -> Self {\n Self {\n kind: DefaultBodyLimitKind::Limit(limit),\n }\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":182,"symbol":"apply","kind":"function","lang":"rust","doc":"async fn from_request(mut req: Request, _: &S) -> Result { DefaultBodyLimit::max(1024).apply(&mut req); Ok(Self(Bytes::from_request(req, &()).await?)) } } ```","code":"pub fn apply(self, req: &mut Request) {\n req.extensions_mut().insert(self.kind);\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":190,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n DefaultBodyLimitService {\n inner,\n kind: self.kind,\n }\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":205,"symbol":"DefaultBodyLimitService","kind":"type","lang":"rust","code":"pub struct DefaultBodyLimitService {\n pub(super) inner: S,\n pub(super) kind: DefaultBodyLimitKind,\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":219,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> std::task::Poll> {\n self.inner.poll_ready(cx)\n }"} {"repo":"axum","file":"axum-core/src/extract/default_body_limit.rs","line":224,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, mut req: Request) -> Self::Future {\n req.extensions_mut().insert(self.kind);\n self.inner.call(req)\n }"} {"repo":"axum","file":"axum-core/src/extract/from_ref.rs","line":14,"symbol":"FromRef","kind":"type","lang":"rust","doc":"This trait can be derived using `#[derive(FromRef)]`. [`State`]: https://docs.rs/axum/0.8/axum/extract/struct.State.html [sharing-state]: https://docs.rs/axum/0.8/axum/index.html#sharing-state-with-handlers NOTE: This trait is defined in axum-core, even though it is mainly used with `State` which is defined in axum. That allows crate authors to use it when implementing extractors.","code":"pub trait FromRef {\n /// Converts to this type from a reference to the input type.\n fn from_ref(input: &T) -> Self;\n}"} {"repo":"axum","file":"axum-core/src/extract/from_ref.rs","line":16,"symbol":"from_ref","kind":"function","lang":"rust","doc":"Converts to this type from a reference to the input type.","code":"fn from_ref(input: &T) -> Self;"} {"repo":"axum","file":"axum-core/src/extract/from_ref.rs","line":23,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &T) -> Self {\n input.clone()\n }"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":34,"symbol":"ViaParts","kind":"type","lang":"rust","code":"pub enum ViaParts {}"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":38,"symbol":"ViaRequest","kind":"type","lang":"rust","code":"pub enum ViaRequest {}"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":55,"symbol":"FromRequestParts","kind":"type","lang":"rust","code":"pub trait FromRequestParts: Sized {\n /// If the extractor fails it'll use this \"rejection\" type. A rejection is\n /// a kind of error that can be converted into a response.\n type Rejection: IntoResponse;\n\n /// Perform the extraction.\n fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> impl Future> + Send;\n}"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":61,"symbol":"from_request_parts","kind":"function","lang":"rust","doc":"Perform the extraction.","code":"fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> impl Future> + Send;"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":81,"symbol":"FromRequest","kind":"type","lang":"rust","code":"pub trait FromRequest: Sized {\n /// If the extractor fails it'll use this \"rejection\" type. A rejection is\n /// a kind of error that can be converted into a response.\n type Rejection: IntoResponse;\n\n /// Perform the extraction.\n fn from_request(\n req: Request,\n state: &S,\n ) -> impl Future> + Send;\n}"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":87,"symbol":"from_request","kind":"function","lang":"rust","doc":"Perform the extraction.","code":"fn from_request(\n req: Request,\n state: &S,\n ) -> impl Future> + Send;"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":100,"symbol":"from_request","kind":"function","lang":"rust","code":"fn from_request(\n req: Request,\n state: &S,\n ) -> impl Future> {\n let (mut parts, _) = req.into_parts();\n async move { Self::from_request_parts(&mut parts, state).await }\n }"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":116,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n Ok(T::from_request_parts(parts, state).await)\n }"} {"repo":"axum","file":"axum-core/src/extract/mod.rs","line":128,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n Ok(T::from_request(req, state).await)\n }"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":11,"symbol":"OptionalFromRequestParts","kind":"type","lang":"rust","doc":"Customize the behavior of `Option` as a [`FromRequestParts`] extractor.","code":"pub trait OptionalFromRequestParts: Sized {\n /// If the extractor fails, it will use this \"rejection\" type.\n ///\n /// A rejection is a kind of error that can be converted into a response.\n type Rejection: IntoResponse;\n\n /// Perform the extraction.\n fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> impl Future, Self::Rejection>> + Send;\n}"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":18,"symbol":"from_request_parts","kind":"function","lang":"rust","doc":"Perform the extraction.","code":"fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> impl Future, Self::Rejection>> + Send;"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":25,"symbol":"OptionalFromRequest","kind":"type","lang":"rust","doc":"Customize the behavior of `Option` as a [`FromRequest`] extractor.","code":"pub trait OptionalFromRequest: Sized {\n /// If the extractor fails, it will use this \"rejection\" type.\n ///\n /// A rejection is a kind of error that can be converted into a response.\n type Rejection: IntoResponse;\n\n /// Perform the extraction.\n fn from_request(\n req: Request,\n state: &S,\n ) -> impl Future, Self::Rejection>> + Send;\n}"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":32,"symbol":"from_request","kind":"function","lang":"rust","doc":"Perform the extraction.","code":"fn from_request(\n req: Request,\n state: &S,\n ) -> impl Future, Self::Rejection>> + Send;"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":49,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> impl Future, Self::Rejection>> {\n T::from_request_parts(parts, state)\n }"} {"repo":"axum","file":"axum-core/src/extract/option.rs","line":66,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result, Self::Rejection> {\n T::from_request(req, state).await\n }"} {"repo":"axum","file":"axum-core/src/extract/rejection.rs","line":18,"symbol":"from_err","kind":"function","lang":"rust","code":"pub(crate) fn from_err(err: E) -> Self\n where\n E: Into,\n {\n // peel any number of `axum_core::Error` wrappers to reach the underlying source error\n let mut box_error = err.into();\n loop {\n match box_error.downcast::() {\n Ok(unwrapped) => {\n box_error = unwrapped.into_inner();\n }\n Err(err) => {\n box_error = err;\n break;\n }\n }\n }\n match box_error.downcast::() {\n Ok(err) => Self::LengthLimitError(LengthLimitError::from_err(err)),\n Err(err) => Self::UnknownBodyError(UnknownBodyError::from_err(err)),\n }\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":14,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _: &S) -> Result {\n Ok(req)\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":25,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _: &S) -> Result {\n Ok(parts.method.clone())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":36,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _: &S) -> Result {\n Ok(parts.uri.clone())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":47,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _: &S) -> Result {\n Ok(parts.version)\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":63,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _: &S) -> Result {\n Ok(parts.headers.clone())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":75,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _: &S) -> Result {\n let mut body = req.into_limited_body();\n #[allow(clippy::use_self)]\n let mut bytes = BytesMut::new();\n body_to_bytes_mut(&mut body, &mut bytes).await?;\n Ok(bytes)\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":84,"symbol":"body_to_bytes_mut","kind":"function","lang":"rust","code":"async fn body_to_bytes_mut(body: &mut Body, bytes: &mut BytesMut) -> Result<(), BytesRejection> {\n while let Some(frame) = body\n .frame()\n .await\n .transpose()\n .map_err(FailedToBufferBody::from_err)?\n {\n let Ok(data) = frame.into_data() else {\n // Match `Bytes` by ignoring non-data frames until the body ends.\n continue;\n };\n bytes.put(data);\n }\n\n Ok(())\n}"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":107,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _: &S) -> Result {\n let bytes = req\n .into_limited_body()\n .collect()\n .await\n .map_err(FailedToBufferBody::from_err)?\n .to_bytes();\n\n Ok(bytes)\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":125,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let bytes = Bytes::from_request(req, state)\n .await\n .map_err(|err| match err {\n BytesRejection::FailedToBufferBody(inner) => {\n StringRejection::FailedToBufferBody(inner)\n }\n })?;\n\n #[allow(clippy::use_self)]\n let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?;\n\n Ok(string)\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":148,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n Ok(parts.clone())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":160,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n Ok(parts.extensions.clone())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":171,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _: &S) -> Result {\n Ok(req.into_body())\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":182,"symbol":"extract_request_parts","kind":"function","lang":"rust","code":"async fn extract_request_parts() {\n #[derive(Clone)]\n struct Ext;\n\n async fn handler(parts: http::request::Parts) {\n assert_eq!(parts.method, Method::GET);\n assert_eq!(parts.uri, \"/\");\n assert_eq!(parts.version, http::Version::HTTP_11);\n assert_eq!(parts.headers[\"x-foo\"], \"123\");\n parts.extensions.get::().unwrap();\n }\n\n let client = TestClient::new(Router::new().route(\"/\", get(handler)).layer(Extension(Ext)));\n\n let res = client.get(\"/\").header(\"x-foo\", \"123\").await;\n assert_eq!(res.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":184,"symbol":"Ext","kind":"type","lang":"rust","code":"struct Ext;"} {"repo":"axum","file":"axum-core/src/extract/request_parts.rs","line":186,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(parts: http::request::Parts) {\n assert_eq!(parts.method, Method::GET);\n assert_eq!(parts.uri, \"/\");\n assert_eq!(parts.version, http::Version::HTTP_11);\n assert_eq!(parts.headers[\"x-foo\"], \"123\");\n parts.extensions.get::().unwrap();\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":13,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_: &mut Parts, _: &S) -> Result<(), Self::Rejection> {\n Ok(())\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":86,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\n where\n T: FromRequest<(), M>,\n {\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":92,"symbol":"assert_from_request_parts","kind":"function","lang":"rust","code":"fn assert_from_request_parts>() {}"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":95,"symbol":"unit","kind":"function","lang":"rust","code":"fn unit() {\n assert_from_request_parts::<()>();\n assert_from_request::<_, ()>();\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":101,"symbol":"tuple_of_one","kind":"function","lang":"rust","code":"fn tuple_of_one() {\n assert_from_request_parts::<(Method,)>();\n assert_from_request::<_, (Method,)>();\n assert_from_request::<_, (Bytes,)>();\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":108,"symbol":"tuple_of_two","kind":"function","lang":"rust","code":"fn tuple_of_two() {\n assert_from_request_parts::<((), ())>();\n assert_from_request::<_, ((), ())>();\n assert_from_request::<_, (Method, Bytes)>();\n }"} {"repo":"axum","file":"axum-core/src/extract/tuple.rs","line":115,"symbol":"nested_tuple","kind":"function","lang":"rust","code":"fn nested_tuple() {\n assert_from_request_parts::<(((Method,),),)>();\n assert_from_request::<_, ((((Bytes,),),),)>();\n }"} {"repo":"axum","file":"axum-core/src/macros.rs","line":346,"symbol":"source_gives_inner_source","kind":"function","lang":"rust","doc":"The implementation of `.source()` on `Outer` should defer straight to the implementation on its inner type instead of returning the inner type itself, because the `Display` implementation on `Outer` already forwards to the inner type and so it would result in two errors in the chain `Display`ing the same thing.","code":"fn source_gives_inner_source() {\n let rejection = Outer::Inner1(Inner1);\n assert!(rejection.source().is_none());\n\n let msg = \"hello world\";\n let rejection = Outer::Inner2(Inner2(Error::new(msg)));\n assert_eq!(rejection.source().unwrap().to_string(), msg);\n }"} {"repo":"axum","file":"axum-core/src/response/append_headers.rs","line":34,"symbol":"AppendHeaders","kind":"type","lang":"rust","doc":"(SET_COOKIE, \"foo=bar\"), (SET_COOKIE, \"baz=qux\"), ]) ) } ```","code":"pub struct AppendHeaders(pub I);"} {"repo":"axum","file":"axum-core/src/response/append_headers.rs","line":44,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/append_headers.rs","line":59,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n for (key, value) in self.0 {\n let key = key.try_into().map_err(TryIntoHeaderError::key)?;\n let value = value.try_into().map_err(TryIntoHeaderError::value)?;\n res.headers_mut().append(key, value);\n }\n\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":115,"symbol":"IntoResponse","kind":"type","lang":"rust","code":"pub trait IntoResponse {\n /// Create a response.\n #[must_use]\n fn into_response(self) -> Response;\n}"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":118,"symbol":"into_response","kind":"function","lang":"rust","doc":"Create a response.","code":"fn into_response(self) -> Response;"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":122,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n *res.status_mut() = self;\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":130,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Body::unknown().into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":136,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self {}\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":146,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self {\n Ok(value) => value.into_response(),\n Err(err) => err.into_response(),\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":159,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.map(Body::new)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":165,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Response::from_parts(self, Body::empty())\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":171,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Response::new(self)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":177,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Cow::Borrowed(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":183,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Cow::<'static, str>::Owned(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":189,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n String::from(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":195,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = Body::from(self).into_response();\n res.headers_mut().insert(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),\n );\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":206,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = Body::from(self).into_response();\n res.headers_mut().insert(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),\n );\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":217,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.freeze().into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":227,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (first, second) = self.into_inner();\n let mut res = Response::new(Body::new(BytesChainBody {\n first: Some(first),\n second: Some(second),\n }));\n res.headers_mut().insert(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),\n );\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":241,"symbol":"BytesChainBody","kind":"type","lang":"rust","code":"struct BytesChainBody {\n first: Option,\n second: Option,\n}"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":254,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n mut self: Pin<&mut Self>,\n _cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n if let Some(mut buf) = self.first.take() {\n let bytes = buf.copy_to_bytes(buf.remaining());\n return Poll::Ready(Some(Ok(Frame::data(bytes))));\n }\n\n if let Some(mut buf) = self.second.take() {\n let bytes = buf.copy_to_bytes(buf.remaining());\n return Poll::Ready(Some(Ok(Frame::data(bytes))));\n }\n\n Poll::Ready(None)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":271,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n self.first.is_none() && self.second.is_none()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":275,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> SizeHint {\n match (self.first.as_ref(), self.second.as_ref()) {\n (Some(first), Some(second)) => {\n let total_size = first.remaining() + second.remaining();\n SizeHint::with_exact(total_size as u64)\n }\n (Some(buf), None) => SizeHint::with_exact(buf.remaining() as u64),\n (None, Some(buf)) => SizeHint::with_exact(buf.remaining() as u64),\n (None, None) => SizeHint::with_exact(0),\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":289,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Cow::Borrowed(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":295,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.as_slice().into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":301,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.to_vec().into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":307,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Cow::<'static, [u8]>::Owned(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":313,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Vec::from(self).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":319,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = Body::from(self).into_response();\n res.headers_mut().insert(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),\n );\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":333,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = self.1.into_response();\n if res.extensions().get::().is_none() {\n *res.status_mut() = self.0;\n }\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":343,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n *res.headers_mut() = self;\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":351,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n *res.extensions_mut() = self;\n res\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":365,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":374,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (parts, res) = self;\n (parts.status, parts.headers, parts.extensions, res).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":384,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (template, res) = self;\n let (parts, ()) = template.into_parts();\n (parts, res).into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response.rs","line":395,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (res,) = self;\n res.into_response()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":76,"symbol":"IntoResponseParts","kind":"type","lang":"rust","code":"pub trait IntoResponseParts {\n /// The type returned in the event of an error.\n ///\n /// This can be used to fallibly convert types into headers or extensions.\n type Error: IntoResponse;\n\n /// Set parts of the response\n fn into_response_parts(self, res: ResponseParts) -> Result;\n}"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":83,"symbol":"into_response_parts","kind":"function","lang":"rust","doc":"Set parts of the response","code":"fn into_response_parts(self, res: ResponseParts) -> Result;"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":92,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, res: ResponseParts) -> Result {\n if let Some(inner) = self {\n inner.into_response_parts(res)\n } else {\n Ok(res)\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":105,"symbol":"ResponseParts","kind":"type","lang":"rust","doc":"Parts of a response. Used with [`IntoResponseParts`].","code":"pub struct ResponseParts {\n pub(crate) res: Response,\n}"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":112,"symbol":"status","kind":"function","lang":"rust","doc":"Gets the response status code.","code":"pub fn status(&self) -> StatusCode {\n self.res.status()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":118,"symbol":"status_mut","kind":"function","lang":"rust","doc":"Gets a mutable reference to the response status code.","code":"pub fn status_mut(&mut self) -> &mut StatusCode {\n self.res.status_mut()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":124,"symbol":"headers","kind":"function","lang":"rust","doc":"Gets a reference to the response headers.","code":"pub fn headers(&self) -> &HeaderMap {\n self.res.headers()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":130,"symbol":"headers_mut","kind":"function","lang":"rust","doc":"Gets a mutable reference to the response headers.","code":"pub fn headers_mut(&mut self) -> &mut HeaderMap {\n self.res.headers_mut()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":136,"symbol":"extensions","kind":"function","lang":"rust","doc":"Gets a reference to the response extensions.","code":"pub fn extensions(&self) -> &Extensions {\n self.res.extensions()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":142,"symbol":"extensions_mut","kind":"function","lang":"rust","doc":"Gets a mutable reference to the response extensions.","code":"pub fn extensions_mut(&mut self) -> &mut Extensions {\n self.res.extensions_mut()\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":150,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n res.headers_mut().extend(self);\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":165,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n for (key, value) in self {\n let key = key.try_into().map_err(TryIntoHeaderError::key)?;\n let value = value.try_into().map_err(TryIntoHeaderError::value)?;\n res.headers_mut().insert(key, value);\n }\n\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":178,"symbol":"TryIntoHeaderError","kind":"type","lang":"rust","doc":"Error returned if converting a value to a header fails.","code":"pub struct TryIntoHeaderError {\n kind: TryIntoHeaderErrorKind,\n}"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":183,"symbol":"key","kind":"function","lang":"rust","code":"pub(super) fn key(err: K) -> Self {\n Self {\n kind: TryIntoHeaderErrorKind::Key(err),\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":189,"symbol":"value","kind":"function","lang":"rust","code":"pub(super) fn value(err: V) -> Self {\n Self {\n kind: TryIntoHeaderErrorKind::Value(err),\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":197,"symbol":"TryIntoHeaderErrorKind","kind":"type","lang":"rust","code":"enum TryIntoHeaderErrorKind {\n Key(K),\n Value(V),\n}"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":207,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self.kind {\n TryIntoHeaderErrorKind::Key(inner) => {\n (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response()\n }\n TryIntoHeaderErrorKind::Value(inner) => {\n (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response()\n }\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":220,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self.kind {\n TryIntoHeaderErrorKind::Key(_) => write!(f, \"failed to convert key to a header name\"),\n TryIntoHeaderErrorKind::Value(_) => {\n write!(f, \"failed to convert value to a header value\")\n }\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":235,"symbol":"source","kind":"function","lang":"rust","code":"fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n match &self.kind {\n TryIntoHeaderErrorKind::Key(inner) => Some(inner),\n TryIntoHeaderErrorKind::Value(inner) => Some(inner),\n }\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":277,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n res.extensions_mut().extend(self);\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":286,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, res: ResponseParts) -> Result {\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/into_response_parts.rs","line":298,"symbol":"failed_into_response_parts","kind":"function","lang":"rust","code":"fn failed_into_response_parts() {\n let response = (StatusCode::CREATED, [(\"\\n\", \"\\n\")]).into_response();\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n\n let response = (StatusCode::CREATED, [(\"\\n\", \"\\n\")], ()).into_response();\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n }"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":112,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self {\n Ok(ok) => ok.into_response(),\n Err(err) => err.0,\n }\n }"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":125,"symbol":"ErrorResponse","kind":"type","lang":"rust","doc":"An [`IntoResponse`]-based error type See [`Result`] for more details.","code":"pub struct ErrorResponse(Response);"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":131,"symbol":"from","kind":"function","lang":"rust","code":"fn from(value: T) -> Self {\n Self(value.into_response())\n }"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":171,"symbol":"IntoResponseFailed","kind":"type","lang":"rust","doc":"`IntoResponseFailed` as a response extension, and the 201 Created override is ignored. This is a behavior introduced with axum 0.9.\\ To force a status code override even when an inner [`IntoResponseParts`] / [`IntoResponse`] failed, use [`ForceStatusCode`].","code":"pub struct IntoResponseFailed;"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":176,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n res.extensions_mut().insert(self);\n Ok(res)\n }"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":192,"symbol":"into_response_failed_doesnt_impl_into_response","kind":"function","lang":"rust","doc":"```compile_fail fn foo() where axum_core::response::IntoResponseFailed: axum_core::response::IntoResponse, {} ```","code":"fn into_response_failed_doesnt_impl_into_response() {}"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":198,"symbol":"ForceStatusCode","kind":"type","lang":"rust","doc":"Set the status code regardless of whether [`IntoResponseFailed`] is used or not. See the docs for [`IntoResponseFailed`] for more details.","code":"pub struct ForceStatusCode(pub StatusCode);"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":201,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n *res.status_mut() = self.0;\n res\n }"} {"repo":"axum","file":"axum-core/src/response/mod.rs","line":212,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (ForceStatusCode(status), res) = self;\n let mut res = res.into_response();\n *res.status_mut() = status;\n res\n }"} {"repo":"axum","file":"axum-extra/src/body/async_read_body.rs","line":59,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `AsyncReadBody`.","code":"pub fn new(read: R) -> Self\n where\n R: AsyncRead + Send + 'static,\n {\n Self {\n body: Body::from_stream(ReaderStream::new(read)),\n }\n }"} {"repo":"axum","file":"axum-extra/src/body/async_read_body.rs","line":74,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n self.project().body.poll_frame(cx)\n }"} {"repo":"axum","file":"axum-extra/src/body/async_read_body.rs","line":82,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n self.body.is_end_stream()\n }"} {"repo":"axum","file":"axum-extra/src/body/async_read_body.rs","line":87,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> http_body::SizeHint {\n self.body.size_hint()\n }"} {"repo":"axum","file":"axum-extra/src/body/async_read_body.rs","line":93,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.body.into_response()\n }"} {"repo":"axum","file":"axum-extra/src/either.rs","line":108,"symbol":"Either","kind":"type","lang":"rust","doc":"Combines two extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":120,"symbol":"Either3","kind":"type","lang":"rust","doc":"Combines three extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either3 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":134,"symbol":"Either4","kind":"type","lang":"rust","doc":"Combines four extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either4 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n #[allow(missing_docs)]\n E4(E4),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":150,"symbol":"Either5","kind":"type","lang":"rust","doc":"Combines five extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either5 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n #[allow(missing_docs)]\n E4(E4),\n #[allow(missing_docs)]\n E5(E5),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":168,"symbol":"Either6","kind":"type","lang":"rust","doc":"Combines six extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either6 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n #[allow(missing_docs)]\n E4(E4),\n #[allow(missing_docs)]\n E5(E5),\n #[allow(missing_docs)]\n E6(E6),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":188,"symbol":"Either7","kind":"type","lang":"rust","doc":"Combines seven extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either7 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n #[allow(missing_docs)]\n E4(E4),\n #[allow(missing_docs)]\n E5(E5),\n #[allow(missing_docs)]\n E6(E6),\n #[allow(missing_docs)]\n E7(E7),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":210,"symbol":"Either8","kind":"type","lang":"rust","doc":"Combines eight extractors or responses into a single type. See the [module docs](self) for examples.","code":"pub enum Either8 {\n #[allow(missing_docs)]\n E1(E1),\n #[allow(missing_docs)]\n E2(E2),\n #[allow(missing_docs)]\n E3(E3),\n #[allow(missing_docs)]\n E4(E4),\n #[allow(missing_docs)]\n E5(E5),\n #[allow(missing_docs)]\n E6(E6),\n #[allow(missing_docs)]\n E7(E7),\n #[allow(missing_docs)]\n E8(E8),\n}"} {"repo":"axum","file":"axum-extra/src/either.rs","line":284,"symbol":"layer","kind":"function","lang":"rust","code":"fn layer(&self, inner: S) -> Self::Service {\n match self {\n Self::E1(layer) => Either::E1(layer.layer(inner)),\n Self::E2(layer) => Either::E2(layer.layer(inner)),\n }\n }"} {"repo":"axum","file":"axum-extra/src/either.rs","line":301,"symbol":"poll_ready","kind":"function","lang":"rust","code":"fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> {\n match self {\n Self::E1(inner) => inner.poll_ready(cx),\n Self::E2(inner) => inner.poll_ready(cx),\n }\n }"} {"repo":"axum","file":"axum-extra/src/either.rs","line":308,"symbol":"call","kind":"function","lang":"rust","code":"fn call(&mut self, req: R) -> Self::Future {\n match self {\n Self::E1(inner) => futures_util::future::Either::Left(inner.call(req)),\n Self::E2(inner) => futures_util::future::Either::Right(inner.call(req)),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":78,"symbol":"Cached","kind":"type","lang":"rust","doc":") { // ... } ``` [request extensions]: http::Extensions","code":"pub struct Cached(pub T);"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":81,"symbol":"CachedEntry","kind":"type","lang":"rust","code":"struct CachedEntry(T);"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":90,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n if let Some(value) = parts.extensions.get::>() {\n Ok(Self(value.0.clone()))\n } else {\n let value = T::from_request_parts(parts, state).await?;\n parts.extensions.insert(CachedEntry(value.clone()));\n Ok(Self(value))\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":114,"symbol":"works","kind":"function","lang":"rust","code":"async fn works() {\n static COUNTER: AtomicU32 = AtomicU32::new(0);\n\n #[derive(Clone, Debug, PartialEq, Eq)]\n struct Extractor(Instant);\n\n impl FromRequestParts for Extractor\n where\n S: Send + Sync,\n {\n type Rejection = Infallible;\n\n async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n COUNTER.fetch_add(1, Ordering::SeqCst);\n Ok(Self(Instant::now()))\n }\n }\n\n let (mut parts, _) = Request::new(()).into_parts();\n\n let first = Cached::::from_request_parts(&mut parts, &())\n .await\n .unwrap()\n .0;\n assert_eq!(COUNTER.load(Ordering::SeqCst), 1);\n\n let second = Cached::::from_request_parts(&mut parts, &())\n .await\n .unwrap()\n .0;\n assert_eq!(COUNTER.load(Ordering::SeqCst), 1);\n\n assert_eq!(first, second);\n }"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":118,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(Instant);"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":126,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n COUNTER.fetch_add(1, Ordering::SeqCst);\n Ok(Self(Instant::now()))\n }"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":153,"symbol":"_last_handler_argument","kind":"function","lang":"rust","doc":"Not a #[test], we just want to know this compiles","code":"async fn _last_handler_argument() {\n async fn handler(_: http::Method, _: Cached) {}\n let _r: Router = Router::new().route(\"/\", get(handler));\n }"} {"repo":"axum","file":"axum-extra/src/extract/cached.rs","line":154,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: http::Method, _: Cached) {}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":100,"symbol":"CookieJar","kind":"type","lang":"rust","doc":"let app = Router::new() .route(\"/sessions\", post(create_session)) .route(\"/me\", get(me)); # let app: Router = app; ```","code":"pub struct CookieJar {\n jar: cookie::CookieJar,\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":110,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n Ok(Self::from_headers(&parts.headers))\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":115,"symbol":"cookies_from_request","kind":"function","lang":"rust","code":"fn cookies_from_request(headers: &HeaderMap) -> impl Iterator> + '_ {\n headers\n .get_all(COOKIE)\n .into_iter()\n .filter_map(|value| value.to_str().ok())\n .flat_map(|value| value.split(';'))\n .filter_map(|cookie| Cookie::parse_encoded(cookie.to_owned()).ok())\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":133,"symbol":"from_headers","kind":"function","lang":"rust","doc":"The cookies in `headers` will be added to the jar. This is intended to be used in middleware and other places where it might be difficult to run extractors. Normally you should create `CookieJar`s through [`FromRequestParts`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn from_headers(headers: &HeaderMap) -> Self {\n let mut jar = cookie::CookieJar::new();\n for cookie in cookies_from_request(headers) {\n jar.add_original(cookie);\n }\n Self { jar }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":150,"symbol":"new","kind":"function","lang":"rust","doc":"run extractors. Normally you should create `CookieJar`s through [`FromRequestParts`]. If you need a jar that contains the headers from a request, use [`CookieJar::from_headers`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn new() -> Self {\n Self::default()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":169,"symbol":"get","kind":"function","lang":"rust","doc":"async fn handle(jar: CookieJar) { let value: Option = jar .get(\"foo\") .map(|cookie| cookie.value().to_owned()); } ```","code":"pub fn get(&self, name: &str) -> Option<&Cookie<'static>> {\n self.jar.get(name)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":185,"symbol":"remove","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: CookieJar) -> CookieJar { jar.remove(Cookie::from(\"foo\")) } ```","code":"pub fn remove>>(mut self, cookie: C) -> Self {\n self.jar.remove(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":205,"symbol":"add","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: CookieJar) -> CookieJar { jar.add(Cookie::new(\"foo\", \"bar\")) } ```","code":"pub fn add>>(mut self, cookie: C) -> Self {\n self.jar.add(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":211,"symbol":"iter","kind":"function","lang":"rust","doc":"Get an iterator over all cookies in the jar.","code":"pub fn iter(&self) -> impl Iterator> {\n self.jar.iter()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":219,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n set_cookies(&self.jar, res.headers_mut());\n Ok(res)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":226,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":231,"symbol":"set_cookies","kind":"function","lang":"rust","code":"fn set_cookies(jar: &cookie::CookieJar, headers: &mut HeaderMap) {\n for cookie in jar.delta() {\n if let Ok(header_value) = cookie.encoded().to_string().parse() {\n headers.append(SET_COOKIE, header_value);\n }\n }\n\n // we don't need to call `jar.reset_delta()` because `into_response_parts` consumes the cookie\n // jar so it cannot be called multiple times.\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":329,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n key: Key,\n custom_key: CustomKey,\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":335,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(state: &AppState) -> Self {\n state.key.clone()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":341,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(state: &AppState) -> Self {\n state.custom_key.clone()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":347,"symbol":"CustomKey","kind":"type","lang":"rust","code":"struct CustomKey(Key);"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":350,"symbol":"from","kind":"function","lang":"rust","code":"fn from(custom: CustomKey) -> Self {\n custom.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":357,"symbol":"signed_cannot_access_invalid_cookies","kind":"function","lang":"rust","code":"async fn signed_cannot_access_invalid_cookies() {\n async fn get_cookie(jar: SignedCookieJar) -> impl IntoResponse {\n format!(\"{:?}\", jar.get(\"key\"))\n }\n\n let state = AppState {\n key: Key::generate(),\n custom_key: CustomKey(Key::generate()),\n };\n\n let app = Router::new()\n .route(\"/get\", get(get_cookie))\n .with_state(state);\n\n let res = app\n .clone()\n .oneshot(\n Request::builder()\n .uri(\"/get\")\n .header(\"cookie\", \"key=value\")\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n let body = body_text(res).await;\n assert_eq!(body, \"None\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":358,"symbol":"get_cookie","kind":"function","lang":"rust","code":"async fn get_cookie(jar: SignedCookieJar) -> impl IntoResponse {\n format!(\"{:?}\", jar.get(\"key\"))\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/mod.rs","line":386,"symbol":"body_text","kind":"function","lang":"rust","code":"async fn body_text(body: B) -> String\n where\n B: axum::body::HttpBody,\n B::Error: std::fmt::Debug,\n {\n let bytes = body.collect().await.unwrap().to_bytes();\n String::from_utf8(bytes.to_vec()).unwrap()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":108,"symbol":"PrivateCookieJar","kind":"type","lang":"rust","doc":"impl FromRef for Key { fn from_ref(state: &AppState) -> Self { state.0.key.clone() } } ```","code":"pub struct PrivateCookieJar {\n jar: cookie::CookieJar,\n key: Key,\n // The key used to extract the key. Allows users to use multiple keys for different\n // jars. Maybe a library wants its own key.\n _marker: PhantomData,\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":117,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"PrivateCookieJar\")\n .field(\"jar\", &self.jar)\n .field(\"key\", &\"REDACTED\")\n .finish()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":132,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let k = K::from_ref(state);\n let key = k.into();\n let PrivateCookieJar {\n jar,\n key,\n _marker: _,\n } = PrivateCookieJar::from_headers(&parts.headers, key);\n Ok(Self {\n jar,\n key,\n _marker: PhantomData,\n })\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":157,"symbol":"from_headers","kind":"function","lang":"rust","doc":"The valid cookies in `headers` will be added to the jar. This is intended to be used in middleware and other places where it might be difficult to run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequestParts`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn from_headers(headers: &HeaderMap, key: Key) -> Self {\n let mut jar = cookie::CookieJar::new();\n let mut private_jar = jar.private_mut(&key);\n for cookie in cookies_from_request(headers) {\n if let Some(cookie) = private_jar.decrypt(cookie) {\n private_jar.add_original(cookie);\n }\n }\n\n Self {\n jar,\n key,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":179,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new empty `PrivateCookieJarIter`. This is intended to be used in middleware and other places where it might be difficult to run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequestParts`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn new(key: Key) -> Self {\n Self {\n jar: Default::default(),\n key,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":206,"symbol":"get","kind":"function","lang":"rust","doc":"async fn handle(jar: PrivateCookieJar) { let value: Option = jar .get(\"foo\") .map(|cookie| cookie.value().to_owned()); } ```","code":"pub fn get(&self, name: &str) -> Option> {\n self.private_jar().get(name)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":222,"symbol":"remove","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: PrivateCookieJar) -> PrivateCookieJar { jar.remove(Cookie::from(\"foo\")) } ```","code":"pub fn remove>>(mut self, cookie: C) -> Self {\n self.private_jar_mut().remove(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":242,"symbol":"add","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: PrivateCookieJar) -> PrivateCookieJar { jar.add(Cookie::new(\"foo\", \"bar\")) } ```","code":"pub fn add>>(mut self, cookie: C) -> Self {\n self.private_jar_mut().add(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":250,"symbol":"decrypt","kind":"function","lang":"rust","doc":"Authenticates and decrypts `cookie`, returning the plaintext version if decryption succeeds or `None` otherwise.","code":"pub fn decrypt(&self, cookie: Cookie<'static>) -> Option> {\n self.private_jar().decrypt(cookie)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":257,"symbol":"iter","kind":"function","lang":"rust","doc":"Get an iterator over all cookies in the jar. Only cookies with valid authenticity and integrity are yielded by the iterator.","code":"pub fn iter(&self) -> impl Iterator> + '_ {\n PrivateCookieJarIter {\n jar: self,\n iter: self.jar.iter(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":264,"symbol":"private_jar","kind":"function","lang":"rust","code":"fn private_jar(&self) -> PrivateJar<&'_ cookie::CookieJar> {\n self.jar.private(&self.key)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":268,"symbol":"private_jar_mut","kind":"function","lang":"rust","code":"fn private_jar_mut(&mut self) -> PrivateJar<&'_ mut cookie::CookieJar> {\n self.jar.private_mut(&self.key)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":276,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n set_cookies(&self.jar, res.headers_mut());\n Ok(res)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":283,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":289,"symbol":"PrivateCookieJarIter","kind":"type","lang":"rust","code":"struct PrivateCookieJarIter<'a, K> {\n jar: &'a PrivateCookieJar,\n iter: cookie::Iter<'a>,\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":297,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option {\n loop {\n let cookie = self.iter.next()?;\n\n if let Some(cookie) = self.jar.get(cookie.name()) {\n return Some(cookie);\n }\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/private.rs","line":309,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n jar: self.jar.clone(),\n key: self.key.clone(),\n _marker: self._marker,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":125,"symbol":"SignedCookieJar","kind":"type","lang":"rust","doc":"impl FromRef for Key { fn from_ref(state: &AppState) -> Self { state.0.key.clone() } } ```","code":"pub struct SignedCookieJar {\n jar: cookie::CookieJar,\n key: Key,\n // The key used to extract the key. Allows users to use multiple keys for different\n // jars. Maybe a library wants its own key.\n _marker: PhantomData,\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":134,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"SignedCookieJar\")\n .field(\"jar\", &self.jar)\n .field(\"key\", &\"REDACTED\")\n .finish()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":149,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let k = K::from_ref(state);\n let key = k.into();\n let SignedCookieJar {\n jar,\n key,\n _marker: _,\n } = SignedCookieJar::from_headers(&parts.headers, key);\n Ok(Self {\n jar,\n key,\n _marker: PhantomData,\n })\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":174,"symbol":"from_headers","kind":"function","lang":"rust","doc":"The valid cookies in `headers` will be added to the jar. This is intended to be used in middleware and other places where it might be difficult to run extractors. Normally you should create `SignedCookieJar`s through [`FromRequestParts`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn from_headers(headers: &HeaderMap, key: Key) -> Self {\n let mut jar = cookie::CookieJar::new();\n let mut signed_jar = jar.signed_mut(&key);\n for cookie in cookies_from_request(headers) {\n if let Some(cookie) = signed_jar.verify(cookie) {\n signed_jar.add_original(cookie);\n }\n }\n\n Self {\n jar,\n key,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":196,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new empty `SignedCookieJar`. This is intended to be used in middleware and other places where it might be difficult to run extractors. Normally you should create `SignedCookieJar`s through [`FromRequestParts`]. [`FromRequestParts`]: axum::extract::FromRequestParts","code":"pub fn new(key: Key) -> Self {\n Self {\n jar: Default::default(),\n key,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":224,"symbol":"get","kind":"function","lang":"rust","doc":"async fn handle(jar: SignedCookieJar) { let value: Option = jar .get(\"foo\") .map(|cookie| cookie.value().to_owned()); } ```","code":"pub fn get(&self, name: &str) -> Option> {\n self.signed_jar().get(name)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":240,"symbol":"remove","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: SignedCookieJar) -> SignedCookieJar { jar.remove(Cookie::from(\"foo\")) } ```","code":"pub fn remove>>(mut self, cookie: C) -> Self {\n self.signed_jar_mut().remove(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":260,"symbol":"add","kind":"function","lang":"rust","doc":"use axum::response::IntoResponse; async fn handle(jar: SignedCookieJar) -> SignedCookieJar { jar.add(Cookie::new(\"foo\", \"bar\")) } ```","code":"pub fn add>>(mut self, cookie: C) -> Self {\n self.signed_jar_mut().add(cookie);\n self\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":268,"symbol":"verify","kind":"function","lang":"rust","doc":"Verifies the authenticity and integrity of `cookie`, returning the plaintext version if verification succeeds or `None` otherwise.","code":"pub fn verify(&self, cookie: Cookie<'static>) -> Option> {\n self.signed_jar().verify(cookie)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":275,"symbol":"iter","kind":"function","lang":"rust","doc":"Get an iterator over all cookies in the jar. Only cookies with valid authenticity and integrity are yielded by the iterator.","code":"pub fn iter(&self) -> impl Iterator> + '_ {\n SignedCookieJarIter {\n jar: self,\n iter: self.jar.iter(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":282,"symbol":"signed_jar","kind":"function","lang":"rust","code":"fn signed_jar(&self) -> SignedJar<&'_ cookie::CookieJar> {\n self.jar.signed(&self.key)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":286,"symbol":"signed_jar_mut","kind":"function","lang":"rust","code":"fn signed_jar_mut(&mut self) -> SignedJar<&'_ mut cookie::CookieJar> {\n self.jar.signed_mut(&self.key)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":294,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n set_cookies(&self.jar, res.headers_mut());\n Ok(res)\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":301,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self, ()).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":307,"symbol":"SignedCookieJarIter","kind":"type","lang":"rust","code":"struct SignedCookieJarIter<'a, K> {\n jar: &'a SignedCookieJar,\n iter: cookie::Iter<'a>,\n}"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":315,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option {\n loop {\n let cookie = self.iter.next()?;\n\n if let Some(cookie) = self.jar.get(cookie.name()) {\n return Some(cookie);\n }\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/cookie/signed.rs","line":327,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n jar: self.jar.clone(),\n key: self.key.clone(),\n _marker: self._marker,\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":29,"symbol":"Form","kind":"type","lang":"rust","doc":"is no longer the case. Now it only uses an older version of the same deserializer, purely for ease of transition to the latest version. Before switching to `axum::extract::Form`, it is recommended to read the [changelog for `serde_html_form v0.3.0`][changelog]. [changelog]: https://github.com/jplatte/serde_html_form/blob/main/CHANGELOG.md#030","code":"pub struct Form(pub T);"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":40,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n let is_get_or_head =\n req.method() == http::Method::GET || req.method() == http::Method::HEAD;\n\n let RawForm(bytes) = req.extract().await?;\n\n let deserializer = serde_html_form::Deserializer::new(form_urlencoded::parse(&bytes));\n\n serde_path_to_error::deserialize::<_, T>(deserializer)\n .map(Self)\n .map_err(|err| {\n if is_get_or_head {\n FailedToDeserializeForm::from_err(err).into()\n } else {\n FailedToDeserializeFormBody::from_err(err).into()\n }\n })\n }"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":100,"symbol":"supports_multiple_values","kind":"function","lang":"rust","code":"async fn supports_multiple_values() {\n #[derive(Deserialize)]\n struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|Form(data): Form| async move { data.values.join(\",\") }),\n );\n\n let client = TestClient::new(app);\n\n let res = client\n .post(\"/\")\n .header(CONTENT_TYPE, \"application/x-www-form-urlencoded\")\n .body(\"value=one&value=two\")\n .await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"one,two\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":102,"symbol":"Data","kind":"type","lang":"rust","code":"struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":125,"symbol":"deserialize_error_status_codes","kind":"function","lang":"rust","code":"async fn deserialize_error_status_codes() {\n #[allow(dead_code)]\n #[derive(Deserialize)]\n struct Payload {\n a: i32,\n }\n\n let app = Router::new().route(\n \"/\",\n on(\n MethodFilter::GET.or(MethodFilter::POST),\n |_: Form| async {},\n ),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/?a=false\").await;\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize form: a: invalid digit found in string\"\n );\n\n let res = client\n .post(\"/\")\n .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())\n .body(\"a=false\")\n .await;\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize form body: a: invalid digit found in string\"\n );\n }"} {"repo":"axum","file":"axum-extra/src/extract/form.rs","line":128,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {\n a: i32,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":81,"symbol":"JsonDeserializer","kind":"type","lang":"rust","doc":"StatusCode::OK.into_response() } let app = Router::new().route(\"/upload\", post(upload)); # let _: Router = app; ```","code":"pub struct JsonDeserializer {\n bytes: Bytes,\n _marker: PhantomData,\n}"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":93,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n if json_content_type(req.headers()) {\n let bytes = Bytes::from_request(req, state).await?;\n Ok(Self {\n bytes,\n _marker: PhantomData,\n })\n } else {\n Err(MissingJsonContentType.into())\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":112,"symbol":"deserialize","kind":"function","lang":"rust","doc":"Deserialize the request body into the target type. See [`JsonDeserializer`] for more details.","code":"pub fn deserialize(&'a self) -> Result {\n let deserializer = &mut serde_json::Deserializer::from_slice(&self.bytes);\n\n let value = match serde_path_to_error::deserialize(deserializer) {\n Ok(value) => value,\n Err(err) => {\n let rejection = match err.inner().classify() {\n serde_json::error::Category::Data => JsonDataError::from_err(err).into(),\n serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {\n JsonSyntaxError::from_err(err).into()\n }\n serde_json::error::Category::Io => {\n if cfg!(debug_assertions) {\n // we don't use `serde_json::from_reader` and instead always buffer\n // bodies first, so we shouldn't encounter any IO errors\n unreachable!()\n } else {\n JsonSyntaxError::from_err(err).into()\n }\n }\n };\n return Err(rejection);\n }\n };\n\n Ok("} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":185,"symbol":"json_content_type","kind":"function","lang":"rust","code":"fn json_content_type(headers: &HeaderMap) -> bool {\n let Some(content_type) = headers.get(header::CONTENT_TYPE) else {\n return false;\n };\n\n let Ok(content_type) = content_type.to_str() else {\n return false;\n };\n\n let Ok(mime) = content_type.parse::() else {\n return false;\n };\n\n let is_json_content_type = mime.type_() == \"application\"\n && (mime.subtype() == \"json\" || mime.suffix().is_some_and(|name| name == \"json\"));\n\n is_json_content_type\n}"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":219,"symbol":"deserialize_body","kind":"function","lang":"rust","code":"async fn deserialize_body() {\n #[derive(Debug, Deserialize)]\n struct Input<'a> {\n #[serde(borrow)]\n foo: Cow<'a, str>,\n }\n\n async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(input) => {\n assert!(matches!(input.foo, Cow::Borrowed(_)));\n input.foo.into_owned().into_response()\n }\n Err(e) => e.into_response(),\n }\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").json(&json!({ \"foo\": \"bar\" })).await;\n let body = res.text().await;\n\n assert_eq!(body, \"bar\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":221,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input<'a> {\n #[serde(borrow)]\n foo: Cow<'a, str>,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":226,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(input) => {\n assert!(matches!(input.foo, Cow::Borrowed(_)));\n input.foo.into_owned().into_response()\n }\n Err(e) => e.into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":246,"symbol":"deserialize_body_escaped_to_cow","kind":"function","lang":"rust","code":"async fn deserialize_body_escaped_to_cow() {\n #[derive(Debug, Deserialize)]\n struct Input<'a> {\n #[serde(borrow)]\n foo: Cow<'a, str>,\n }\n\n async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(Input { foo }) => {\n let Cow::Owned(foo) = foo else {\n panic!(\"Deserializer is expected to fallback to Cow::Owned when encountering escaped characters\")\n };\n\n foo.into_response()\n }\n Err(e) => e.into_response(),\n }\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n\n // The escaped characters prevent serde_json from borrowing.\n let res = client.post(\"/\").json(&json!({ \"foo\": \"\\\"bar\\\"\" })).await;\n\n let body = res.text().await;\n\n assert_eq!(body, r#\"\"bar\"\"#);\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":248,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input<'a> {\n #[serde(borrow)]\n foo: Cow<'a, str>,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":253,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(Input { foo }) => {\n let Cow::Owned(foo) = foo else {\n panic!(\"Deserializer is expected to fallback to Cow::Owned when encountering escaped characters\")\n };\n\n foo.into_response()\n }\n Err(e) => e.into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":279,"symbol":"deserialize_body_escaped_to_str","kind":"function","lang":"rust","code":"async fn deserialize_body_escaped_to_str() {\n #[derive(Debug, Deserialize)]\n struct Input<'a> {\n // Explicit `#[serde(borrow)]` attribute is not required for `&str` or &[u8].\n // See: https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl\n foo: &'a str,\n }\n\n async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(Input { foo }) => foo.to_owned().into_response(),\n Err(e) => e.into_response(),\n }\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n\n let res = client.post(\"/\").json(&json!({ \"foo\": \"good\" })).await;\n let body = res.text().await;\n assert_eq!(body, \"good\");\n\n let res = client.post(\"/\").json(&json!({ \"foo\": \"\\\"bad\\\"\" })).await;\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n let body_text = res.text().await;\n assert_eq!(\n body_text,\n \"Failed to deserialize the JSON body into the target type: foo: invalid type: string \\\"\\\\\\\"bad\\\\\\\"\\\", expected a borro"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":281,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input<'a> {\n // Explicit `#[serde(borrow)]` attribute is not required for `&str` or &[u8].\n // See: https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl\n foo: &'a str,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":287,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(deserializer: JsonDeserializer>) -> Response {\n match deserializer.deserialize() {\n Ok(Input { foo }) => foo.to_owned().into_response(),\n Err(e) => e.into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":312,"symbol":"consume_body_to_json_requires_json_content_type","kind":"function","lang":"rust","code":"async fn consume_body_to_json_requires_json_content_type() {\n #[derive(Debug, Deserialize)]\n struct Input<'a> {\n #[allow(dead_code)]\n foo: Cow<'a, str>,\n }\n\n async fn handler(_deserializer: JsonDeserializer>) -> Response {\n panic!(\"This handler should not be called\")\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(r#\"{ \"foo\": \"bar\" }\"#).await;\n\n let status = res.status();\n\n assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":314,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input<'a> {\n #[allow(dead_code)]\n foo: Cow<'a, str>,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":319,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_deserializer: JsonDeserializer>) -> Response {\n panic!(\"This handler should not be called\")\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":334,"symbol":"json_content_types","kind":"function","lang":"rust","code":"async fn json_content_types() {\n async fn valid_json_content_type(content_type: &str) -> bool {\n println!(\"testing {content_type:?}\");\n\n async fn handler(_deserializer: JsonDeserializer) -> Response {\n StatusCode::OK.into_response()\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let res = TestClient::new(app)\n .post(\"/\")\n .header(\"content-type\", content_type)\n .body(\"{}\")\n .await;\n\n res.status() == StatusCode::OK\n }\n\n assert!(valid_json_content_type(\"application/json\").await);\n assert!(valid_json_content_type(\"application/json; charset=utf-8\").await);\n assert!(valid_json_content_type(\"application/json;charset=utf-8\").await);\n assert!(valid_json_content_type(\"application/cloudevents+json\").await);\n assert!(!valid_json_content_type(\"text/json\").await);\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":335,"symbol":"valid_json_content_type","kind":"function","lang":"rust","code":"async fn valid_json_content_type(content_type: &str) -> bool {\n println!(\"testing {content_type:?}\");\n\n async fn handler(_deserializer: JsonDeserializer) -> Response {\n StatusCode::OK.into_response()\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let res = TestClient::new(app)\n .post(\"/\")\n .header(\"content-type\", content_type)\n .body(\"{}\")\n .await;\n\n res.status() == StatusCode::OK\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":338,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_deserializer: JsonDeserializer) -> Response {\n StatusCode::OK.into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":361,"symbol":"invalid_json_syntax","kind":"function","lang":"rust","code":"async fn invalid_json_syntax() {\n async fn handler(deserializer: JsonDeserializer) -> Response {\n match deserializer.deserialize() {\n Ok(_) => panic!(\"Should have matched `Err`\"),\n Err(e) => e.into_response(),\n }\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n let res = client\n .post(\"/\")\n .body(\"{\")\n .header(\"content-type\", \"application/json\")\n .await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":362,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(deserializer: JsonDeserializer) -> Response {\n match deserializer.deserialize() {\n Ok(_) => panic!(\"Should have matched `Err`\"),\n Err(e) => e.into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":382,"symbol":"Foo","kind":"type","lang":"rust","code":"struct Foo {\n #[allow(dead_code)]\n a: i32,\n #[allow(dead_code)]\n b: Vec,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":390,"symbol":"Bar","kind":"type","lang":"rust","code":"struct Bar {\n #[allow(dead_code)]\n x: i32,\n #[allow(dead_code)]\n y: i32,\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":398,"symbol":"invalid_json_data","kind":"function","lang":"rust","code":"async fn invalid_json_data() {\n async fn handler(deserializer: JsonDeserializer) -> Response {\n match deserializer.deserialize() {\n Ok(_) => panic!(\"Should have matched `Err`\"),\n Err(e) => e.into_response(),\n }\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let client = TestClient::new(app);\n let res = client\n .post(\"/\")\n .body(\"{\\\"a\\\": 1, \\\"b\\\": [{\\\"x\\\": 2}]}\")\n .header(\"content-type\", \"application/json\")\n .await;\n\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n let body_text = res.text().await;\n assert_eq!(\n body_text,\n \"Failed to deserialize the JSON body into the target type: b[0]: missing field `y` at line 1 column 23\"\n );\n }"} {"repo":"axum","file":"axum-extra/src/extract/json_deserializer.rs","line":399,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(deserializer: JsonDeserializer) -> Response {\n match deserializer.deserialize() {\n Ok(_) => panic!(\"Should have matched `Err`\"),\n Err(e) => e.into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":90,"symbol":"Multipart","kind":"type","lang":"rust","doc":"that leads to significant usability issues such as `Field` not being `'static`. `axum_extra::extract::Multipart` instead enforces field exclusivity at runtime which makes things easier to use at the cost of possible runtime errors. [`next_field()`]: Multipart::next_field","code":"pub struct Multipart {\n inner: multer::Multipart<'static>,\n}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":100,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n let boundary = parse_boundary(req.headers()).ok_or(InvalidBoundary)?;\n let stream = req.with_limited_body().into_body();\n let multipart = multer::Multipart::new(stream.into_data_stream(), boundary);\n Ok(Self { inner: multipart })\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":110,"symbol":"next_field","kind":"function","lang":"rust","doc":"Yields the next [`Field`] if available.","code":"pub async fn next_field(&mut self) -> Result, MultipartError> {\n let field = self\n .inner\n .next_field()\n .await\n .map_err(MultipartError::from_multer)?;\n\n if let Some(field) = field {\n Ok(Some(Field { inner: field }))\n } else {\n Ok(None)\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":125,"symbol":"into_stream","kind":"function","lang":"rust","doc":"Convert the `Multipart` into a stream of its fields.","code":"pub fn into_stream(self) -> impl Stream> + Send + 'static {\n futures_util::stream::try_unfold(self, |mut multipart| async move {\n let field = multipart.next_field().await?;\n Ok(field.map(|field| (field, multipart)))\n })\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":135,"symbol":"Field","kind":"type","lang":"rust","doc":"A single field in a multipart stream.","code":"pub struct Field {\n inner: multer::Field<'static>,\n}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":142,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n Pin::new(&mut self.inner)\n .poll_next(cx)\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":154,"symbol":"name","kind":"function","lang":"rust","doc":"The field name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.","code":"pub fn name(&self) -> Option<&str> {\n self.inner.name()\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":162,"symbol":"file_name","kind":"function","lang":"rust","doc":"The file name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.","code":"pub fn file_name(&self) -> Option<&str> {\n self.inner.file_name()\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":168,"symbol":"content_type","kind":"function","lang":"rust","doc":"Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field.","code":"pub fn content_type(&self) -> Option<&str> {\n self.inner.content_type().map(|m| m.as_ref())\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":174,"symbol":"headers","kind":"function","lang":"rust","doc":"Get a map of headers as [`HeaderMap`].","code":"pub fn headers(&self) -> &HeaderMap {\n self.inner.headers()\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":179,"symbol":"bytes","kind":"function","lang":"rust","doc":"Get the full data of the field as [`Bytes`].","code":"pub async fn bytes(self) -> Result {\n self.inner\n .bytes()\n .await\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":187,"symbol":"text","kind":"function","lang":"rust","doc":"Get the full field data as text.","code":"pub async fn text(self) -> Result {\n self.inner.text().await.map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":229,"symbol":"chunk","kind":"function","lang":"rust","doc":"Ok(()) } let app = Router::new().route(\"/upload\", post(upload)); # let _: Router = app; ```","code":"pub async fn chunk(&mut self) -> Result, MultipartError> {\n self.inner\n .chunk()\n .await\n .map_err(MultipartError::from_multer)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":239,"symbol":"MultipartError","kind":"type","lang":"rust","doc":"Errors associated with parsing `multipart/form-data` requests.","code":"pub struct MultipartError {\n source: multer::Error,\n}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":244,"symbol":"from_multer","kind":"function","lang":"rust","code":"fn from_multer(multer: multer::Error) -> Self {\n Self { source: multer }\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":249,"symbol":"body_text","kind":"function","lang":"rust","doc":"Get the response body text used for this rejection.","code":"pub fn body_text(&self) -> String {\n let body = if is_body_limit_error(&self.source) {\n \"Request payload is too large\".to_owned()\n } else {\n self.source.to_string()\n };\n axum_core::__log_rejection!(\n rejection_type = Self,\n body_text = body,\n status = self.status(),\n );\n body\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":265,"symbol":"status","kind":"function","lang":"rust","doc":"Get the status code used for this rejection.","code":"pub fn status(&self) -> http::StatusCode {\n status_code_from_multer_error(&self.source)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":270,"symbol":"status_code_from_multer_error","kind":"function","lang":"rust","code":"fn status_code_from_multer_error(err: &multer::Error) -> StatusCode {\n match err {\n multer::Error::UnknownField { .. }\n | multer::Error::IncompleteFieldData { .. }\n | multer::Error::IncompleteHeaders\n | multer::Error::ReadHeaderFailed(..)\n | multer::Error::DecodeHeaderName { .. }\n | multer::Error::DecodeContentType(..)\n | multer::Error::NoBoundary\n | multer::Error::DecodeHeaderValue { .. }\n | multer::Error::NoMultipart\n | multer::Error::IncompleteStream => StatusCode::BAD_REQUEST,\n multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => {\n StatusCode::PAYLOAD_TOO_LARGE\n }\n multer::Error::StreamReadFailed(err) => {\n if let Some(err) = err.downcast_ref::() {\n return status_code_from_multer_error(err);\n }\n\n if err\n .downcast_ref::()\n .and_then(|err| err.source())\n .and_then(|err| err.downcast_ref::())\n .is_some()\n {\n return StatusCode::PAYLOAD_TOO_LARGE;\n"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":305,"symbol":"is_body_limit_error","kind":"function","lang":"rust","code":"fn is_body_limit_error(err: &multer::Error) -> bool {\n match err {\n multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => true,\n multer::Error::StreamReadFailed(err) => {\n if let Some(err) = err.downcast_ref::() {\n return is_body_limit_error(err);\n }\n err.downcast_ref::()\n .and_then(|err| err.source())\n .and_then(|err| err.downcast_ref::())\n .is_some()\n }\n _ => false,\n }\n}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":322,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (self.status(), self.body_text()).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":328,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"Error parsing `multipart/form-data` request\")\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":334,"symbol":"source","kind":"function","lang":"rust","code":"fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n Some(&self.source)\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":339,"symbol":"parse_boundary","kind":"function","lang":"rust","code":"fn parse_boundary(headers: &HeaderMap) -> Option {\n let content_type = headers.get(CONTENT_TYPE)?.to_str().ok()?;\n multer::parse_boundary(content_type).ok()\n}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":368,"symbol":"content_type_with_encoding","kind":"function","lang":"rust","code":"async fn content_type_with_encoding() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n const FILE_NAME: &str = \"index.html\";\n const CONTENT_TYPE: &str = \"text/html; charset=utf-8\";\n\n async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let field = multipart.next_field().await.unwrap().unwrap();\n\n assert_eq!(field.file_name().unwrap(), FILE_NAME);\n assert_eq!(field.content_type().unwrap(), CONTENT_TYPE);\n assert_eq!(field.bytes().await.unwrap(), BYTES);\n\n assert!(multipart.next_field().await.unwrap().is_none());\n }\n\n let app = Router::new().route(\"/\", post(handle));\n\n let client = TestClient::new(app);\n\n let form = reqwest::multipart::Form::new().part(\n \"file\",\n reqwest::multipart::Part::bytes(BYTES)\n .file_name(FILE_NAME)\n .mime_str(CONTENT_TYPE)\n .unwrap(),\n );\n\n client.post(\"/\").multipart(form).await;\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":373,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let field = multipart.next_field().await.unwrap().unwrap();\n\n assert_eq!(field.file_name().unwrap(), FILE_NAME);\n assert_eq!(field.content_type().unwrap(), CONTENT_TYPE);\n assert_eq!(field.bytes().await.unwrap(), BYTES);\n\n assert!(multipart.next_field().await.unwrap().is_none());\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":399,"symbol":"_multipart_from_request_limited","kind":"function","lang":"rust","doc":"No need for this to be a #[test], we just want to make sure it compiles","code":"fn _multipart_from_request_limited() {\n async fn handler(_: Multipart) {}\n let _app: Router<()> = Router::new().route(\"/\", post(handler));\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":400,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Multipart) {}"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":405,"symbol":"body_too_large","kind":"function","lang":"rust","code":"async fn body_too_large() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n\n async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }\n\n let app = Router::new()\n .route(\"/\", post(handle))\n .layer(DefaultBodyLimit::max(BYTES.len() - 1));\n\n let client = TestClient::new(app);\n\n let form =\n reqwest::multipart::Form::new().part(\"file\", reqwest::multipart::Part::bytes(BYTES));\n\n let res = client.post(\"/\").multipart(form).await;\n assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);\n assert_eq!(res.text().await, \"Request payload is too large\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":408,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":431,"symbol":"body_too_large_with_tracing","kind":"function","lang":"rust","code":"async fn body_too_large_with_tracing() {\n const BYTES: &[u8] = \"🦀\".as_bytes();\n\n async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let result: Result<(), MultipartError> = async {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }\n .await;\n\n let subscriber = tracing_subscriber::FmtSubscriber::builder()\n .with_max_level(tracing::level_filters::LevelFilter::TRACE)\n .with_writer(std::io::sink)\n .finish();\n\n let guard = tracing::subscriber::set_default(subscriber);\n let response = result.into_response();\n drop(guard);\n\n response\n }\n\n let app = Router::new()\n .route(\"/\", post(handle))\n .layer(DefaultBodyLimit::max(BYTES.len() - 1));\n\n let client = TestClient::new(app);\n\n let form =\n reqwest::multipart::Form::new().part(\"file\", reqwest::multipart::Part::bytes(BYTES));\n\n let res = client.post(\"/\").multipart(form).await;\n "} {"repo":"axum","file":"axum-extra/src/extract/multipart.rs","line":434,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(mut multipart: Multipart) -> impl IntoResponse {\n let result: Result<(), MultipartError> = async {\n while let Some(field) = multipart.next_field().await? {\n field.bytes().await?;\n }\n Ok(())\n }\n .await;\n\n let subscriber = tracing_subscriber::FmtSubscriber::builder()\n .with_max_level(tracing::level_filters::LevelFilter::TRACE)\n .with_writer(std::io::sink)\n .finish();\n\n let guard = tracing::subscriber::set_default(subscriber);\n let response = result.into_response();\n drop(guard);\n\n response\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":25,"symbol":"Query","kind":"type","lang":"rust","doc":"is no longer the case. Now it only uses an older version of the same deserializer, purely for ease of transition to the latest version. Before switching to `axum::extract::Form`, it is recommended to read the [changelog for `serde_html_form v0.3.0`][changelog]. [changelog]: https://github.com/jplatte/serde_html_form/blob/main/CHANGELOG.md#030","code":"pub struct Query(pub T);"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":34,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let query = parts.uri.query().unwrap_or_default();\n let deserializer =\n serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));\n let value = serde_path_to_error::deserialize(deserializer)\n .map_err(FailedToDeserializeQueryString::from_err)?;\n Ok(Self(value))\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":67,"symbol":"try_from_uri","kind":"function","lang":"rust","doc":"let uri: Uri = \"http://example.com/path?foo=hello&bar=42\".parse().unwrap(); let result: Query = Query::try_from_uri(&uri).unwrap(); assert_eq!(result.foo, String::from(\"hello\")); assert_eq!(result.bar, 42); ```","code":"pub fn try_from_uri(value: &Uri) -> Result {\n let query = value.query().unwrap_or_default();\n let params =\n serde_html_form::from_str(query).map_err(FailedToDeserializeQueryString::from_err)?;\n Ok(Self(params))\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":131,"symbol":"OptionalQuery","kind":"type","lang":"rust","doc":"let app = Router::new().route(\"/list_things\", get(list_things)); # let _: Router = app; ``` If the query string cannot be parsed it will reject the request with a `400 Bad Request` response.","code":"pub struct OptionalQuery(pub Option);"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":140,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n if let Some(query) = parts.uri.query() {\n let deserializer =\n serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));\n let value = serde_path_to_error::deserialize(deserializer)\n .map_err(FailedToDeserializeQueryString::from_err)?;\n Ok(Self(Some(value)))\n } else {\n Ok(Self(None))\n }\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":157,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Self::Target {\n &self.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":164,"symbol":"deref_mut","kind":"function","lang":"rust","code":"fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":189,"symbol":"query_supports_multiple_values","kind":"function","lang":"rust","code":"async fn query_supports_multiple_values() {\n #[derive(Deserialize)]\n struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|Query(data): Query| async move { data.values.join(\",\") }),\n );\n\n let client = TestClient::new(app);\n\n let res = client\n .post(\"/?value=one&value=two\")\n .header(CONTENT_TYPE, \"application/x-www-form-urlencoded\")\n .body(\"\")\n .await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"one,two\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":191,"symbol":"Data","kind":"type","lang":"rust","code":"struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":214,"symbol":"correct_rejection_status_code","kind":"function","lang":"rust","code":"async fn correct_rejection_status_code() {\n #[derive(Deserialize)]\n #[allow(dead_code)]\n struct Params {\n n: i32,\n }\n\n async fn handler(_: Query) {}\n\n let app = Router::new().route(\"/\", get(handler));\n let client = TestClient::new(app);\n\n let res = client.get(\"/?n=hi\").await;\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n assert_eq!(\n res.text().await,\n \"Failed to deserialize query string: n: invalid digit found in string\"\n );\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":217,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n n: i32,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":221,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Query) {}"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":235,"symbol":"optional_query_supports_multiple_values","kind":"function","lang":"rust","code":"async fn optional_query_supports_multiple_values() {\n #[derive(Deserialize)]\n struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|OptionalQuery(data): OptionalQuery| async move {\n data.map(|Data { values }| values.join(\",\"))\n .unwrap_or(\"None\".to_owned())\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client\n .post(\"/?value=one&value=two\")\n .header(CONTENT_TYPE, \"application/x-www-form-urlencoded\")\n .body(\"\")\n .await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"one,two\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":237,"symbol":"Data","kind":"type","lang":"rust","code":"struct Data {\n #[serde(rename = \"value\")]\n values: Vec,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":263,"symbol":"optional_query_deserializes_no_parameters_into_none","kind":"function","lang":"rust","code":"async fn optional_query_deserializes_no_parameters_into_none() {\n #[derive(Deserialize)]\n struct Data {\n value: String,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|OptionalQuery(data): OptionalQuery| async move {\n match data {\n None => \"None\".into(),\n Some(data) => data.value,\n }\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.post(\"/\").body(\"\").await;\n\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"None\");\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":265,"symbol":"Data","kind":"type","lang":"rust","code":"struct Data {\n value: String,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":288,"symbol":"optional_query_preserves_parsing_errors","kind":"function","lang":"rust","code":"async fn optional_query_preserves_parsing_errors() {\n #[derive(Deserialize)]\n struct Data {\n value: String,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|OptionalQuery(data): OptionalQuery| async move {\n match data {\n None => \"None\".into(),\n Some(data) => data.value,\n }\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client\n .post(\"/?other=something\")\n .header(CONTENT_TYPE, \"application/x-www-form-urlencoded\")\n .body(\"\")\n .await;\n\n assert_eq!(res.status(), StatusCode::BAD_REQUEST);\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":290,"symbol":"Data","kind":"type","lang":"rust","code":"struct Data {\n value: String,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":316,"symbol":"test_try_from_uri","kind":"function","lang":"rust","code":"fn test_try_from_uri() {\n #[derive(Deserialize)]\n struct TestQueryParams {\n foo: Vec,\n bar: u32,\n }\n let uri: Uri = \"http://example.com/path?foo=hello&bar=42&foo=goodbye\"\n .parse()\n .unwrap();\n let result: Query = Query::try_from_uri(&uri).unwrap();\n assert_eq!(result.foo, [String::from(\"hello\"), String::from(\"goodbye\")]);\n assert_eq!(result.bar, 42);\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":318,"symbol":"TestQueryParams","kind":"type","lang":"rust","code":"struct TestQueryParams {\n foo: Vec,\n bar: u32,\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":331,"symbol":"test_try_from_uri_with_invalid_query","kind":"function","lang":"rust","code":"fn test_try_from_uri_with_invalid_query() {\n #[derive(Deserialize)]\n struct TestQueryParams {\n _foo: String,\n _bar: u32,\n }\n let uri: Uri = \"http://example.com/path?foo=hello&bar=invalid\"\n .parse()\n .unwrap();\n let result: Result, _> = Query::try_from_uri(&uri);\n\n assert!(result.is_err());\n }"} {"repo":"axum","file":"axum-extra/src/extract/query.rs","line":333,"symbol":"TestQueryParams","kind":"type","lang":"rust","code":"struct TestQueryParams {\n _foo: String,\n _bar: u32,\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":60,"symbol":"WithRejection","kind":"type","lang":"rust","doc":"# let _: axum::Router = axum::Router::new().route(\"/\", axum::routing::get(handler)); ``` [`FromRequest`]: axum::extract::FromRequest [`IntoResponse`]: axum::response::IntoResponse [`From`]: std::convert::From","code":"pub struct WithRejection(pub E, pub PhantomData);"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":64,"symbol":"into_inner","kind":"function","lang":"rust","doc":"Returns the wrapped extractor","code":"pub fn into_inner(self) -> E {\n self.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":73,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_tuple(\"WithRejection\")\n .field(&self.0)\n .field(&self.1)\n .finish()\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":85,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self(self.0.clone(), self.1)\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":93,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self(Default::default(), Default::default())\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":101,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Self::Target {\n &self.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":107,"symbol":"deref_mut","kind":"function","lang":"rust","code":"fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":120,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let extractor = E::from_request(req, state).await?;\n Ok(Self(extractor, PhantomData))\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":134,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let extractor = E::from_request_parts(parts, state).await?;\n Ok(Self(extractor, PhantomData))\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":152,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":165,"symbol":"extractor_rejection_is_transformed","kind":"function","lang":"rust","code":"async fn extractor_rejection_is_transformed() {\n struct TestExtractor;\n struct TestRejection;\n\n impl FromRequestParts for TestExtractor\n where\n S: Send + Sync,\n {\n type Rejection = ();\n\n async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n Err(())\n }\n }\n\n impl IntoResponse for TestRejection {\n fn into_response(self) -> Response {\n ().into_response()\n }\n }\n\n impl From<()> for TestRejection {\n fn from(_: ()) -> Self {\n Self\n }\n }\n\n let req = Request::new(Body::empty());\n let result = WithRejection::::from_request(req, &()).await;\n assert!(matches!(result, Err(TestRejection)));\n\n let (mut parts, _) = Request::new(()).into_parts();\n let result =\n WithRejection::::from_request_parts(&mut parts, &())\n .await;\n assert!(matches!(result, Err(TestRejection)));\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":166,"symbol":"TestExtractor","kind":"type","lang":"rust","code":"struct TestExtractor;"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":167,"symbol":"TestRejection","kind":"type","lang":"rust","code":"struct TestRejection;"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":175,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n _parts: &mut Parts,\n _state: &S,\n ) -> Result {\n Err(())\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":184,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n ().into_response()\n }"} {"repo":"axum","file":"axum-extra/src/extract/with_rejection.rs","line":190,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ()) -> Self {\n Self\n }"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":25,"symbol":"HandlerCallWithExtractors","kind":"type","lang":"rust","doc":"This trait is similar to [`Handler`] but rather than taking the request it takes the extracted inputs. The drawback of this trait is that you cannot apply middleware to individual handlers like you can with [`Handler::layer`].","code":"pub trait HandlerCallWithExtractors: Sized {\n /// The type of future calling this handler returns.\n type Future: Future + Send + 'static;\n\n /// Call the handler with the extracted inputs.\n fn call(self, extractors: T, state: S) -> >::Future;\n\n /// Convert this `HandlerCallWithExtractors` into [`Handler`].\n fn into_handler(self) -> IntoHandler {\n IntoHandler {\n handler: self,\n _marker: PhantomData,\n }\n }\n\n /// Chain two handlers together, running the second one if the first one rejects.\n ///\n /// Note that this only moves to the next handler if an extractor fails. The response from\n /// handlers are not considered.\n ///\n /// # Example\n ///\n /// ```\n /// use axum_extra::handler::HandlerCallWithExtractors;\n /// use axum::{\n /// Router,\n /// routing::get,\n /// extract::FromRequestParts,\n /// };\n ///\n /// // handlers for varying levels of access\n /// async fn admin(admin: AdminPermissions) {\n /// // request came from an admin\n /// }\n ///\n /// async fn user(user: User) {\n ///"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":30,"symbol":"call","kind":"function","lang":"rust","doc":"Call the handler with the extracted inputs.","code":"fn call(self, extractors: T, state: S) -> >::Future;"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":33,"symbol":"into_handler","kind":"function","lang":"rust","doc":"Convert this `HandlerCallWithExtractors` into [`Handler`].","code":"fn into_handler(self) -> IntoHandler {\n IntoHandler {\n handler: self,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":105,"symbol":"or","kind":"function","lang":"rust","doc":"// to `guest` admin.or(user).or(guest) ) ); # let _: Router = app; ```","code":"fn or(self, rhs: R) -> Or\n where\n R: HandlerCallWithExtractors,\n {\n Or {\n lhs: self,\n rhs,\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":162,"symbol":"IntoHandler","kind":"type","lang":"rust","doc":"A [`Handler`] created from a [`HandlerCallWithExtractors`]. Created with [`HandlerCallWithExtractors::into_handler`].","code":"pub struct IntoHandler {\n handler: H,\n _marker: PhantomData (T, S)>,\n}"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":176,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, req: Request, state: S) -> Self::Future {\n let req = req.map(Body::new);\n Box::pin(async move {\n match T::from_request(req, &state).await {\n Ok(t) => self.handler.call(t, state).await,\n Err(rejection) => rejection.into_response(),\n }\n })\n }"} {"repo":"axum","file":"axum-extra/src/handler/mod.rs","line":193,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n handler: self.handler.clone(),\n _marker: self._marker,\n }\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":17,"symbol":"Or","kind":"type","lang":"rust","doc":"[`Handler`] that runs one [`Handler`] and if that rejects it'll fallback to another [`Handler`]. Created with [`HandlerCallWithExtractors::or`](super::HandlerCallWithExtractors::or).","code":"pub struct Or {\n pub(super) lhs: L,\n pub(super) rhs: R,\n pub(super) _marker: PhantomData (Lt, Rt, S)>,\n}"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":36,"symbol":"call","kind":"function","lang":"rust","code":"fn call(\n self,\n extractors: Either,\n state: S,\n ) -> , S>>::Future {\n match extractors {\n Either::E1(lt) => self\n .lhs\n .call(lt, state)\n .map(IntoResponse::into_response as _)\n .left_future(),\n Either::E2(rt) => self\n .rhs\n .call(rt, state)\n .map(IntoResponse::into_response as _)\n .right_future(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":69,"symbol":"call","kind":"function","lang":"rust","code":"fn call(self, req: Request, state: S) -> Self::Future {\n let (mut parts, body) = req.into_parts();\n\n Box::pin(async move {\n if let Ok(lt) = Lt::from_request_parts(&mut parts, &state).await {\n return self.lhs.call(lt, state).await;\n }\n\n let req = Request::from_parts(parts, body);\n\n match Rt::from_request(req, &state).await {\n Ok(rt) => self.rhs.call(rt, state).await,\n Err(rejection) => rejection.into_response(),\n }\n })\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":99,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n lhs: self.lhs.clone(),\n rhs: self.rhs.clone(),\n _marker: self._marker,\n }\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":120,"symbol":"works","kind":"function","lang":"rust","code":"async fn works() {\n #[derive(Deserialize)]\n struct Params {\n a: String,\n }\n\n async fn one(Path(id): Path) -> String {\n id.to_string()\n }\n\n async fn two(Query(params): Query) -> String {\n params.a\n }\n\n async fn three() -> &'static str {\n \"fallback\"\n }\n\n let app = Router::new().route(\"/{id}\", get(one.or(two).or(three)));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/123\").await;\n assert_eq!(res.text().await, \"123\");\n\n let res = client.get(\"/foo?a=bar\").await;\n assert_eq!(res.text().await, \"bar\");\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.text().await, \"fallback\");\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":122,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n a: String,\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":126,"symbol":"one","kind":"function","lang":"rust","code":"async fn one(Path(id): Path) -> String {\n id.to_string()\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":130,"symbol":"two","kind":"function","lang":"rust","code":"async fn two(Query(params): Query) -> String {\n params.a\n }"} {"repo":"axum","file":"axum-extra/src/handler/or.rs","line":134,"symbol":"three","kind":"function","lang":"rust","code":"async fn three() -> &'static str {\n \"fallback\"\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":85,"symbol":"AsExtractor","kind":"type","lang":"rust","doc":"Marker type used to prove that an `JsonLines` was constructed via `FromRequest`.","code":"pub struct AsExtractor;"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":90,"symbol":"AsResponse","kind":"type","lang":"rust","doc":"Marker type used to prove that an `JsonLines` was constructed via `JsonLines::new`.","code":"pub struct AsResponse;"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":94,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `JsonLines` from a stream of items.","code":"pub fn new(stream: S) -> Self {\n Self {\n inner: Inner::Response { stream },\n _marker: PhantomData,\n }\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":109,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n // `Stream::lines` isn't a thing so we have to convert it into an `AsyncRead`\n // so we can call `AsyncRead::lines` and then convert it back to a `Stream`\n let body = req.into_limited_body();\n let stream = body.into_data_stream();\n let stream = stream.map_err(io::Error::other);\n let read = StreamReader::new(stream);\n let lines_stream = LinesStream::new(read.lines());\n\n let deserialized_stream =\n lines_stream\n .map_err(axum_core::Error::new)\n .and_then(|value| async move {\n serde_json::from_str::(&value).map_err(axum_core::Error::new)\n });\n\n Ok(Self {\n inner: Inner::Extractor {\n stream: Box::pin(deserialized_stream),\n },\n _marker: PhantomData,\n })\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":137,"symbol":"poll_next","kind":"function","lang":"rust","code":"fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.project().inner.project() {\n InnerProj::Extractor { stream } => stream.poll_next(cx),\n // `JsonLines<_, AsExtractor>` can only be constructed via `FromRequest`\n // which doesn't use this variant\n InnerProj::Response { .. } => unreachable!(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":153,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let inner = match self.inner {\n Inner::Response { stream } => stream,\n // `JsonLines<_, AsResponse>` can only be constructed via `JsonLines::new`\n // which doesn't use this variant\n Inner::Extractor { .. } => unreachable!(),\n };\n\n let stream = inner.map_err(Into::into).and_then(|value| async move {\n let mut buf = BytesMut::new().writer();\n serde_json::to_writer(&mut buf, &value)?;\n buf.write_all(b\"\\n\")?;\n Ok::<_, BoxError>(buf.into_inner().freeze())\n });\n let stream = Body::from_stream(stream);\n\n // there is no consensus around mime type yet\n // https://github.com/wardi/jsonlines/issues/36\n stream.into_response()\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":189,"symbol":"User","kind":"type","lang":"rust","code":"struct User {\n id: i32,\n }"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":194,"symbol":"extractor","kind":"function","lang":"rust","code":"async fn extractor() {\n let app = Router::new().route(\n \"/\",\n post(|mut stream: JsonLines| async move {\n assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 1 });\n assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 2 });\n assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 3 });\n\n // sources are downcastable to `serde_json::Error`\n let err = stream.next().await.unwrap().unwrap_err();\n let _: &serde_json::Error = err\n .source()\n .unwrap()\n .downcast_ref::()\n .unwrap();\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client\n .post(\"/\")\n .body(\n [\n \"{\\\"id\\\":1}\",\n \"{\\\"id\\\":2}\",\n \"{\\\"id\\\":3}\",\n // to trigger an error for source downcasting\n \"{\\\"id\\\":false}\",\n ]\n .join(\"\\n\"),\n )\n .await;\n assert_eq!(res.status(), St"} {"repo":"axum","file":"axum-extra/src/json_lines.rs","line":231,"symbol":"response","kind":"function","lang":"rust","code":"async fn response() {\n let app = Router::new().route(\n \"/\",\n get(|| async {\n let values = futures_util::stream::iter(vec![\n Ok::<_, Infallible>(User { id: 1 }),\n Ok::<_, Infallible>(User { id: 2 }),\n Ok::<_, Infallible>(User { id: 3 }),\n ]);\n JsonLines::new(values)\n }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n\n let values = res\n .text()\n .await\n .lines()\n .map(|line| serde_json::from_str::(line).unwrap())\n .collect::>();\n\n assert_eq!(\n values,\n vec![User { id: 1 }, User { id: 2 }, User { id: 3 },]\n );\n }"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":33,"symbol":"option_layer","kind":"function","lang":"rust","doc":"# Difference between this and [`tower::util::option_layer`] `axum_extra::middleware::option_layer` makes sure that the output `Body` is [`axum::body::Body`]. [`Layer`]: tower_layer::Layer","code":"pub fn option_layer(layer: Option) -> Either<(ResponseAxumBodyLayer, L), Identity> {\n layer\n .map(|layer| Either::E1((ResponseAxumBodyLayer, layer)))\n .unwrap_or_else(|| Either::E2(Identity::new()))\n}"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":55,"symbol":"remap_response_body","kind":"function","lang":"rust","code":"fn remap_response_body() {\n struct BodyWrapper;\n\n impl BodyWrapper {\n fn new(_: AxumBody) -> Self {\n Self\n }\n }\n\n impl HttpBody for BodyWrapper {\n type Data = Bytes;\n type Error = Infallible;\n fn poll_frame(\n self: Pin<&mut Self>,\n _cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n unimplemented!()\n }\n fn is_end_stream(&self) -> bool {\n unimplemented!()\n }\n fn size_hint(&self) -> http_body::SizeHint {\n unimplemented!()\n }\n }\n let _app: Router = Router::new().layer(option_layer(Some(MapResponseBodyLayer::new(\n BodyWrapper::new,\n ))));\n }"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":56,"symbol":"BodyWrapper","kind":"type","lang":"rust","code":"struct BodyWrapper;"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":59,"symbol":"new","kind":"function","lang":"rust","code":"fn new(_: AxumBody) -> Self {\n Self\n }"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":67,"symbol":"poll_frame","kind":"function","lang":"rust","code":"fn poll_frame(\n self: Pin<&mut Self>,\n _cx: &mut Context<'_>,\n ) -> Poll, Self::Error>>> {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":73,"symbol":"is_end_stream","kind":"function","lang":"rust","code":"fn is_end_stream(&self) -> bool {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-extra/src/middleware.rs","line":76,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> http_body::SizeHint {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":92,"symbol":"Protobuf","kind":"type","lang":"rust","doc":"# unimplemented!() } let app = Router::new().route(\"/users/{id}\", get(get_user)); # let _: Router = app; ```","code":"pub struct Protobuf(pub T);"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":101,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let bytes = Bytes::from_request(req, state).await?;\n\n match T::decode(bytes) {\n Ok(value) => Ok(Self(value)),\n Err(err) => Err(ProtobufDecodeError::from_err(err).into()),\n }\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":114,"symbol":"from","kind":"function","lang":"rust","code":"fn from(inner: T) -> Self {\n Self(inner)\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":123,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut buf = BytesMut::with_capacity(self.0.encoded_len());\n match &self.0.encode(&mut buf) {\n Ok(()) => buf.into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":166,"symbol":"decode_body","kind":"function","lang":"rust","code":"async fn decode_body() {\n #[derive(prost::Message)]\n struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }\n\n let app = Router::new().route(\n \"/\",\n post(|Protobuf(input): Protobuf| async move { input.foo }),\n );\n\n let input = Input {\n foo: \"bar\".to_owned(),\n };\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(input.encode_to_vec()).await;\n\n let status = res.status();\n let body = res.text().await;\n\n assert_eq!(status, StatusCode::OK);\n assert_eq!(body, input.foo);\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":168,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":193,"symbol":"prost_decode_error","kind":"function","lang":"rust","code":"async fn prost_decode_error() {\n #[derive(prost::Message)]\n struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }\n\n #[derive(prost::Message)]\n struct Expected {\n #[prost(int32, tag = \"1\")]\n test: i32,\n }\n\n let app = Router::new().route(\"/\", post(|_: Protobuf| async {}));\n\n let input = Input {\n foo: \"bar\".to_owned(),\n };\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(input.encode_to_vec()).await;\n\n assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);\n assert!(res.text().await.starts_with(\"Failed to decode the body\"));\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":195,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":201,"symbol":"Expected","kind":"type","lang":"rust","code":"struct Expected {\n #[prost(int32, tag = \"1\")]\n test: i32,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":220,"symbol":"body_too_large_is_bytes_rejection","kind":"function","lang":"rust","code":"async fn body_too_large_is_bytes_rejection() {\n #[derive(prost::Message)]\n struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }\n\n let app = Router::new()\n .route(\"/\", post(|_: Protobuf| async {}))\n .layer(DefaultBodyLimit::max(1));\n\n let input = Input {\n foo: \"bar\".to_owned(),\n };\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(input.encode_to_vec()).await;\n\n assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);\n assert!(res\n .text()\n .await\n .starts_with(\"Failed to buffer the request body\"));\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":222,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":246,"symbol":"encode_body","kind":"function","lang":"rust","code":"async fn encode_body() {\n #[derive(prost::Message)]\n struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }\n\n #[derive(prost::Message)]\n struct Output {\n #[prost(string, tag = \"1\")]\n result: String,\n }\n\n #[axum::debug_handler]\n async fn handler(Protobuf(input): Protobuf) -> Protobuf {\n let output = Output { result: input.foo };\n\n Protobuf(output)\n }\n\n let app = Router::new().route(\"/\", post(handler));\n\n let input = Input {\n foo: \"bar\".to_owned(),\n };\n\n let client = TestClient::new(app);\n let res = client.post(\"/\").body(input.encode_to_vec()).await;\n\n let content_type_header_value = res\n .headers()\n .get(CONTENT_TYPE)\n .expect(\"missing expected header\");\n\n assert_eq!(\n content_type_header_value,\n mime::APPLICATION_OCTET_STREAM.as_ref()\n );\n\n let body = res.bytes().await;\n\n let output = Output::decode(body).unwrap();\n\n assert_eq!(output.result, input.foo);\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":248,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n #[prost(string, tag = \"1\")]\n foo: String,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":254,"symbol":"Output","kind":"type","lang":"rust","code":"struct Output {\n #[prost(string, tag = \"1\")]\n result: String,\n }"} {"repo":"axum","file":"axum-extra/src/protobuf.rs","line":260,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(Protobuf(input): Protobuf) -> Protobuf {\n let output = Output { result: input.foo };\n\n Protobuf(output)\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":39,"symbol":"Attachment","kind":"type","lang":"rust","doc":"let _: Router = app; ``` # Note If you use axum with hyper, hyper will set the `Content-Length` if it is known.","code":"pub struct Attachment {\n inner: T,\n filename: Option,\n content_type: Option,\n}"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":47,"symbol":"new","kind":"function","lang":"rust","doc":"Creates a new [`Attachment`].","code":"pub fn new(inner: T) -> Self {\n Self {\n inner,\n filename: None,\n content_type: None,\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":58,"symbol":"filename","kind":"function","lang":"rust","doc":"Sets the filename of the [`Attachment`]. This updates the `Content-Disposition` header to add a filename.","code":"pub fn filename>(mut self, value: H) -> Self {\n self.filename = match value.try_into() {\n Ok(filename) if filename.to_str().is_ok() => Some(filename),\n _ => {\n error!(\"Attachment filename contains invalid characters\");\n None\n }\n };\n self\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":70,"symbol":"content_type","kind":"function","lang":"rust","doc":"Sets the content-type of the [`Attachment`]","code":"pub fn content_type>(mut self, value: H) -> Self {\n if let Ok(content_type) = value.try_into() {\n self.content_type = Some(content_type);\n } else {\n error!(\"Attachment content-type contains invalid characters\");\n }\n self\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":84,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> axum_core::response::Response {\n let mut headers = HeaderMap::new();\n\n if let Some(content_type) = self.content_type {\n headers.append(header::CONTENT_TYPE, content_type);\n }\n\n let content_disposition = if let Some(filename) = self.filename {\n let filename_str = filename\n .to_str()\n .expect(\"This was a HeaderValue so this can not fail\");\n let value = format!(\n \"attachment; filename=\\\"{}\\\"\",\n EscapedQuotedString(filename_str)\n );\n HeaderValue::try_from(value).expect(\"This was a HeaderValue so this can not fail\")\n } else {\n HeaderValue::from_static(\"attachment\")\n };\n\n headers.append(header::CONTENT_DISPOSITION, content_disposition);\n\n (headers, self.inner).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":117,"symbol":"attachment_without_filename","kind":"function","lang":"rust","code":"fn attachment_without_filename() {\n let attachment = Attachment::new(\"data\").into_response();\n let value = attachment.headers().get(CONTENT_DISPOSITION).unwrap();\n assert_eq!(value, \"attachment\");\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":124,"symbol":"attachment_with_normal_filename","kind":"function","lang":"rust","code":"fn attachment_with_normal_filename() {\n let attachment = Attachment::new(\"data\")\n .filename(\"report.pdf\")\n .into_response();\n let value = attachment.headers().get(CONTENT_DISPOSITION).unwrap();\n assert_eq!(value, \"attachment; filename=\\\"report.pdf\\\"\");\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":133,"symbol":"attachment_with_opaque_filename","kind":"function","lang":"rust","code":"fn attachment_with_opaque_filename() {\n let filename = HeaderValue::from_bytes(b\"report\\xff.pdf\").unwrap();\n let attachment = Attachment::new(\"data\").filename(filename).into_response();\n let value = attachment.headers().get(CONTENT_DISPOSITION).unwrap();\n assert_eq!(value, \"attachment\");\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":141,"symbol":"attachment_filename_escapes_quotes","kind":"function","lang":"rust","code":"fn attachment_filename_escapes_quotes() {\n // A filename containing a double quote should be escaped to prevent\n // Content-Disposition parameter injection (see CVE-2023-29401)\n let attachment = Attachment::new(\"data\")\n .filename(\"evil\\\"; filename*=UTF-8''pwned.txt; x=\\\"\")\n .into_response();\n let value = attachment.headers().get(CONTENT_DISPOSITION).unwrap();\n assert_eq!(\n value,\n \"attachment; filename=\\\"evil\\\\\\\"; filename*=UTF-8''pwned.txt; x=\\\\\\\"\\\"\"\n );\n }"} {"repo":"axum","file":"axum-extra/src/response/attachment.rs","line":155,"symbol":"attachment_filename_escapes_backslashes","kind":"function","lang":"rust","code":"fn attachment_filename_escapes_backslashes() {\n let attachment = Attachment::new(\"data\")\n .filename(\"file\\\\name.txt\")\n .into_response();\n let value = attachment.headers().get(CONTENT_DISPOSITION).unwrap();\n assert_eq!(value, \"attachment; filename=\\\"file\\\\\\\\name.txt\\\"\");\n }"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":8,"symbol":"EscapedQuotedString","kind":"type","lang":"rust","doc":"A wrapper type that escapes backslashes and double quotes when formatted, for safe inclusion in Content-Disposition header quoted-strings. This prevents Content-Disposition header parameter injection (similar to CVE-2023-29401).","code":"pub(crate) struct EscapedQuotedString<'a>(pub &'a str);"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":11,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n for c in self.0.chars() {\n if c == '\\\\' || c == '\"' {\n f.write_char('\\\\')?;\n }\n f.write_char(c)?;\n }\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":23,"symbol":"contains_newlines","kind":"function","lang":"rust","code":"pub(crate) fn contains_newlines(value: &str) -> bool {\n value.contains(['\\r', '\\n'])\n}"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":32,"symbol":"no_special_characters","kind":"function","lang":"rust","code":"fn no_special_characters() {\n assert_eq!(EscapedQuotedString(\"report.pdf\").to_string(), \"report.pdf\");\n }"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":37,"symbol":"escapes_double_quotes","kind":"function","lang":"rust","code":"fn escapes_double_quotes() {\n assert_eq!(\n EscapedQuotedString(\"evil\\\"; filename*=UTF-8''pwned.txt; x=\\\"\").to_string(),\n \"evil\\\\\\\"; filename*=UTF-8''pwned.txt; x=\\\\\\\"\",\n );\n }"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":45,"symbol":"escapes_backslashes","kind":"function","lang":"rust","code":"fn escapes_backslashes() {\n assert_eq!(\n EscapedQuotedString(\"file\\\\name.txt\").to_string(),\n \"file\\\\\\\\name.txt\",\n );\n }"} {"repo":"axum","file":"axum-extra/src/response/content_disposition.rs","line":53,"symbol":"detects_newlines","kind":"function","lang":"rust","code":"fn detects_newlines() {\n assert!(contains_newlines(\"line\\r\\nbreak\"));\n assert!(contains_newlines(\"line\\nbreak\"));\n assert!(!contains_newlines(\"report.pdf\"));\n }"} {"repo":"axum","file":"axum-extra/src/response/erased_json.rs","line":43,"symbol":"ErasedJson","kind":"type","lang":"rust","doc":"ErasedJson::new(&foo) } else { ErasedJson::new(&bar) } } ```","code":"pub struct ErasedJson(Result>);"} {"repo":"axum","file":"axum-extra/src/response/erased_json.rs","line":47,"symbol":"new","kind":"function","lang":"rust","doc":"Create an `ErasedJson` by serializing a value with the compact formatter.","code":"pub fn new(val: T) -> Self {\n let mut bytes = BytesMut::with_capacity(128);\n let result = match serde_json::to_writer((&mut bytes).writer(), &val) {\n Ok(()) => Ok(bytes.freeze()),\n Err(e) => Err(Arc::new(e)),\n };\n Self(result)\n }"} {"repo":"axum","file":"axum-extra/src/response/erased_json.rs","line":57,"symbol":"pretty","kind":"function","lang":"rust","doc":"Create an `ErasedJson` by serializing a value with the pretty formatter.","code":"pub fn pretty(val: T) -> Self {\n let mut bytes = BytesMut::with_capacity(128);\n let result = match serde_json::to_writer_pretty((&mut bytes).writer(), &val) {\n Ok(()) => {\n bytes.put_u8(b'\\n');\n Ok(bytes.freeze())\n }\n Err(e) => Err(Arc::new(e)),\n };\n Self(result)\n }"} {"repo":"axum","file":"axum-extra/src/response/erased_json.rs","line":71,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self.0 {\n Ok(bytes) => (\n [(\n header::CONTENT_TYPE,\n HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),\n )],\n bytes,\n )\n .into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n IntoResponseFailed,\n err.to_string(),\n )\n .into_response(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/error_response.rs","line":28,"symbol":"InternalServerError","kind":"type","lang":"rust","doc":"async fn maybe_error() -> Result> { try_thing().map_err(InternalServerError)?; // do something on success # Ok(String::from(\"ok\")) } ```","code":"pub struct InternalServerError(pub T);"} {"repo":"axum","file":"axum-extra/src/response/error_response.rs","line":31,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n error!(error = &self.0 as &dyn Error);\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n \"An error occurred while processing your request.\",\n )\n .into_response()\n }"} {"repo":"axum","file":"axum-extra/src/response/error_response.rs","line":47,"symbol":"internal_server_error","kind":"function","lang":"rust","code":"fn internal_server_error() {\n let response = InternalServerError(Error::other(\"Test\")).into_response();\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":49,"symbol":"FileStream","kind":"type","lang":"rust","doc":"Ok(file_stream_resp.into_response()) } let app = Router::new().route(\"/file-stream\", get(file_stream)); # let _: Router = app; ```","code":"pub struct FileStream {\n /// stream.\n pub stream: S,\n /// The file name of the file.\n pub file_name: Option,\n /// The size of the file.\n pub content_size: Option,\n}"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":65,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new [`FileStream`]","code":"pub fn new(stream: S) -> Self {\n Self {\n stream,\n file_name: None,\n content_size: None,\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":76,"symbol":"file_name","kind":"function","lang":"rust","doc":"Set the file name of the [`FileStream`]. This adds the attachment `Content-Disposition` header with the given `file_name`.","code":"pub fn file_name(mut self, file_name: impl Into) -> Self {\n self.file_name = Some(file_name.into());\n self\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":82,"symbol":"content_size","kind":"function","lang":"rust","doc":"Set the size of the file.","code":"pub fn content_size(mut self, len: u64) -> Self {\n self.content_size = Some(len);\n self\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":126,"symbol":"into_range_response","kind":"function","lang":"rust","doc":"Ok(FileStream::new(stream).into_range_response(10, file_size - 1, file_size)) } let app = Router::new().route(\"/file-stream\", get(range_response)); # let _: Router = app; ```","code":"pub fn into_range_response(self, start: u64, end: u64, total_size: u64) -> Response {\n let mut resp = Response::builder().header(header::CONTENT_TYPE, \"application/octet-stream\");\n resp = resp.status(StatusCode::PARTIAL_CONTENT);\n\n resp = resp.header(\n header::CONTENT_RANGE,\n format!(\"bytes {start}-{end}/{total_size}\"),\n );\n\n resp.body(body::Body::from_stream(self.stream))\n .unwrap_or_else(|e| {\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"build FileStream response error: {e}\"),\n )\n .into_response()\n })\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":184,"symbol":"try_range_response","kind":"function","lang":"rust","doc":".map_err(|e| (StatusCode::NOT_FOUND, format!(\"File not found: {e}\"))) } let app = Router::new().route(\"/file-stream\", get(range_stream)); # let _: Router = app; ```","code":"pub async fn try_range_response(\n file_path: impl AsRef,\n start: u64,\n mut end: u64,\n ) -> io::Result {\n let mut file = File::open(file_path).await?;\n\n let metadata = file.metadata().await?;\n let total_size = metadata.len();\n\n if total_size == 0 {\n return Ok((StatusCode::RANGE_NOT_SATISFIABLE, \"Range Not Satisfiable\").into_response());\n }\n\n if end == 0 {\n end = total_size - 1;\n }\n\n if start > total_size {\n return Ok((StatusCode::RANGE_NOT_SATISFIABLE, \"Range Not Satisfiable\").into_response());\n }\n if start > end {\n return Ok((StatusCode::RANGE_NOT_SATISFIABLE, \"Range Not Satisfiable\").into_response());\n }\n if end >= total_size {\n return Ok((StatusCode::RANGE_NOT_SATISFIABLE, \"Range Not Satisfiable\").into_response());\n }\n\n file.seek(std::io::SeekFrom::Start(start)).await?;\n\n let stream = ReaderStream::new(file.take(end - start + 1));\n\n Ok(FileStream::new(stream).into_range_response(start, end, total_size))\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":244,"symbol":"from_path","kind":"function","lang":"rust","doc":".map_err(|e| (StatusCode::NOT_FOUND, format!(\"File not found: {e}\"))) } let app = Router::new().route(\"/file-stream\", get(file_stream)); # let _: Router = app; ```","code":"pub async fn from_path(path: impl AsRef) -> io::Result {\n let file = File::open(&path).await?;\n let mut content_size = None;\n let mut file_name = None;\n\n if let Ok(metadata) = file.metadata().await {\n content_size = Some(metadata.len());\n }\n\n if let Some(file_name_os) = path.as_ref().file_name() {\n if let Some(file_name_str) = file_name_os.to_str() {\n file_name = Some(file_name_str.to_owned());\n }\n }\n\n Ok(Self {\n stream: ReaderStream::new(file),\n file_name,\n content_size,\n })\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":273,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut resp = Response::builder().header(header::CONTENT_TYPE, \"application/octet-stream\");\n\n if let Some(file_name) = self.file_name {\n resp = resp.header(\n header::CONTENT_DISPOSITION,\n format!(\n \"attachment; filename=\\\"{}\\\"\",\n super::content_disposition::EscapedQuotedString(&file_name)\n ),\n );\n }\n\n if let Some(content_size) = self.content_size {\n resp = resp.header(header::CONTENT_LENGTH, content_size);\n }\n\n resp.body(body::Body::from_stream(self.stream))\n .unwrap_or_else(|e| {\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"build FileStream response error: {e}\"),\n )\n .into_response()\n })\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":313,"symbol":"response","kind":"function","lang":"rust","code":"async fn response() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n // Simulating a file stream\n let file_content = b\"Hello, this is the simulated file content!\".to_vec();\n let reader = Cursor::new(file_content);\n\n // Response file stream\n // Content size and file name are not attached by default\n let stream = ReaderStream::new(reader);\n FileStream::new(stream).into_response()\n }),\n );\n\n // Simulating a GET request\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::OK);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n\n // Validate Response Body\n let body: &[u8] = &response.into_body().collect().await?.to_bytes();\n assert_eq!(\n std::str::from_utf8(body)?,\n "} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":352,"symbol":"response_not_set_filename","kind":"function","lang":"rust","code":"async fn response_not_set_filename() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n // Simulating a file stream\n let file_content = b\"Hello, this is the simulated file content!\".to_vec();\n let size = file_content.len() as u64;\n let reader = Cursor::new(file_content);\n\n // Response file stream\n let stream = ReaderStream::new(reader);\n FileStream::new(stream).content_size(size).into_response()\n }),\n );\n\n // Simulating a GET request\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::OK);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n assert_eq!(response.headers().get(\"content-length\").unwrap(), \"42\");\n\n // Validate Response Body\n let body: &[u8] = &response.into_body().co"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":392,"symbol":"response_not_set_content_size","kind":"function","lang":"rust","code":"async fn response_not_set_content_size() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n // Simulating a file stream\n let file_content = b\"Hello, this is the simulated file content!\".to_vec();\n let reader = Cursor::new(file_content);\n\n // Response file stream\n let stream = ReaderStream::new(reader);\n FileStream::new(stream).file_name(\"test\").into_response()\n }),\n );\n\n // Simulating a GET request\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::OK);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n assert_eq!(\n response.headers().get(\"content-disposition\").unwrap(),\n \"attachment; filename=\\\"test\\\"\"\n );\n\n // Validate Response Body\n let body: &[u8] = &response"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":434,"symbol":"response_with_content_size_and_filename","kind":"function","lang":"rust","code":"async fn response_with_content_size_and_filename() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n // Simulating a file stream\n let file_content = b\"Hello, this is the simulated file content!\".to_vec();\n let size = file_content.len() as u64;\n let reader = Cursor::new(file_content);\n\n // Response file stream\n let stream = ReaderStream::new(reader);\n FileStream::new(stream)\n .file_name(\"test\")\n .content_size(size)\n .into_response()\n }),\n );\n\n // Simulating a GET request\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::OK);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n assert_eq!(\n response.headers().get(\"content-dis"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":481,"symbol":"response_from_path","kind":"function","lang":"rust","code":"async fn response_from_path() -> Result<(), Box> {\n let app = Router::new().route(\n \"/from_path\",\n get(move || async move {\n FileStream::from_path(Path::new(\"CHANGELOG.md\"))\n .await\n .unwrap()\n .into_response()\n }),\n );\n\n // Simulating a GET request\n let response = app\n .oneshot(\n Request::builder()\n .uri(\"/from_path\")\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::OK);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n assert_eq!(\n response.headers().get(\"content-disposition\").unwrap(),\n \"attachment; filename=\\\"CHANGELOG.md\\\"\"\n );\n\n let file = File::open(\"CHANGELOG.md\").await.unwrap();\n // get file size\n let content_length = file.metadata()."} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":533,"symbol":"response_range_file","kind":"function","lang":"rust","code":"async fn response_range_file() -> Result<(), Box> {\n let app = Router::new().route(\"/range_response\", get(range_stream));\n\n // Simulating a GET request\n let response = app\n .oneshot(\n Request::builder()\n .uri(\"/range_response\")\n .header(header::RANGE, \"bytes=20-1000\")\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n // Validate Response Status Code\n assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);\n\n // Validate Response Headers\n assert_eq!(\n response.headers().get(\"content-type\").unwrap(),\n \"application/octet-stream\"\n );\n\n let file = File::open(\"CHANGELOG.md\").await.unwrap();\n // get file size\n let content_length = file.metadata().await.unwrap().len();\n\n assert_eq!(\n response\n .headers()\n .get(\"content-range\")\n .unwrap()\n .to_str()\n .unwrap(),\n format!(\"bytes 20-1000/{content_length}\")\n );\n Ok"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":573,"symbol":"range_stream","kind":"function","lang":"rust","code":"async fn range_stream(headers: HeaderMap) -> Response {\n let range_header = headers\n .get(header::RANGE)\n .and_then(|value| value.to_str().ok());\n\n let (start, end) = if let Some(range) = range_header {\n if let Some(range) = parse_range_header(range) {\n range\n } else {\n return (StatusCode::RANGE_NOT_SATISFIABLE, \"Invalid Range\").into_response();\n }\n } else {\n (0, 0) // default range end = 0, if end = 0 end == file size - 1\n };\n\n FileStream::>::try_range_response(Path::new(\"CHANGELOG.md\"), start, end)\n .await\n .unwrap()\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":593,"symbol":"parse_range_header","kind":"function","lang":"rust","code":"fn parse_range_header(range: &str) -> Option<(u64, u64)> {\n let range = range.strip_prefix(\"bytes=\")?;\n let mut parts = range.split('-');\n let start = parts.next()?.parse::().ok()?;\n let end = parts\n .next()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n if start > end {\n return None;\n }\n Some((start, end))\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":608,"symbol":"filename_escapes_quotes","kind":"function","lang":"rust","code":"async fn filename_escapes_quotes() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n let file_content = b\"data\".to_vec();\n let reader = Cursor::new(file_content);\n let stream = ReaderStream::new(reader);\n // Filename containing double quotes that could cause parameter injection\n FileStream::new(stream)\n .file_name(\"evil\\\"; filename*=UTF-8''pwned.txt; x=\\\"\")\n .into_response()\n }),\n );\n\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_eq!(\n response.headers().get(\"content-disposition\").unwrap(),\n \"attachment; filename=\\\"evil\\\\\\\"; filename*=UTF-8''pwned.txt; x=\\\\\\\"\\\"\"\n );\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":635,"symbol":"filename_escapes_backslashes","kind":"function","lang":"rust","code":"async fn filename_escapes_backslashes() -> Result<(), Box> {\n let app = Router::new().route(\n \"/file\",\n get(|| async {\n let file_content = b\"data\".to_vec();\n let reader = Cursor::new(file_content);\n let stream = ReaderStream::new(reader);\n FileStream::new(stream)\n .file_name(\"file\\\\name.txt\")\n .into_response()\n }),\n );\n\n let response = app\n .oneshot(Request::builder().uri(\"/file\").body(Body::empty())?)\n .await?;\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_eq!(\n response.headers().get(\"content-disposition\").unwrap(),\n \"attachment; filename=\\\"file\\\\\\\\name.txt\\\"\"\n );\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/response/file_stream.rs","line":661,"symbol":"response_range_empty_file","kind":"function","lang":"rust","code":"async fn response_range_empty_file() -> Result<(), Box> {\n let file = tempfile::NamedTempFile::new()?;\n file.as_file().set_len(0)?;\n let path = file.path().to_owned();\n\n let app = Router::new().route(\n \"/range_empty\",\n get(move |headers: HeaderMap| {\n let path = path.clone();\n async move {\n let range_header = headers\n .get(header::RANGE)\n .and_then(|value| value.to_str().ok());\n\n let (start, end) = if let Some(range) = range_header {\n if let Some(range) = parse_range_header(range) {\n range\n } else {\n return (StatusCode::RANGE_NOT_SATISFIABLE, \"Invalid Range\")\n .into_response();\n }\n } else {\n (0, 0)\n };\n\n FileStream::>::try_range_response(path, start, end)\n .await\n .unwrap_or_else(|_| StatusCode::INTERNAL_"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":14,"symbol":"MultipartForm","kind":"type","lang":"rust","doc":"Create multipart forms to be used in API responses. This struct implements [`IntoResponse`], and so it can be returned from a handler.","code":"pub struct MultipartForm {\n parts: Vec,\n}"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":29,"symbol":"with_parts","kind":"function","lang":"rust","doc":"```rust use axum_extra::response::multiple::{MultipartForm, Part}; let parts: Vec = vec![Part::text(\"foo\".to_string(), \"abc\"), Part::text(\"bar\".to_string(), \"def\")]; let form = MultipartForm::with_parts(parts); ```","code":"pub fn with_parts(parts: Vec) -> Self {\n Self { parts }\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":35,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n // see RFC 7578 for details\n let Some(boundary) = generate_boundary_for_parts(&self.parts) else {\n return (\n StatusCode::INTERNAL_SERVER_ERROR,\n \"Unable to generate multipart boundary\",\n )\n .into_response();\n };\n let mut headers = HeaderMap::new();\n let mime_type: Mime = match format!(\"multipart/form-data; boundary={boundary}\").parse() {\n Ok(m) => m,\n // Realistically this should never happen unless the boundary generation code\n // is modified, and that will be caught by unit tests\n Err(_) => {\n return (\n StatusCode::INTERNAL_SERVER_ERROR,\n \"Invalid multipart boundary generated\",\n )\n .into_response()\n }\n };\n // The use of unwrap is safe here because mime types are inherently string representable\n headers.insert(header::CONTENT_TYPE, mime_type.to_string().parse().unwrap());\n let mut serialized_form: Vec = Vec::new();\n for part in self.parts {\n // for each p"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":82,"symbol":"Part","kind":"type","lang":"rust","doc":"Valid settings for that header are: \"base64\", \"quoted-printable\", \"8bit\", \"7bit\", and \"binary\". A single part of a multipart form as defined by and RFC 7578.","code":"pub struct Part {\n // Every part is expected to contain:\n // - a [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition\n // header, where `Content-Disposition` is set to `form-data`, with a parameter of `name` that is set to\n // the name of the field in the form. In the below example, the name of the field is `user`:\n // ```\n // Content-Disposition: form-data; name=\"user\"\n // ```\n // If the field contains a file, then the `filename` parameter may be set to the name of the file.\n // Handling for non-ascii field names is not done here, support for non-ascii characters may be encoded using\n // methodology described in RFC 2047.\n // - (optionally) a `Content-Type` header, which if not set, defaults to `text/plain`.\n // If the field contains a file, then the file should be identified with that file's MIME type (e.g., `image/gif`).\n // If the `MIME` type is not known or specified, then the MIME type should be set to `application/octet-stream`.\n /// The name of the part in question\n name: String,\n /// If the part should be treated as a file, the filename that should be attached that part\n filen"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":122,"symbol":"text","kind":"function","lang":"rust","doc":"// create a form with a single part that has a field with a name of \"foo\", // and a value of \"abc\" let parts: Vec = vec![Part::text(\"foo\".to_string(), \"abc\")]; let form = MultipartForm::from_iter(parts); ```","code":"pub fn text(name: String, contents: &str) -> Self {\n Self {\n name,\n filename: None,\n mime_type: mime::TEXT_PLAIN_UTF_8,\n contents: contents.as_bytes().to_vec(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":147,"symbol":"file","kind":"function","lang":"rust","doc":"// create a form with a single part that has a field with a name of \"foo\", // with a file name of \"foo.txt\", and with the specified contents let parts: Vec = vec![Part::file(\"foo\", \"foo.txt\", vec![0x68, 0x68, 0x20, 0x6d, 0x6f, 0x6d])]; let form = MultipartForm::from_iter(parts); ```","code":"pub fn file(field_name: &str, file_name: &str, contents: Vec) -> Self {\n Self {\n name: field_name.to_owned(),\n filename: Some(file_name.to_owned()),\n // If the `MIME` type is not known or specified, then the MIME type should be set to `application/octet-stream`.\n // See RFC2388 section 3 for specifics.\n mime_type: mime::APPLICATION_OCTET_STREAM,\n contents,\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":174,"symbol":"raw_part","kind":"function","lang":"rust","doc":"// create a form with a single part that has a field with a name of \"part_name\", // with a MIME type of \"application/json\", and the supplied contents. let parts: Vec = vec![Part::raw_part(\"part_name\", \"application/json\", vec![0x68, 0x68, 0x20, 0x6d, 0x6f, 0x6d], None).expect(\"MIME type must be valid\")]; let form = MultipartForm::from_iter(parts); ```","code":"pub fn raw_part(\n name: &str,\n mime_type: &str,\n contents: Vec,\n filename: Option<&str>,\n ) -> Result {\n let mime_type = mime_type.parse().map_err(|_| \"Invalid MIME type\")?;\n Ok(Self {\n name: name.to_owned(),\n filename: filename.map(|f| f.to_owned()),\n mime_type,\n contents,\n })\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":190,"symbol":"serialize","kind":"function","lang":"rust","doc":"Serialize this part into a chunk that can be easily inserted into a larger form","code":"pub(super) fn serialize(&self) -> Result, &'static str> {\n // A part is serialized in this general format:\n // // the filename is optional\n // Content-Disposition: form-data; name=\"FIELD_NAME\"; filename=\"FILENAME\"\\r\\n\n // // the mime type (not strictly required by the spec, but always sent here)\n // Content-Type: mime/type\\r\\n\n // // a blank line, then the contents of the file start\n // \\r\\n\n // CONTENTS\\r\\n\n\n if contains_newlines(&self.name) {\n return Err(\"Invalid multipart field name\");\n }\n\n // Format what we can as a string, then handle the rest at a byte level\n let mut serialized_part = format!(\n \"Content-Disposition: form-data; name=\\\"{}\\\"\",\n EscapedQuotedString(&self.name)\n );\n // specify a filename if one was set\n if let Some(filename) = &self.filename {\n if contains_newlines(filename) {\n return Err(\"Invalid multipart filename\");\n }\n serialized_part += &format!(\"; filename=\\\"{}\\\"\", EscapedQuotedString(filename));\n }\n serialized_part += \"\\r\\n\";\n // specify the MIME"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":227,"symbol":"contains_boundary","kind":"function","lang":"rust","code":"fn contains_boundary(&self, boundary: &str) -> bool {\n let boundary_bytes = boundary.as_bytes();\n\n self.name.contains(boundary)\n || self\n .filename\n .as_ref()\n .is_some_and(|filename| filename.contains(boundary))\n || self.mime_type.to_string().contains(boundary)\n || self\n .contents\n .windows(boundary_bytes.len())\n .any(|window| window == boundary_bytes)\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":244,"symbol":"from_iter","kind":"function","lang":"rust","code":"fn from_iter>(iter: T) -> Self {\n Self {\n parts: iter.into_iter().collect(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":255,"symbol":"generate_boundary_for_parts","kind":"function","lang":"rust","code":"fn generate_boundary_for_parts(parts: &[Part]) -> Option {\n for _ in 0..BOUNDARY_GENERATION_ATTEMPTS {\n let boundary = generate_boundary();\n if !parts.iter().any(|part| part.contains_boundary(&boundary)) {\n return Some(boundary);\n }\n }\n\n None\n}"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":271,"symbol":"generate_boundary","kind":"function","lang":"rust","doc":"A boundary is defined as a user-defined (arbitrary) value that does not occur in any of the data. Because the specification does not clearly define a methodology for generating boundaries, this implementation follows Reqwest's, and generates a boundary in the format of `XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX` where `XXXXXXXX` is a hexadecimal representation of a pseudo randomly generated u64.","code":"fn generate_boundary() -> String {\n let a = fastrand::u64(0..u64::MAX);\n let b = fastrand::u64(0..u64::MAX);\n let c = fastrand::u64(0..u64::MAX);\n let d = fastrand::u64(0..u64::MAX);\n format!(\"{a:016x}-{b:016x}-{c:016x}-{d:016x}\")\n}"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":291,"symbol":"process_form","kind":"function","lang":"rust","code":"async fn process_form() -> Result<(), Box> {\n // create a boilerplate handle that returns a form\n async fn handle() -> MultipartForm {\n let parts: Vec = vec![\n Part::text(\"part1\".to_owned(), \"basictext\"),\n Part::file(\n \"part2\",\n \"file.txt\",\n vec![0x68, 0x69, 0x20, 0x6d, 0x6f, 0x6d],\n ),\n Part::raw_part(\"part3\", \"text/plain\", b\"rawpart\".to_vec(), None).unwrap(),\n ];\n MultipartForm::from_iter(parts)\n }\n\n // make a request to that handle\n let app = Router::new().route(\"/\", get(handle));\n let response: Response<_> = app\n .oneshot(Request::builder().uri(\"/\").body(Body::empty())?)\n .await?;\n // content_type header\n let ct_header = response.headers().get(\"content-type\").unwrap().to_str()?;\n let boundary = ct_header.split(\"boundary=\").nth(1).unwrap().to_owned();\n let body: &[u8] = &response.into_body().collect().await?.to_bytes();\n assert_eq!(\n std::str::from_utf8(body)?,\n format!(\n "} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":293,"symbol":"handle","kind":"function","lang":"rust","doc":"create a boilerplate handle that returns a form","code":"async fn handle() -> MultipartForm {\n let parts: Vec = vec![\n Part::text(\"part1\".to_owned(), \"basictext\"),\n Part::file(\n \"part2\",\n \"file.txt\",\n vec![0x68, 0x69, 0x20, 0x6d, 0x6f, 0x6d],\n ),\n Part::raw_part(\"part3\", \"text/plain\", b\"rawpart\".to_vec(), None).unwrap(),\n ];\n MultipartForm::from_iter(parts)\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":341,"symbol":"multipart_part_escapes_content_disposition_params","kind":"function","lang":"rust","code":"fn multipart_part_escapes_content_disposition_params() {\n let part = Part::file(\n \"field\\\"; injected=\\\"1\",\n \"evil\\\\name\\\"; filename*=UTF-8''pwned.txt; x=\\\"\",\n b\"hi\".to_vec(),\n );\n\n let body = String::from_utf8(part.serialize().unwrap()).unwrap();\n\n assert!(body.starts_with(\n \"Content-Disposition: form-data; name=\\\"field\\\\\\\"; injected=\\\\\\\"1\\\"; filename=\\\"evil\\\\\\\\name\\\\\\\"; filename*=UTF-8''pwned.txt; x=\\\\\\\"\\\"\\r\\n\"\n ));\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":356,"symbol":"multipart_form_rejects_newlines_in_field_metadata","kind":"function","lang":"rust","code":"async fn multipart_form_rejects_newlines_in_field_metadata(\n ) -> Result<(), Box> {\n async fn handle() -> MultipartForm {\n MultipartForm::from_iter(vec![Part::file(\n \"bad\\r\\nx-extra: injected\",\n \"file.txt\",\n b\"hi\".to_vec(),\n )])\n }\n\n let app = Router::new().route(\"/\", get(handle));\n let response = app\n .oneshot(Request::builder().uri(\"/\").body(Body::empty())?)\n .await?;\n\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n\n let body = response.into_body().collect().await?.to_bytes();\n assert_eq!(&body[..], b\"Invalid multipart field name or filename\");\n\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":358,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle() -> MultipartForm {\n MultipartForm::from_iter(vec![Part::file(\n \"bad\\r\\nx-extra: injected\",\n \"file.txt\",\n b\"hi\".to_vec(),\n )])\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":380,"symbol":"valid_boundary_generation","kind":"function","lang":"rust","code":"fn valid_boundary_generation() {\n for _ in 0..256 {\n let boundary = generate_boundary();\n let mime_type: Result =\n format!(\"multipart/form-data; boundary={boundary}\").parse();\n assert!(\n mime_type.is_ok(),\n \"The generated boundary was unable to be parsed into a valid mime type.\"\n );\n }\n }"} {"repo":"axum","file":"axum-extra/src/response/multiple.rs","line":393,"symbol":"generated_boundary_does_not_appear_in_part_contents","kind":"function","lang":"rust","code":"async fn generated_boundary_does_not_appear_in_part_contents() {\n fastrand::seed(0);\n let colliding_boundary = generate_boundary();\n let colliding_boundary_marker = format!(\"--{colliding_boundary}\");\n let contents = format!(\"before\\r\\n{colliding_boundary_marker}\\r\\nafter\");\n let parts = vec![Part::text(\"part\".to_owned(), &contents)];\n\n fastrand::seed(0);\n let response = MultipartForm::from_iter(parts).into_response();\n let content_type = response\n .headers()\n .get(\"content-type\")\n .unwrap()\n .to_str()\n .unwrap();\n let boundary = content_type.split(\"boundary=\").nth(1).unwrap().to_owned();\n assert_ne!(boundary, colliding_boundary);\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n let body = std::str::from_utf8(&body).unwrap();\n let boundary_marker = format!(\"--{boundary}\");\n\n assert_eq!(body.matches(&boundary_marker).count(), 2);\n assert_eq!(body.matches(&colliding_boundary_marker).count(), 1);\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":32,"symbol":"__private_validate_static_path","kind":"function","lang":"rust","doc":"Validates a path at compile time, used with the vpath macro.","code":"pub const fn __private_validate_static_path(path: &'static str) -> &'static str {\n if path.is_empty() {\n panic!(\"Paths must start with a `/`. Use \\\"/\\\" for root routes\")\n }\n if path.as_bytes()[0] != b'/' {\n panic!(\"Paths must start with /\");\n }\n\n // Checks if we have a path in 107 format.\n let size: usize = path.len() - 1;\n let mut curr: usize = 0;\n let bytes = path.as_bytes();\n while curr < size {\n if bytes[curr] == b'/' && (bytes[curr + 1] == b'*' || bytes[curr + 1] == b':') {\n panic!(\n \"You have a path with a deprecated format, move your ':var' or '*var' to '{{var}}'\"\n );\n }\n curr += 1;\n }\n\n path\n}"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":119,"symbol":"RouterExt","kind":"type","lang":"rust","doc":"Extension trait that adds additional methods to [`Router`].","code":"pub trait RouterExt: sealed::Sealed {\n /// Add a typed `GET` route to the router.\n ///\n /// The path will be inferred from the first argument to the handler function which must\n /// implement [`TypedPath`].\n ///\n /// See [`TypedPath`] for more details and examples.\n #[cfg(feature = \"typed-routing\")]\n fn typed_get(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;\n\n /// Add a typed `DELETE` route to the router.\n ///\n /// The path will be inferred from the first argument to the handler function which must\n /// implement [`TypedPath`].\n ///\n /// See [`TypedPath`] for more details and examples.\n #[cfg(feature = \"typed-routing\")]\n fn typed_delete(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;\n\n /// Add a typed `HEAD` route to the router.\n ///\n /// The path will be inferred from the first argument to the handler function which must\n /// implement [`TypedPath`].\n ///\n /// See [`TypedPath`] for more details and examples.\n "} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":127,"symbol":"typed_get","kind":"function","lang":"rust","doc":"Add a typed `GET` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_get(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":140,"symbol":"typed_delete","kind":"function","lang":"rust","doc":"Add a typed `DELETE` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_delete(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":153,"symbol":"typed_head","kind":"function","lang":"rust","doc":"Add a typed `HEAD` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_head(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":166,"symbol":"typed_options","kind":"function","lang":"rust","doc":"Add a typed `OPTIONS` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_options(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":179,"symbol":"typed_patch","kind":"function","lang":"rust","doc":"Add a typed `PATCH` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_patch(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":192,"symbol":"typed_post","kind":"function","lang":"rust","doc":"Add a typed `POST` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_post(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":205,"symbol":"typed_put","kind":"function","lang":"rust","doc":"Add a typed `PUT` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_put(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":218,"symbol":"typed_trace","kind":"function","lang":"rust","doc":"Add a typed `TRACE` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_trace(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":231,"symbol":"typed_connect","kind":"function","lang":"rust","doc":"Add a typed `CONNECT` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_connect(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":244,"symbol":"typed_query","kind":"function","lang":"rust","doc":"Add a typed `QUERY` route to the router. The path will be inferred from the first argument to the handler function which must implement [`TypedPath`]. See [`TypedPath`] for more details and examples.","code":"fn typed_query(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":275,"symbol":"route_with_tsr","kind":"function","lang":"rust","doc":"// `/foo/` will redirect to `/foo` .route_with_tsr(\"/foo\", get(|| async {})) // `/bar` will redirect to `/bar/` .route_with_tsr(\"/bar/\", get(|| async {})); # let _: Router = app; ```","code":"fn route_with_tsr(self, path: &str, method_router: MethodRouter) -> Self\n where\n Self: Sized;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":282,"symbol":"route_service_with_tsr","kind":"function","lang":"rust","doc":"Add another route to the router with an additional \"trailing slash redirect\" route. This works like [`RouterExt::route_with_tsr`] but accepts any [`Service`].","code":"fn route_service_with_tsr(self, path: &str, service: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n Self: Sized;"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":295,"symbol":"typed_get","kind":"function","lang":"rust","code":"fn typed_get(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::get(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":305,"symbol":"typed_delete","kind":"function","lang":"rust","code":"fn typed_delete(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::delete(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":315,"symbol":"typed_head","kind":"function","lang":"rust","code":"fn typed_head(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::head(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":325,"symbol":"typed_options","kind":"function","lang":"rust","code":"fn typed_options(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::options(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":335,"symbol":"typed_patch","kind":"function","lang":"rust","code":"fn typed_patch(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::patch(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":345,"symbol":"typed_post","kind":"function","lang":"rust","code":"fn typed_post(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::post(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":355,"symbol":"typed_put","kind":"function","lang":"rust","code":"fn typed_put(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::put(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":365,"symbol":"typed_trace","kind":"function","lang":"rust","code":"fn typed_trace(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::trace(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":375,"symbol":"typed_connect","kind":"function","lang":"rust","code":"fn typed_connect(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::connect(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":385,"symbol":"typed_query","kind":"function","lang":"rust","code":"fn typed_query(self, handler: H) -> Self\n where\n H: axum::handler::Handler,\n T: SecondElementIs

+ 'static,\n P: TypedPath,\n {\n self.route(P::PATH, axum::routing::query(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":395,"symbol":"route_with_tsr","kind":"function","lang":"rust","code":"fn route_with_tsr(mut self, path: &str, method_router: MethodRouter) -> Self\n where\n Self: Sized,\n {\n validate_tsr_path(path);\n let method_filter = method_router.method_filter();\n self = self.route(path, method_router);\n add_tsr_redirect_route(self, path, method_filter)\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":406,"symbol":"route_service_with_tsr","kind":"function","lang":"rust","code":"fn route_service_with_tsr(mut self, path: &str, service: T) -> Self\n where\n T: Service + Clone + Send + Sync + 'static,\n T::Response: IntoResponse,\n T::Future: Send + 'static,\n Self: Sized,\n {\n validate_tsr_path(path);\n self = self.route_service(path, service);\n add_tsr_redirect_route(self, path, None)\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":420,"symbol":"validate_tsr_path","kind":"function","lang":"rust","code":"fn validate_tsr_path(path: &str) {\n if path == \"/\" {\n panic!(\"Cannot add a trailing slash redirect route for `/`\")\n }\n}"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":426,"symbol":"add_tsr_redirect_route","kind":"function","lang":"rust","code":"fn add_tsr_redirect_route(\n router: Router,\n path: &str,\n method_filter: Option,\n) -> Router\nwhere\n S: Clone + Send + Sync + 'static,\n{\n async fn redirect_handler(OriginalUri(uri): OriginalUri) -> Response {\n let new_uri = map_path(uri, |path| {\n path.strip_suffix('/')\n .map(Cow::Borrowed)\n .unwrap_or_else(|| Cow::Owned(format!(\"{path}/\")))\n });\n\n if let Some(new_uri) = new_uri {\n Redirect::permanent(new_uri.to_string()).into_response()\n } else {\n StatusCode::BAD_REQUEST.into_response()\n }\n }\n\n let _slot;\n let redirect_path = if let Some(without_slash) = path.strip_suffix('/') {\n without_slash\n } else {\n // FIXME: Can return `&format!(...)` directly when MSRV is updated\n _slot = format!(\"{path}/\");\n &_slot\n };\n\n let method_router = match method_filter {\n Some(f) => on(f, redirect_handler),\n None => any(redirect_handler),\n };\n\n router.route(redirect_path, method_router)\n}"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":434,"symbol":"redirect_handler","kind":"function","lang":"rust","code":"async fn redirect_handler(OriginalUri(uri): OriginalUri) -> Response {\n let new_uri = map_path(uri, |path| {\n path.strip_suffix('/')\n .map(Cow::Borrowed)\n .unwrap_or_else(|| Cow::Owned(format!(\"{path}/\")))\n });\n\n if let Some(new_uri) = new_uri {\n Redirect::permanent(new_uri.to_string()).into_response()\n } else {\n StatusCode::BAD_REQUEST.into_response()\n }\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":468,"symbol":"map_path","kind":"function","lang":"rust","doc":"Map the path of a `Uri`. Returns `None` if the `Uri` cannot be put back together with the new path.","code":"fn map_path(original_uri: Uri, f: F) -> Option\nwhere\n F: FnOnce(&str) -> Cow<'_, str>,\n{\n let mut parts = original_uri.into_parts();\n let path_and_query = parts.path_and_query.as_ref()?;\n\n let new_path = f(path_and_query.path());\n\n let new_path_and_query = if let Some(query) = &path_and_query.query() {\n format!(\"{new_path}?{query}\").parse::().ok()?\n } else {\n new_path.parse::().ok()?\n };\n parts.path_and_query = Some(new_path_and_query);\n\n Uri::from_parts(parts).ok()\n}"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":488,"symbol":"Sealed","kind":"type","lang":"rust","code":"pub trait Sealed {}"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":502,"symbol":"test_tsr","kind":"function","lang":"rust","code":"async fn test_tsr() {\n let app = Router::new()\n .route_with_tsr(\"/foo\", get(|| async {}))\n .route_with_tsr(\"/bar/\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/foo/\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/foo\");\n\n let res = client.get(\"/bar/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/bar\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/bar/\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":525,"symbol":"tsr_with_params","kind":"function","lang":"rust","code":"async fn tsr_with_params() {\n let app = Router::new()\n .route_with_tsr(\n \"/a/{a}\",\n get(|Path(param): Path| async move { param }),\n )\n .route_with_tsr(\n \"/b/{b}/\",\n get(|Path(param): Path| async move { param }),\n );\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/a/foo\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"foo\");\n\n let res = client.get(\"/a/foo/\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/a/foo\");\n\n let res = client.get(\"/b/foo/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"foo\");\n\n let res = client.get(\"/b/foo\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/b/foo/\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":556,"symbol":"tsr_maintains_query_params","kind":"function","lang":"rust","code":"async fn tsr_maintains_query_params() {\n let app = Router::new().route_with_tsr(\"/foo\", get(|| async {}));\n\n let client = TestClient::new(app);\n\n let res = client.get(\"/foo/?a=a\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/foo?a=a\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":567,"symbol":"tsr_works_in_nested_router","kind":"function","lang":"rust","code":"async fn tsr_works_in_nested_router() {\n let app = Router::new().nest(\n \"/neko\",\n Router::new().route_with_tsr(\"/nyan/\", get(|| async {})),\n );\n\n let client = TestClient::new(app);\n let res = client.get(\"/neko/nyan/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n\n let res = client.get(\"/neko/nyan\").await;\n assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);\n assert_eq!(res.headers()[\"location\"], \"/neko/nyan/\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":583,"symbol":"tsr_independent_route_registration","kind":"function","lang":"rust","code":"fn tsr_independent_route_registration() {\n let _: Router = Router::new()\n .route_with_tsr(\"/x\", get(|| async {}))\n .route_with_tsr(\"/x\", post(|| async {}));\n }"} {"repo":"axum","file":"axum-extra/src/routing/mod.rs","line":591,"symbol":"tsr_at_root","kind":"function","lang":"rust","code":"fn tsr_at_root() {\n let _: Router = Router::new().route_with_tsr(\"/\", get(|| async move {}));\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":36,"symbol":"Resource","kind":"type","lang":"rust","doc":"// `DELETE /users/{users_id}` .destroy(|Path(user_id): Path| async {}); let app = Router::new().merge(users); # let _: Router = app; ```","code":"pub struct Resource {\n pub(crate) name: String,\n pub(crate) router: Router,\n}"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":48,"symbol":"named","kind":"function","lang":"rust","doc":"Create a `Resource` with the given name. All routes will be nested at `/{resource_name}`.","code":"pub fn named(resource_name: &str) -> Self {\n Self {\n name: resource_name.to_owned(),\n router: Router::new(),\n }\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":56,"symbol":"index","kind":"function","lang":"rust","doc":"Add a handler at `GET /{resource_name}`.","code":"pub fn index(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = self.index_create_path();\n self.route(&path, get(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":66,"symbol":"create","kind":"function","lang":"rust","doc":"Add a handler at `POST /{resource_name}`.","code":"pub fn create(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = self.index_create_path();\n self.route(&path, post(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":76,"symbol":"new","kind":"function","lang":"rust","doc":"Add a handler at `GET /{resource_name}/new`.","code":"pub fn new(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = format!(\"/{}/new\", self.name);\n self.route(&path, get(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":88,"symbol":"show","kind":"function","lang":"rust","doc":"Add a handler at `GET //{_id}`. For example when the resources are posts: `GET /post/{post_id}`.","code":"pub fn show(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = self.show_update_destroy_path();\n self.route(&path, get(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":100,"symbol":"edit","kind":"function","lang":"rust","doc":"Add a handler at `GET //{_id}/edit`. For example when the resources are posts: `GET /post/{post_id}/edit`.","code":"pub fn edit(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = format!(\"/{0}/{{{0}_id}}/edit\", self.name);\n self.route(&path, get(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":112,"symbol":"update","kind":"function","lang":"rust","doc":"Add a handler at `PUT or PATCH //{_id}`. For example when the resources are posts: `PUT /post/{post_id}`.","code":"pub fn update(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = self.show_update_destroy_path();\n self.route(\n &path,\n on(MethodFilter::PUT.or(MethodFilter::PATCH), handler),\n )\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":127,"symbol":"destroy","kind":"function","lang":"rust","doc":"Add a handler at `DELETE //{_id}`. For example when the resources are posts: `DELETE /post/{post_id}`.","code":"pub fn destroy(self, handler: H) -> Self\n where\n H: Handler,\n T: 'static,\n {\n let path = self.show_update_destroy_path();\n self.route(&path, delete(handler))\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":136,"symbol":"index_create_path","kind":"function","lang":"rust","code":"fn index_create_path(&self) -> String {\n format!(\"/{}\", self.name)\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":140,"symbol":"show_update_destroy_path","kind":"function","lang":"rust","code":"fn show_update_destroy_path(&self) -> String {\n format!(\"/{0}/{{{0}_id}}\", self.name)\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":144,"symbol":"route","kind":"function","lang":"rust","code":"fn route(mut self, path: &str, method_router: MethodRouter) -> Self {\n self.router = self.router.route(path, method_router);\n self\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":151,"symbol":"from","kind":"function","lang":"rust","code":"fn from(resource: Resource) -> Self {\n resource.router\n }"} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":166,"symbol":"works","kind":"function","lang":"rust","code":"async fn works() {\n let users = Resource::named(\"users\")\n .index(|| async { \"users#index\" })\n .create(|| async { \"users#create\" })\n .new(|| async { \"users#new\" })\n .show(|Path(id): Path| async move { format!(\"users#show id={id}\") })\n .edit(|Path(id): Path| async move { format!(\"users#edit id={id}\") })\n .update(|Path(id): Path| async move { format!(\"users#update id={id}\") })\n .destroy(|Path(id): Path| async move { format!(\"users#destroy id={id}\") });\n\n let app = Router::new().merge(users);\n\n assert_eq!(call_route(&app, Method::GET, \"/users\").await, \"users#index\");\n\n assert_eq!(\n call_route(&app, Method::POST, \"/users\").await,\n \"users#create\"\n );\n\n assert_eq!(\n call_route(&app, Method::GET, \"/users/new\").await,\n \"users#new\"\n );\n\n assert_eq!(\n call_route(&app, Method::GET, \"/users/1\").await,\n \"users#show id=1\"\n );\n\n assert_eq!(\n call_route(&app, Method::GET, \"/users/1/edit\").await,\n \"users#edit id=1\"\n );\n\n assert_eq!(\n "} {"repo":"axum","file":"axum-extra/src/routing/resource.rs","line":216,"symbol":"call_route","kind":"function","lang":"rust","code":"async fn call_route(app: &Router, method: Method, uri: &str) -> String {\n let res = app\n .clone()\n .oneshot(\n Request::builder()\n .method(method)\n .uri(uri)\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n let bytes = res.collect().await.unwrap().to_bytes();\n String::from_utf8(bytes.to_vec()).unwrap()\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":217,"symbol":"TypedPath","kind":"type","lang":"rust","doc":"[`RouterExt::typed_get`]: super::RouterExt::typed_get [`RouterExt::typed_post`]: super::RouterExt::typed_post [`Path`]: axum::extract::Path [`Display`]: std::fmt::Display [`Deserialize`]: serde::Deserialize [`PathRejection`]: axum::extract::rejection::PathRejection","code":"pub trait TypedPath: std::fmt::Display {\n /// The path with optional captures such as `/users/{id}`.\n const PATH: &'static str;\n\n /// Convert the path into a `Uri`.\n ///\n /// # Panics\n ///\n /// The default implementation parses the required [`Display`] implementation. If that fails it\n /// will panic.\n ///\n /// Using `#[derive(TypedPath)]` will never result in a panic since it percent-encodes\n /// arguments.\n ///\n /// [`Display`]: std::fmt::Display\n fn to_uri(&self) -> Uri {\n self.to_string().parse().unwrap()\n }\n\n /// Add query parameters to a path.\n ///\n /// # Example\n ///\n /// ```\n /// use axum_extra::routing::TypedPath;\n /// use serde::Serialize;\n ///\n /// #[derive(TypedPath)]\n /// #[typed_path(\"/users\")]\n /// struct Users;\n ///\n /// #[derive(Serialize)]\n /// struct Pagination {\n /// page: u32,\n /// per_page: u32,\n /// }\n ///\n /// let path = Users.with_query_params(Pagination {\n /// page: 1,\n /// per_page: 10,\n /// });\n ///\n /// assert_eq!(path.to_uri(), \"/users?page=1&per_page=10\");\n /// ```\n ///\n /// # Panics\n ///\n /// If `p"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":232,"symbol":"to_uri","kind":"function","lang":"rust","doc":"will panic. Using `#[derive(TypedPath)]` will never result in a panic since it percent-encodes arguments. [`Display`]: std::fmt::Display","code":"fn to_uri(&self) -> Uri {\n self.to_string().parse().unwrap()\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":269,"symbol":"with_query_params","kind":"function","lang":"rust","doc":"If `params` doesn't support being serialized as query params [`WithQueryParams`]'s [`Display`] implementation will panic, and thus [`WithQueryParams::to_uri`] will also panic. [`WithQueryParams::to_uri`]: TypedPath::to_uri [`Display`]: std::fmt::Display","code":"fn with_query_params(self, params: T) -> WithQueryParams\n where\n T: Serialize,\n Self: Sized,\n {\n WithQueryParams { path: self, params }\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":282,"symbol":"WithQueryParams","kind":"type","lang":"rust","doc":"A [`TypedPath`] with query params. See [`TypedPath::with_query_params`] for more details.","code":"pub struct WithQueryParams {\n path: P,\n params: T,\n}"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":292,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let mut out = self.path.to_string();\n\n let params_start = out.find('?').map(|i| i + 1).unwrap_or_else(|| {\n out.push('?');\n out.len()\n });\n let mut urlencoder = form_urlencoded::Serializer::for_suffix(&mut out, params_start);\n self.params\n .serialize(serde_html_form::ser::Serializer::new(&mut urlencoder))\n .unwrap_or_else(|err| {\n panic!(\n \"failed to URL encode value of type `{}`: {err}\",\n type_name::(),\n )\n });\n f.write_str(&out)?;\n\n Ok(())\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":333,"symbol":"SecondElementIs","kind":"type","lang":"rust","doc":"You normally shouldn't have to use this trait directly. It is sealed such that it cannot be implemented outside this crate. [`RouterExt`]: super::RouterExt","code":"pub trait SecondElementIs

: Sealed {}"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":394,"symbol":"UsersShow","kind":"type","lang":"rust","code":"struct UsersShow {\n id: i32,\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":399,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n foo: &'static str,\n bar: i32,\n baz: bool,\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":406,"symbol":"with_params","kind":"function","lang":"rust","code":"fn with_params() {\n let path = UsersShow { id: 1 }.with_query_params(Params {\n foo: \"foo\",\n bar: 123,\n baz: true,\n });\n\n let uri = path.to_uri();\n\n assert_eq!(uri, \"/users/1?foo=foo&bar=123&baz=true\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":419,"symbol":"with_params_called_multiple_times","kind":"function","lang":"rust","code":"fn with_params_called_multiple_times() {\n let path = UsersShow { id: 1 }\n .with_query_params(Params {\n foo: \"foo\",\n bar: 123,\n baz: true,\n })\n .with_query_params([(\"qux\", 1337)]);\n\n let uri = path.to_uri();\n\n assert_eq!(uri, \"/users/1?foo=foo&bar=123&baz=true&qux=1337\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":434,"symbol":"with_params_question_mark_no_params","kind":"function","lang":"rust","code":"fn with_params_question_mark_no_params() {\n #[derive(TypedPath)]\n #[typed_path(\"/test?\")]\n struct EndsWithQuestionMark;\n\n assert_eq!(EndsWithQuestionMark.to_uri(), \"/test?\");\n\n let path = EndsWithQuestionMark.with_query_params(Params {\n foo: \"foo\",\n bar: 123,\n baz: true,\n });\n\n let uri = path.to_uri();\n\n assert_eq!(uri, \"/test?foo=foo&bar=123&baz=true\");\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":437,"symbol":"EndsWithQuestionMark","kind":"type","lang":"rust","code":"struct EndsWithQuestionMark;"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":454,"symbol":"supports_with_rejection","kind":"function","lang":"rust","code":"fn supports_with_rejection() {\n use crate::routing::RouterExt;\n use axum::{\n extract::rejection::PathRejection,\n response::{IntoResponse, Response},\n Router,\n };\n async fn handler(_: crate::extract::WithRejection) {}\n\n struct MyRejection {}\n\n impl IntoResponse for MyRejection {\n fn into_response(self) -> Response {\n unimplemented!()\n }\n }\n\n impl From for MyRejection {\n fn from(_: PathRejection) -> Self {\n unimplemented!()\n }\n }\n\n let _: Router = Router::new().typed_get(handler);\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":461,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: crate::extract::WithRejection) {}"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":463,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":466,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-extra/src/routing/typed.rs","line":472,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: PathRejection) -> Self {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":55,"symbol":"TypedHeader","kind":"type","lang":"rust","doc":"( TypedHeader(ContentType::text_utf8()), \"Hello, World!\", ) } ```","code":"pub struct TypedHeader(pub T);"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":64,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let mut values = parts.headers.get_all(T::name()).iter();\n let is_missing = values.size_hint() == (0, Some(0));\n T::decode(&mut values)\n .map(Self)\n .map_err(|err| TypedHeaderRejection {\n name: T::name(),\n reason: if is_missing {\n // Report a more precise rejection for the missing header case.\n TypedHeaderRejectionReason::Missing\n } else {\n TypedHeaderRejectionReason::Error(err)\n },\n })\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":88,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n _state: &S,\n ) -> Result, Self::Rejection> {\n let mut values = parts.headers.get_all(T::name()).iter();\n if values.size_hint() == (0, Some(0)) {\n return Ok(None);\n }\n\n match T::decode(&mut values) {\n Ok(value) => Ok(Some(Self(value))),\n Err(err) => Err(TypedHeaderRejection {\n name: T::name(),\n reason: TypedHeaderRejectionReason::Error(err),\n }),\n }\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":115,"symbol":"into_response_parts","kind":"function","lang":"rust","code":"fn into_response_parts(self, mut res: ResponseParts) -> Result {\n res.headers_mut().typed_insert(self.0);\n Ok(res)\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":125,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let mut res = ().into_response();\n res.headers_mut().typed_insert(self.0);\n res\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":135,"symbol":"TypedHeaderRejection","kind":"type","lang":"rust","doc":"Rejection used for [`TypedHeader`].","code":"pub struct TypedHeaderRejection {\n name: &'static http::header::HeaderName,\n reason: TypedHeaderRejectionReason,\n}"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":143,"symbol":"name","kind":"function","lang":"rust","doc":"Name of the header that caused the rejection","code":"pub fn name(&self) -> &http::header::HeaderName {\n self.name\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":149,"symbol":"reason","kind":"function","lang":"rust","doc":"Reason why the header extraction has failed","code":"pub fn reason(&self) -> &TypedHeaderRejectionReason {\n &self.reason\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":157,"symbol":"is_missing","kind":"function","lang":"rust","doc":"Returns `true` if the typed header rejection reason is [`Missing`]. [`Missing`]: TypedHeaderRejectionReason::Missing","code":"pub fn is_missing(&self) -> bool {\n self.reason.is_missing()\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":166,"symbol":"TypedHeaderRejectionReason","kind":"type","lang":"rust","doc":"Additional information regarding a [`TypedHeaderRejection`]","code":"pub enum TypedHeaderRejectionReason {\n /// The header was missing from the HTTP request\n Missing,\n /// An error occurred when parsing the header from the HTTP request\n Error(headers::Error),\n}"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":178,"symbol":"is_missing","kind":"function","lang":"rust","doc":"Returns `true` if the typed header rejection reason is [`Missing`]. [`Missing`]: TypedHeaderRejectionReason::Missing","code":"pub fn is_missing(&self) -> bool {\n matches!(self, Self::Missing)\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":184,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let status = StatusCode::BAD_REQUEST;\n let body = self.to_string();\n axum_core::__log_rejection!(rejection_type = Self, body_text = body, status = status,);\n (status, body).into_response()\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":193,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match &self.reason {\n TypedHeaderRejectionReason::Missing => {\n write!(f, \"Header of type `{}` was missing\", self.name)\n }\n TypedHeaderRejectionReason::Error(err) => {\n write!(f, \"{err} ({})\", self.name)\n }\n }\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":206,"symbol":"source","kind":"function","lang":"rust","code":"fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n match &self.reason {\n TypedHeaderRejectionReason::Error(err) => Some(err),\n TypedHeaderRejectionReason::Missing => None,\n }\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":222,"symbol":"typed_header","kind":"function","lang":"rust","code":"async fn typed_header() {\n async fn handle(\n TypedHeader(user_agent): TypedHeader,\n TypedHeader(cookies): TypedHeader,\n ) -> impl IntoResponse {\n let user_agent = user_agent.as_str();\n let cookies = cookies.iter().collect::>();\n format!(\"User-Agent={user_agent:?}, Cookie={cookies:?}\")\n }\n\n let app = Router::new().route(\"/\", get(handle));\n\n let client = TestClient::new(app);\n\n let res = client\n .get(\"/\")\n .header(\"user-agent\", \"foobar\")\n .header(\"cookie\", \"a=1; b=2\")\n .header(\"cookie\", \"c=3\")\n .await;\n let body = res.text().await;\n assert_eq!(\n body,\n r#\"User-Agent=\"foobar\", Cookie=[(\"a\", \"1\"), (\"b\", \"2\"), (\"c\", \"3\")]\"#\n );\n\n let res = client.get(\"/\").header(\"user-agent\", \"foobar\").await;\n let body = res.text().await;\n assert_eq!(body, r#\"User-Agent=\"foobar\", Cookie=[]\"#);\n\n let res = client.get(\"/\").header(\"cookie\", \"a=1\").await;\n let body = res.text().await;\n assert_eq!(body, \"Header of type `user-agent` "} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":223,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(\n TypedHeader(user_agent): TypedHeader,\n TypedHeader(cookies): TypedHeader,\n ) -> impl IntoResponse {\n let user_agent = user_agent.as_str();\n let cookies = cookies.iter().collect::>();\n format!(\"User-Agent={user_agent:?}, Cookie={cookies:?}\")\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":258,"symbol":"optional_cookie_is_none_when_missing","kind":"function","lang":"rust","code":"async fn optional_cookie_is_none_when_missing() {\n async fn handle(cookie: Option>) -> &'static str {\n if cookie.is_none() {\n \"none\"\n } else {\n \"some\"\n }\n }\n\n let app = Router::new().route(\"/\", get(handle));\n let client = TestClient::new(app);\n\n let res = client.get(\"/\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"none\");\n\n let res = client.get(\"/\").header(\"cookie\", \"a=1\").await;\n assert_eq!(res.status(), StatusCode::OK);\n assert_eq!(res.text().await, \"some\");\n }"} {"repo":"axum","file":"axum-extra/src/typed_header.rs","line":259,"symbol":"handle","kind":"function","lang":"rust","code":"async fn handle(cookie: Option>) -> &'static str {\n if cookie.is_none() {\n \"none\"\n } else {\n \"some\"\n }\n }"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":7,"symbol":"parse_parenthesized_attribute","kind":"function","lang":"rust","code":"pub(crate) fn parse_parenthesized_attribute(\n input: ParseStream<'_>,\n out: &mut Option<(K, T)>,\n) -> syn::Result<()>\nwhere\n K: Parse + ToTokens,\n T: Parse,\n{\n let kw = input.parse()?;\n\n let content;\n syn::parenthesized!(content in input);\n let inner = content.parse()?;\n\n if out.is_some() {\n let kw_name = std::any::type_name::().split(\"::\").last().unwrap();\n let msg = format!(\"`{kw_name}` specified more than once\");\n return Err(syn::Error::new_spanned(kw, msg));\n }\n\n *out = Some((kw, inner));\n\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":32,"symbol":"parse_assignment_attribute","kind":"function","lang":"rust","code":"pub(crate) fn parse_assignment_attribute(\n input: ParseStream<'_>,\n out: &mut Option<(K, T)>,\n) -> syn::Result<()>\nwhere\n K: Parse + ToTokens,\n T: Parse,\n{\n let kw = input.parse()?;\n input.parse::()?;\n let inner = input.parse()?;\n\n if out.is_some() {\n let kw_name = std::any::type_name::().split(\"::\").last().unwrap();\n let msg = format!(\"`{kw_name}` specified more than once\");\n return Err(syn::Error::new_spanned(kw, msg));\n }\n\n *out = Some((kw, inner));\n\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":55,"symbol":"Combine","kind":"type","lang":"rust","code":"pub(crate) trait Combine: Sized {\n fn combine(self, other: Self) -> syn::Result;\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":56,"symbol":"combine","kind":"function","lang":"rust","code":"fn combine(self, other: Self) -> syn::Result;"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":59,"symbol":"parse_attrs","kind":"function","lang":"rust","code":"pub(crate) fn parse_attrs(ident: &str, attrs: &[syn::Attribute]) -> syn::Result\nwhere\n T: Combine + Default + Parse,\n{\n attrs\n .iter()\n .filter(|attr| attr.meta.path().is_ident(ident))\n .map(|attr| attr.parse_args::())\n .try_fold(T::default(), |out, next| out.combine(next?))\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":70,"symbol":"combine_attribute","kind":"function","lang":"rust","code":"pub(crate) fn combine_attribute(a: &mut Option<(K, T)>, b: Option<(K, T)>) -> syn::Result<()>\nwhere\n K: ToTokens,\n{\n if let Some((kw, inner)) = b {\n if a.is_some() {\n let kw_name = std::any::type_name::().split(\"::\").last().unwrap();\n let msg = format!(\"`{kw_name}` specified more than once\");\n return Err(syn::Error::new_spanned(kw, msg));\n }\n *a = Some((kw, inner));\n }\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":85,"symbol":"combine_unary_attribute","kind":"function","lang":"rust","code":"pub(crate) fn combine_unary_attribute(a: &mut Option, b: Option) -> syn::Result<()>\nwhere\n K: ToTokens,\n{\n if let Some(kw) = b {\n if a.is_some() {\n let kw_name = std::any::type_name::().split(\"::\").last().unwrap();\n let msg = format!(\"`{kw_name}` specified more than once\");\n return Err(syn::Error::new_spanned(kw, msg));\n }\n *a = Some(kw);\n }\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/src/attr_parsing.rs","line":100,"symbol":"second","kind":"function","lang":"rust","code":"pub(crate) fn second(tuple: (T, K)) -> K {\n tuple.1\n}"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":5,"symbol":"expand","kind":"function","lang":"rust","code":"pub(crate) fn expand(_attr: Attrs, mut item_fn: ItemFn) -> TokenStream {\n item_fn.attrs.push(parse_quote!(#[tokio::test]));\n\n let nest_service_fn = replace_nest_with_nest_service(item_fn.clone());\n\n quote! {\n #item_fn\n #nest_service_fn\n }\n}"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":16,"symbol":"Attrs","kind":"type","lang":"rust","code":"pub(crate) struct Attrs;"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":19,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(_input: syn::parse::ParseStream<'_>) -> syn::Result {\n Ok(Self)\n }"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":24,"symbol":"replace_nest_with_nest_service","kind":"function","lang":"rust","code":"fn replace_nest_with_nest_service(mut item_fn: ItemFn) -> Option {\n item_fn.sig.ident = format_ident!(\"{}_with_nest_service\", item_fn.sig.ident);\n\n let mut visitor = NestToNestService::default();\n syn::visit_mut::visit_item_fn_mut(&mut visitor, &mut item_fn);\n\n (visitor.count > 0).then_some(item_fn)\n}"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":34,"symbol":"NestToNestService","kind":"type","lang":"rust","code":"struct NestToNestService {\n count: usize,\n}"} {"repo":"axum","file":"axum-macros/src/axum_test.rs","line":39,"symbol":"visit_expr_method_call_mut","kind":"function","lang":"rust","code":"fn visit_expr_method_call_mut(&mut self, i: &mut syn::ExprMethodCall) {\n if i.method == \"nest\" && i.args.len() == 2 {\n i.method = parse_quote!(nest_service);\n self.count += 1;\n }\n }"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":11,"symbol":"expand","kind":"function","lang":"rust","code":"pub(crate) fn expand(attr: Attrs, item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {\n let Attrs { state_ty } = attr;\n\n let mut state_ty = state_ty.map(second);\n\n let check_extractor_count = check_extractor_count(item_fn, kind);\n let check_path_extractor = check_path_extractor(item_fn, kind);\n let check_output_tuples = check_output_tuples(item_fn);\n let check_output_impls_into_response = if check_output_tuples.is_empty() {\n check_output_impls_into_response(item_fn)\n } else {\n check_output_tuples\n };\n\n // If the function is generic, we can't reliably check its inputs or whether the future it\n // returns is `Send`. Skip those checks to avoid unhelpful additional compiler errors.\n let check_inputs_and_future_send = if item_fn.sig.generics.params.is_empty() {\n let mut err = None;\n\n if state_ty.is_none() {\n let state_types_from_args = state_types_from_args(item_fn);\n\n #[allow(clippy::comparison_chain)]\n if state_types_from_args.len() == 1 {\n state_ty = state_types_from_args.into_iter().next();\n } else if state_types_from_args.len() > 1 {\n err = Some(\n"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":92,"symbol":"FunctionKind","kind":"type","lang":"rust","code":"pub(crate) enum FunctionKind {\n Handler,\n Middleware,\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":98,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::Handler => f.write_str(\"handler\"),\n Self::Middleware => f.write_str(\"middleware\"),\n }\n }"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":107,"symbol":"name_uppercase_plural","kind":"function","lang":"rust","code":"fn name_uppercase_plural(self) -> &'static str {\n match self {\n Self::Handler => \"Handlers\",\n Self::Middleware => \"Middleware\",\n }\n }"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":120,"symbol":"Attrs","kind":"type","lang":"rust","code":"pub(crate) struct Attrs {\n state_ty: Option<(kw::state, Type)>,\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":125,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result {\n let mut state_ty = None;\n\n while !input.is_empty() {\n let lh = input.lookahead1();\n if lh.peek(kw::state) {\n parse_assignment_attribute(input, &mut state_ty)?;\n } else {\n return Err(lh.error());\n }\n\n let _ = input.parse::();\n }\n\n Ok(Self { state_ty })\n }"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":143,"symbol":"check_extractor_count","kind":"function","lang":"rust","code":"fn check_extractor_count(item_fn: &ItemFn, kind: FunctionKind) -> Option {\n let max_extractors = 16;\n let inputs = item_fn\n .sig\n .inputs\n .iter()\n .filter(|arg| skip_next_arg(arg, kind))\n .count();\n if inputs <= max_extractors {\n None\n } else {\n let error_message = format!(\n \"{} cannot take more than {max_extractors} arguments. \\\n Use `(a, b): (ExtractorA, ExtractorA)` to further nest extractors\",\n kind.name_uppercase_plural(),\n );\n let error = syn::Error::new_spanned(&item_fn.sig.inputs, error_message).to_compile_error();\n Some(error)\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":164,"symbol":"extractor_idents","kind":"function","lang":"rust","code":"fn extractor_idents(\n item_fn: &ItemFn,\n kind: FunctionKind,\n) -> impl Iterator {\n item_fn\n .sig\n .inputs\n .iter()\n .filter(move |arg| skip_next_arg(arg, kind))\n .enumerate()\n .filter_map(|(idx, fn_arg)| match fn_arg {\n FnArg::Receiver(_) => None,\n FnArg::Typed(pat_type) => {\n if let Type::Path(type_path) = &*pat_type.ty {\n type_path\n .path\n .segments\n .last()\n .map(|segment| (idx, fn_arg, &segment.ident))\n } else {\n None\n }\n }\n })\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":190,"symbol":"check_path_extractor","kind":"function","lang":"rust","code":"fn check_path_extractor(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {\n let path_extractors = extractor_idents(item_fn, kind)\n .filter(|(_, _, ident)| *ident == \"Path\")\n .collect::>();\n\n if path_extractors.len() > 1 {\n path_extractors\n .into_iter()\n .map(|(_, arg, _)| {\n syn::Error::new_spanned(\n arg,\n \"Multiple parameters must be extracted with a tuple \\\n `Path<(_, _)>` or a struct `Path`, not by applying \\\n multiple `Path<_>` extractors\",\n )\n .to_compile_error()\n })\n .collect()\n } else {\n quote! {}\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":213,"symbol":"is_self_pat_type","kind":"function","lang":"rust","code":"fn is_self_pat_type(typed: &syn::PatType) -> bool {\n let ident = if let syn::Pat::Ident(ident) = &*typed.pat {\n &ident.ident\n } else {\n return false;\n };\n\n ident == \"self\"\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":223,"symbol":"check_inputs_impls_from_request","kind":"function","lang":"rust","code":"fn check_inputs_impls_from_request(\n item_fn: &ItemFn,\n state_ty: &Type,\n kind: FunctionKind,\n) -> TokenStream {\n let takes_self = item_fn.sig.inputs.first().is_some_and(|arg| match arg {\n FnArg::Receiver(_) => true,\n FnArg::Typed(typed) => is_self_pat_type(typed),\n });\n\n WithPosition::new(\n item_fn\n .sig\n .inputs\n .iter()\n .filter(|arg| skip_next_arg(arg, kind)),\n )\n .enumerate()\n .map(|(idx, arg)| {\n let must_impl_from_request_parts = match &arg {\n Position::First(_) | Position::Middle(_) => true,\n Position::Last(_) | Position::Only(_) => false,\n };\n\n let arg = arg.into_inner();\n\n let (span, ty) = match arg {\n FnArg::Receiver(receiver) => {\n if receiver.reference.is_some() {\n return syn::Error::new_spanned(\n receiver,\n \"Handlers must only take owned values\",\n )\n .into_compile_error();\n }\n\n let span = receiver.span();\n (span, syn::parse_quote!(Self))\n }\n "} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":341,"symbol":"check_output_tuples","kind":"function","lang":"rust","code":"fn check_output_tuples(item_fn: &ItemFn) -> TokenStream {\n let elems = match &item_fn.sig.output {\n ReturnType::Type(_, ty) => match &**ty {\n Type::Tuple(tuple) => &tuple.elems,\n _ => return quote! {},\n },\n ReturnType::Default => return quote! {},\n };\n\n let handler_ident = &item_fn.sig.ident;\n\n match elems.len() {\n 0 => quote! {},\n n if n > 17 => syn::Error::new_spanned(\n &item_fn.sig.output,\n \"Cannot return tuples with more than 17 elements\",\n )\n .to_compile_error(),\n _ => WithPosition::new(elems)\n .enumerate()\n .map(|(idx, arg)| match arg {\n Position::First(ty) => match extract_clean_typename(ty).as_deref() {\n Some(\"StatusCode\" | \"Response\") => quote! {},\n Some(\"Parts\") => check_is_response_parts(ty, handler_ident, idx),\n Some(_) | None => {\n if let Some(tn) = well_known_last_response_type(ty) {\n syn::Error::new_spanned(\n ty,\n format!(\n "} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":397,"symbol":"check_into_response","kind":"function","lang":"rust","code":"fn check_into_response(handler: &Ident, ty: &Type) -> TokenStream {\n let (span, ty) = (ty.span(), ty.clone());\n\n let check_fn = format_ident!(\n \"__axum_macros_check_{handler}_into_response_check\",\n span = span,\n );\n\n let call_check_fn = format_ident!(\n \"__axum_macros_check_{handler}_into_response_call_check\",\n span = span,\n );\n\n let call_check_fn_body = quote_spanned! {span=>\n #check_fn();\n };\n\n let from_request_bound = quote_spanned! {span=>\n #ty: ::axum::response::IntoResponse\n };\n quote_spanned! {span=>\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #check_fn()\n where\n #from_request_bound,\n {}\n\n // we have to call the function to actually trigger a compile error\n // since the function is generic, just defining it is not enough\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #call_check_fn() {\n #call_check_fn_body\n }\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":437,"symbol":"check_is_response_parts","kind":"function","lang":"rust","code":"fn check_is_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {\n let (span, ty) = (ty.span(), ty.clone());\n\n let check_fn = format_ident!(\n \"__axum_macros_check_{}_is_response_parts_{index}_check\",\n ident,\n span = span,\n );\n\n quote_spanned! {span=>\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #check_fn(parts: #ty) -> ::axum::http::response::Parts {\n parts\n }\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":456,"symbol":"check_into_response_parts","kind":"function","lang":"rust","code":"fn check_into_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {\n let (span, ty) = (ty.span(), ty.clone());\n\n let check_fn = format_ident!(\n \"__axum_macros_check_{}_into_response_parts_{index}_check\",\n ident,\n span = span,\n );\n\n let call_check_fn = format_ident!(\n \"__axum_macros_check_{}_into_response_parts_{index}_call_check\",\n ident,\n span = span,\n );\n\n let call_check_fn_body = quote_spanned! {span=>\n #check_fn();\n };\n\n let from_request_bound = quote_spanned! {span=>\n #ty: ::axum::response::IntoResponseParts\n };\n quote_spanned! {span=>\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #check_fn()\n where\n #from_request_bound,\n {}\n\n // we have to call the function to actually trigger a compile error\n // since the function is generic, just defining it is not enough\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #call_check_fn() {\n #call_check_fn_body\n }\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":498,"symbol":"check_input_order","kind":"function","lang":"rust","code":"fn check_input_order(item_fn: &ItemFn, kind: FunctionKind) -> Option {\n let number_of_inputs = item_fn\n .sig\n .inputs\n .iter()\n .filter(|arg| skip_next_arg(arg, kind))\n .count();\n\n let types_that_consume_the_request = item_fn\n .sig\n .inputs\n .iter()\n .filter(|arg| skip_next_arg(arg, kind))\n .enumerate()\n .filter_map(|(idx, arg)| {\n let ty = match arg {\n FnArg::Typed(pat_type) => &*pat_type.ty,\n FnArg::Receiver(_) => return None,\n };\n let type_name = request_consuming_type_name(ty)?;\n\n Some((idx, type_name, ty.span()))\n })\n .collect::>();\n\n if types_that_consume_the_request.is_empty() {\n return None;\n };\n\n // exactly one type that consumes the request\n if types_that_consume_the_request.len() == 1 {\n // and that is not the last\n if types_that_consume_the_request[0].0 != number_of_inputs - 1 {\n let (_idx, type_name, span) = &types_that_consume_the_request[0];\n let error = format!(\n \"`{type_name}` consumes the request body and th"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":577,"symbol":"extract_clean_typename","kind":"function","lang":"rust","code":"fn extract_clean_typename(ty: &Type) -> Option {\n let path = match ty {\n Type::Path(type_path) => &type_path.path,\n _ => return None,\n };\n path.segments.last().map(|p| p.ident.to_string())\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":585,"symbol":"request_consuming_type_name","kind":"function","lang":"rust","code":"fn request_consuming_type_name(ty: &Type) -> Option<&'static str> {\n let typename = extract_clean_typename(ty)?;\n\n let type_name = match &*typename {\n \"Json\" => \"Json<_>\",\n \"RawBody\" => \"RawBody<_>\",\n \"RawForm\" => \"RawForm\",\n \"Multipart\" => \"Multipart\",\n \"Protobuf\" => \"Protobuf\",\n \"JsonLines\" => \"JsonLines<_>\",\n \"Form\" => \"Form<_>\",\n \"Request\" => \"Request<_>\",\n \"Bytes\" => \"Bytes\",\n \"String\" => \"String\",\n \"Parts\" => \"Parts\",\n _ => return None,\n };\n\n Some(type_name)\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":606,"symbol":"well_known_last_response_type","kind":"function","lang":"rust","code":"fn well_known_last_response_type(ty: &Type) -> Option<&'static str> {\n let typename = extract_clean_typename(ty)?;\n\n let type_name = match &*typename {\n \"Json\" => \"Json<_>\",\n \"Protobuf\" => \"Protobuf\",\n \"JsonLines\" => \"JsonLines<_>\",\n \"Form\" => \"Form<_>\",\n \"Bytes\" => \"Bytes\",\n \"String\" => \"String\",\n _ => return None,\n };\n\n Some(type_name)\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":622,"symbol":"check_output_impls_into_response","kind":"function","lang":"rust","code":"fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {\n let ty = match &item_fn.sig.output {\n syn::ReturnType::Default => return quote! {},\n syn::ReturnType::Type(_, ty) => ty,\n };\n let span = ty.span();\n\n let declare_inputs = item_fn\n .sig\n .inputs\n .iter()\n .filter_map(|arg| match arg {\n FnArg::Receiver(_) => None,\n FnArg::Typed(pat_ty) => {\n let pat = &pat_ty.pat;\n let ty = &pat_ty.ty;\n Some(quote! {\n let #pat: #ty = panic!();\n })\n }\n })\n .collect::();\n\n let block = &item_fn.block;\n\n let make_value_name = format_ident!(\n \"__axum_macros_check_{}_into_response_make_value\",\n item_fn.sig.ident\n );\n\n let make = if item_fn.sig.asyncness.is_some() {\n quote_spanned! {span=>\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n async fn #make_value_name() -> #ty {\n #declare_inputs\n #block\n }\n }\n } else {\n quote_spanned! {span=>\n "} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":711,"symbol":"check_future_send","kind":"function","lang":"rust","code":"fn check_future_send(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {\n if item_fn.sig.asyncness.is_none() {\n match &item_fn.sig.output {\n syn::ReturnType::Default => {\n return syn::Error::new_spanned(\n item_fn.sig.fn_token,\n format!(\"{} must be `async fn`s\", kind.name_uppercase_plural()),\n )\n .into_compile_error();\n }\n syn::ReturnType::Type(_, ty) => ty,\n };\n }\n\n let span = item_fn.sig.ident.span();\n\n let handler_name = &item_fn.sig.ident;\n\n let args = item_fn.sig.inputs.iter().map(|_| {\n quote_spanned! {span=> panic!() }\n });\n\n let name = format_ident!(\"__axum_macros_check_{}_future\", item_fn.sig.ident);\n\n let define_check = quote! {\n fn check(_: T)\n where T: ::std::future::Future + Send\n {}\n };\n\n let do_check = quote! {\n check(future);\n };\n\n if let Some(receiver) = self_receiver(item_fn) {\n quote! {\n #[allow(warnings)]\n #[allow(unreachable_code)]\n #[doc(hidden)]\n fn #name() {\n #define_check\n "} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":771,"symbol":"self_receiver","kind":"function","lang":"rust","code":"fn self_receiver(item_fn: &ItemFn) -> Option {\n let takes_self = item_fn.sig.inputs.iter().any(|arg| match arg {\n FnArg::Receiver(_) => true,\n FnArg::Typed(typed) => is_self_pat_type(typed),\n });\n\n if takes_self {\n return Some(quote! { Self:: });\n }\n\n if let syn::ReturnType::Type(_, ty) = &item_fn.sig.output {\n if let syn::Type::Path(path) = &**ty {\n let segments = &path.path.segments;\n if segments.len() == 1 {\n if let Some(last) = segments.last() {\n match &last.arguments {\n syn::PathArguments::None if last.ident == \"Self\" => {\n return Some(quote! { Self:: });\n }\n _ => {}\n }\n }\n }\n }\n }\n\n None\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":813,"symbol":"state_types_from_args","kind":"function","lang":"rust","doc":") {} ``` This will extract `AppState`. Returns `None` if there are no `State` args or multiple of different types.","code":"fn state_types_from_args(item_fn: &ItemFn) -> HashSet {\n let types = item_fn\n .sig\n .inputs\n .iter()\n .filter_map(|input| match input {\n FnArg::Receiver(_) => None,\n FnArg::Typed(pat_type) => Some(pat_type),\n })\n .map(|pat_type| &*pat_type.ty);\n crate::infer_state_types(types).collect()\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":826,"symbol":"next_is_last_input","kind":"function","lang":"rust","code":"fn next_is_last_input(item_fn: &ItemFn) -> TokenStream {\n let next_args = item_fn\n .sig\n .inputs\n .iter()\n .enumerate()\n .filter(|(_, arg)| !skip_next_arg(arg, FunctionKind::Middleware))\n .collect::>();\n\n if next_args.is_empty() {\n return quote! {\n compile_error!(\n \"Middleware functions must take `axum::middleware::Next` as the last argument\",\n );\n };\n }\n\n if next_args.len() == 1 {\n let (idx, arg) = &next_args[0];\n if *idx != item_fn.sig.inputs.len() - 1 {\n return quote_spanned! {arg.span()=>\n compile_error!(\"`axum::middleware::Next` must be the last argument\");\n };\n }\n }\n\n if next_args.len() >= 2 {\n return quote! {\n compile_error!(\n \"Middleware functions can only take one argument of type `axum::middleware::Next`\",\n );\n };\n }\n\n quote! {}\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":863,"symbol":"skip_next_arg","kind":"function","lang":"rust","code":"fn skip_next_arg(arg: &FnArg, kind: FunctionKind) -> bool {\n match kind {\n FunctionKind::Handler => true,\n FunctionKind::Middleware => match arg {\n FnArg::Receiver(_) => true,\n FnArg::Typed(pat_type) => {\n if let Type::Path(type_path) = &*pat_type.ty {\n type_path\n .path\n .segments\n .last()\n .map_or(true, |path_segment| path_segment.ident != \"Next\")\n } else {\n true\n }\n }\n },\n }\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":884,"symbol":"ui_debug_handler","kind":"function","lang":"rust","code":"fn ui_debug_handler() {\n crate::run_ui_tests(\"debug_handler\");\n}"} {"repo":"axum","file":"axum-macros/src/debug_handler.rs","line":889,"symbol":"ui_debug_middleware","kind":"function","lang":"rust","code":"fn ui_debug_middleware() {\n crate::run_ui_tests(\"debug_middleware\");\n}"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":11,"symbol":"expand","kind":"function","lang":"rust","code":"pub(crate) fn expand(item: ItemStruct) -> syn::Result {\n if !item.generics.params.is_empty() {\n return Err(syn::Error::new_spanned(\n item.generics,\n \"`#[derive(FromRef)]` doesn't support generics\",\n ));\n }\n\n let tokens = item\n .fields\n .iter()\n .enumerate()\n .map(|(idx, field)| expand_field(&item.ident, idx, field))\n .collect();\n\n Ok(tokens)\n}"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":29,"symbol":"expand_field","kind":"function","lang":"rust","code":"fn expand_field(state: &Ident, idx: usize, field: &Field) -> TokenStream {\n let FieldAttrs { skip } = match parse_attrs(\"from_ref\", &field.attrs) {\n Ok(attrs) => attrs,\n Err(err) => return err.into_compile_error(),\n };\n\n if skip.is_some() {\n return TokenStream::default();\n }\n\n let field_ty = &field.ty;\n let span = field.ty.span();\n\n let body = if let Some(field_ident) = &field.ident {\n if matches!(field_ty, Type::Reference(_)) {\n quote_spanned! {span=> state.#field_ident }\n } else {\n quote_spanned! {span=> state.#field_ident.clone() }\n }\n } else {\n let idx = syn::Index {\n index: idx as _,\n span: field.span(),\n };\n quote_spanned! {span=> state.#idx.clone() }\n };\n\n quote_spanned! {span=>\n #[allow(clippy::clone_on_copy, clippy::clone_on_ref_ptr)]\n impl ::axum::extract::FromRef<#state> for #field_ty {\n fn from_ref(state: &#state) -> Self {\n #body\n }\n }\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":71,"symbol":"FieldAttrs","kind":"type","lang":"rust","code":"pub(super) struct FieldAttrs {\n pub(super) skip: Option,\n}"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":76,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(input: ParseStream<'_>) -> syn::Result {\n let mut skip = None;\n\n while !input.is_empty() {\n let lh = input.lookahead1();\n if lh.peek(kw::skip) {\n skip = Some(input.parse()?);\n } else {\n return Err(lh.error());\n }\n\n let _ = input.parse::();\n }\n\n Ok(Self { skip })\n }"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":95,"symbol":"combine","kind":"function","lang":"rust","code":"fn combine(mut self, other: Self) -> syn::Result {\n let Self { skip } = other;\n combine_unary_attribute(&mut self.skip, skip)?;\n Ok(self)\n }"} {"repo":"axum","file":"axum-macros/src/from_ref.rs","line":103,"symbol":"ui","kind":"function","lang":"rust","code":"fn ui() {\n crate::run_ui_tests(\"from_ref\");\n}"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":14,"symbol":"FromRequestContainerAttrs","kind":"type","lang":"rust","code":"pub(super) struct FromRequestContainerAttrs {\n pub(super) via: Option<(kw::via, syn::Path)>,\n pub(super) rejection: Option<(kw::rejection, syn::Path)>,\n pub(super) state: Option<(kw::state, syn::Type)>,\n}"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":21,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(input: ParseStream<'_>) -> syn::Result {\n let mut via = None;\n let mut rejection = None;\n let mut state = None;\n\n while !input.is_empty() {\n let lh = input.lookahead1();\n if lh.peek(kw::via) {\n parse_parenthesized_attribute(input, &mut via)?;\n } else if lh.peek(kw::rejection) {\n parse_parenthesized_attribute(input, &mut rejection)?;\n } else if lh.peek(kw::state) {\n parse_parenthesized_attribute(input, &mut state)?;\n } else {\n return Err(lh.error());\n }\n\n let _ = input.parse::();\n }\n\n Ok(Self {\n via,\n rejection,\n state,\n })\n }"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":50,"symbol":"combine","kind":"function","lang":"rust","code":"fn combine(mut self, other: Self) -> syn::Result {\n let Self {\n via,\n rejection,\n state,\n } = other;\n combine_attribute(&mut self.via, via)?;\n combine_attribute(&mut self.rejection, rejection)?;\n combine_attribute(&mut self.state, state)?;\n Ok(self)\n }"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":64,"symbol":"FromRequestFieldAttrs","kind":"type","lang":"rust","code":"pub(super) struct FromRequestFieldAttrs {\n pub(super) via: Option<(kw::via, syn::Path)>,\n}"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":69,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(input: ParseStream<'_>) -> syn::Result {\n let mut via = None;\n\n while !input.is_empty() {\n let lh = input.lookahead1();\n if lh.peek(kw::via) {\n parse_parenthesized_attribute(input, &mut via)?;\n } else {\n return Err(lh.error());\n }\n\n let _ = input.parse::();\n }\n\n Ok(Self { via })\n }"} {"repo":"axum","file":"axum-macros/src/from_request/attr.rs","line":88,"symbol":"combine","kind":"function","lang":"rust","code":"fn combine(mut self, other: Self) -> syn::Result {\n let Self { via } = other;\n combine_attribute(&mut self.via, via)?;\n Ok(self)\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":16,"symbol":"Trait","kind":"type","lang":"rust","code":"pub(crate) enum Trait {\n FromRequest,\n FromRequestParts,\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":22,"symbol":"via_marker_type","kind":"function","lang":"rust","code":"fn via_marker_type(self) -> Option {\n match self {\n Self::FromRequest => Some(parse_quote!(M)),\n Self::FromRequestParts => None,\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":31,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::FromRequest => f.write_str(\"FromRequest\"),\n Self::FromRequestParts => f.write_str(\"FromRequestParts\"),\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":40,"symbol":"State","kind":"type","lang":"rust","code":"enum State {\n Custom(syn::Type),\n Default(syn::Type),\n CannotInfer,\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":51,"symbol":"impl_generics","kind":"function","lang":"rust","doc":"```not_rust impl A for B {} ^ this type ```","code":"fn impl_generics(&self) -> impl Iterator {\n match self {\n Self::Default(inner) => Some(inner.clone()),\n Self::Custom(_) => None,\n Self::CannotInfer => Some(parse_quote!(S)),\n }\n .into_iter()\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":64,"symbol":"trait_generics","kind":"function","lang":"rust","doc":"```not_rust impl A for B {} ^ this type ```","code":"fn trait_generics(&self) -> impl Iterator {\n match self {\n Self::Default(inner) | Self::Custom(inner) => iter::once(inner.clone()),\n Self::CannotInfer => iter::once(parse_quote!(S)),\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":71,"symbol":"bounds","kind":"function","lang":"rust","code":"fn bounds(&self) -> TokenStream {\n match self {\n Self::Custom(_) => quote! {},\n Self::Default(inner) => quote! {\n #inner: ::std::marker::Send + ::std::marker::Sync,\n },\n Self::CannotInfer => quote! {\n S: ::std::marker::Send + ::std::marker::Sync,\n },\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":85,"symbol":"to_tokens","kind":"function","lang":"rust","code":"fn to_tokens(&self, tokens: &mut TokenStream) {\n match self {\n Self::Custom(inner) | Self::Default(inner) => inner.to_tokens(tokens),\n Self::CannotInfer => quote! { S }.to_tokens(tokens),\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":93,"symbol":"expand","kind":"function","lang":"rust","code":"pub(crate) fn expand(item: syn::Item, tr: Trait) -> syn::Result {\n match item {\n syn::Item::Struct(item) => {\n let syn::ItemStruct {\n attrs,\n ident,\n generics,\n fields,\n semi_token: _,\n vis: _,\n struct_token: _,\n } = item;\n\n let generic_ident = parse_single_generic_type_on_struct(generics, &fields, tr)?;\n\n let FromRequestContainerAttrs {\n via,\n rejection,\n state,\n } = parse_attrs(\"from_request\", &attrs)?;\n\n let state = if let Some((_, state)) = state {\n State::Custom(state)\n } else {\n let mut inferred_state_types: HashSet<_> =\n infer_state_type_from_field_types(&fields)\n .chain(infer_state_type_from_field_attributes(&fields))\n .collect();\n\n if let Some((_, via)) = &via {\n inferred_state_types.extend(state_from_via(&ident, via));\n }\n\n match inferred_state_types.len() {\n "} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":230,"symbol":"parse_single_generic_type_on_struct","kind":"function","lang":"rust","code":"fn parse_single_generic_type_on_struct(\n generics: syn::Generics,\n fields: &syn::Fields,\n tr: Trait,\n) -> syn::Result> {\n if let Some(where_clause) = generics.where_clause {\n return Err(syn::Error::new_spanned(\n where_clause,\n format_args!(\"#[derive({tr})] doesn't support structs with `where` clauses\"),\n ));\n }\n\n match generics.params.len() {\n 0 => Ok(None),\n 1 => {\n let param = generics.params.first().unwrap();\n let ty_ident = match param {\n syn::GenericParam::Type(ty) => &ty.ident,\n syn::GenericParam::Lifetime(lifetime) => {\n return Err(syn::Error::new_spanned(\n lifetime,\n format_args!(\n \"#[derive({tr})] doesn't support structs \\\n that are generic over lifetimes\"\n ),\n ));\n }\n syn::GenericParam::Const(konst) => {\n return Err(syn::Error::new_spanned(\n konst,\n format_args!(\n "} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":317,"symbol":"error_on_generic_ident","kind":"function","lang":"rust","code":"fn error_on_generic_ident(generic_ident: Option, tr: Trait) -> syn::Result<()> {\n if let Some(generic_ident) = generic_ident {\n Err(syn::Error::new_spanned(\n generic_ident,\n format_args!(\n \"#[derive({tr})] only supports generics when used with #[from_request(via)]\"\n ),\n ))\n } else {\n Ok(())\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":330,"symbol":"impl_struct_by_extracting_each_field","kind":"function","lang":"rust","code":"fn impl_struct_by_extracting_each_field(\n ident: &syn::Ident,\n fields: &syn::Fields,\n rejection: Option,\n state: &State,\n tr: Trait,\n) -> syn::Result {\n let trait_fn_body = if matches!(state, State::CannotInfer) {\n quote! {\n ::std::unimplemented!()\n }\n } else {\n let extract_fields = extract_fields(fields, rejection.as_ref(), tr)?;\n quote! {\n ::std::result::Result::Ok(Self {\n #(#extract_fields)*\n })\n }\n };\n\n let rejection_ident = if let Some(rejection) = rejection {\n quote!(#rejection)\n } else if has_no_fields(fields) {\n quote!(::std::convert::Infallible)\n } else {\n quote!(::axum::response::Response)\n };\n\n let impl_generics = state\n .impl_generics()\n .collect::>();\n\n let trait_generics = state\n .trait_generics()\n .collect::>();\n\n let state_bounds = state.bounds();\n\n Ok(match tr {\n Trait::FromRequest => quote! {\n #[automatically_derived]\n impl<#impl_generics> ::axum::extract::FromRequest<#trait_gener"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":404,"symbol":"has_no_fields","kind":"function","lang":"rust","code":"fn has_no_fields(fields: &syn::Fields) -> bool {\n match fields {\n syn::Fields::Named(fields) => fields.named.is_empty(),\n syn::Fields::Unnamed(fields) => fields.unnamed.is_empty(),\n syn::Fields::Unit => true,\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":412,"symbol":"extract_fields","kind":"function","lang":"rust","code":"fn extract_fields(\n fields: &syn::Fields,\n rejection: Option<&syn::Path>,\n tr: Trait,\n) -> syn::Result> {\n fn member(field: &syn::Field, index: usize) -> TokenStream {\n if let Some(ident) = &field.ident {\n quote! { #ident }\n } else {\n let member = syn::Member::Unnamed(syn::Index {\n index: index as u32,\n span: field.span(),\n });\n quote! { #member }\n }\n }\n\n fn into_inner(via: Option<&(attr::kw::via, syn::Path)>, ty_span: Span) -> TokenStream {\n if let Some((_, path)) = via {\n let span = path.span();\n quote_spanned! {span=>\n |#path(inner)| inner\n }\n } else {\n quote_spanned! {ty_span=>\n ::std::convert::identity\n }\n }\n }\n\n fn into_outer(\n via: Option<&(attr::kw::via, syn::Path)>,\n ty_span: Span,\n field_ty: &Type,\n ) -> TokenStream {\n if let Some((_, path)) = via {\n let span = path.span();\n quote_spanned! {span=>\n #path<#field_ty>\n }\n } else {\n quote_span"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":417,"symbol":"member","kind":"function","lang":"rust","code":"fn member(field: &syn::Field, index: usize) -> TokenStream {\n if let Some(ident) = &field.ident {\n quote! { #ident }\n } else {\n let member = syn::Member::Unnamed(syn::Index {\n index: index as u32,\n span: field.span(),\n });\n quote! { #member }\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":429,"symbol":"into_inner","kind":"function","lang":"rust","code":"fn into_inner(via: Option<&(attr::kw::via, syn::Path)>, ty_span: Span) -> TokenStream {\n if let Some((_, path)) = via {\n let span = path.span();\n quote_spanned! {span=>\n |#path(inner)| inner\n }\n } else {\n quote_spanned! {ty_span=>\n ::std::convert::identity\n }\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":442,"symbol":"into_outer","kind":"function","lang":"rust","code":"fn into_outer(\n via: Option<&(attr::kw::via, syn::Path)>,\n ty_span: Span,\n field_ty: &Type,\n ) -> TokenStream {\n if let Some((_, path)) = via {\n let span = path.span();\n quote_spanned! {span=>\n #path<#field_ty>\n }\n } else {\n quote_spanned! {ty_span=>\n #field_ty\n }\n }\n }"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":653,"symbol":"peel_option","kind":"function","lang":"rust","code":"fn peel_option(ty: &syn::Type) -> Option<&syn::Type> {\n let syn::Type::Path(type_path) = ty else {\n return None;\n };\n\n let segment = type_path.path.segments.last()?;\n\n if segment.ident != \"Option\" {\n return None;\n }\n\n let args = match &segment.arguments {\n syn::PathArguments::AngleBracketed(args) => args,\n syn::PathArguments::Parenthesized(_) | syn::PathArguments::None => return None,\n };\n\n let ty = if args.args.len() == 1 {\n args.args.last().unwrap()\n } else {\n return None;\n };\n\n if let syn::GenericArgument::Type(ty) = ty {\n Some(ty)\n } else {\n None\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":682,"symbol":"peel_result_ok","kind":"function","lang":"rust","code":"fn peel_result_ok(ty: &syn::Type) -> Option<&syn::Type> {\n let syn::Type::Path(type_path) = ty else {\n return None;\n };\n\n let segment = type_path.path.segments.last()?;\n\n if segment.ident != \"Result\" {\n return None;\n }\n\n let args = match &segment.arguments {\n syn::PathArguments::AngleBracketed(args) => args,\n syn::PathArguments::Parenthesized(_) | syn::PathArguments::None => return None,\n };\n\n let ty = if args.args.len() == 2 {\n args.args.first().unwrap()\n } else {\n return None;\n };\n\n if let syn::GenericArgument::Type(ty) = ty {\n Some(ty)\n } else {\n None\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":711,"symbol":"impl_struct_by_extracting_all_at_once","kind":"function","lang":"rust","code":"fn impl_struct_by_extracting_all_at_once(\n ident: &syn::Ident,\n fields: syn::Fields,\n via_path: &syn::Path,\n rejection: Option<&syn::Path>,\n generic_ident: Option<&Ident>,\n state: &State,\n tr: Trait,\n) -> syn::Result {\n let fields = match fields {\n syn::Fields::Named(fields) => fields.named.into_iter(),\n syn::Fields::Unnamed(fields) => fields.unnamed.into_iter(),\n syn::Fields::Unit => Punctuated::<_, Token![,]>::new().into_iter(),\n };\n\n for field in fields {\n let FromRequestFieldAttrs { via } = parse_attrs(\"from_request\", &field.attrs)?;\n\n if let Some((via, _)) = via {\n return Err(syn::Error::new_spanned(\n via,\n \"`#[from_request(via(...))]` on a field cannot be used \\\n together with `#[from_request(...)]` on the container\",\n ));\n }\n }\n\n let path_span = via_path.span();\n\n // for something like\n //\n // ```\n // #[derive(Clone, Default, FromRequest)]\n // #[from_request(via(State))]\n // struct AppState {}\n // ```\n //\n // we need to implement `impl FromRequest` but only for\n // - `#[deri"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":883,"symbol":"impl_enum_by_extracting_all_at_once","kind":"function","lang":"rust","code":"fn impl_enum_by_extracting_all_at_once(\n ident: &syn::Ident,\n variants: Punctuated,\n path: &syn::Path,\n rejection: Option<&syn::Path>,\n state: &State,\n tr: Trait,\n) -> syn::Result {\n for variant in variants {\n let FromRequestFieldAttrs { via } = parse_attrs(\"from_request\", &variant.attrs)?;\n\n if let Some((via, _)) = via {\n return Err(syn::Error::new_spanned(\n via,\n \"`#[from_request(via(...))]` cannot be used on variants\",\n ));\n }\n\n let fields = match variant.fields {\n syn::Fields::Named(fields) => fields.named.into_iter(),\n syn::Fields::Unnamed(fields) => fields.unnamed.into_iter(),\n syn::Fields::Unit => Punctuated::<_, Token![,]>::new().into_iter(),\n };\n\n for field in fields {\n let FromRequestFieldAttrs { via } = parse_attrs(\"from_request\", &field.attrs)?;\n if let Some((via, _)) = via {\n return Err(syn::Error::new_spanned(\n via,\n \"`#[from_request(via(...))]` cannot be used inside variants\",\n ));\n }\n"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":999,"symbol":"infer_state_type_from_field_types","kind":"function","lang":"rust","doc":"struct Extractor { state: State, } ``` We can infer the state type to be `AppState` because it appears inside a `State`","code":"fn infer_state_type_from_field_types(fields: &Fields) -> impl Iterator + '_ {\n match fields {\n Fields::Named(fields_named) => Box::new(crate::infer_state_types(\n fields_named.named.iter().map(|field| &field.ty),\n )) as Box>,\n Fields::Unnamed(fields_unnamed) => Box::new(crate::infer_state_types(\n fields_unnamed.unnamed.iter().map(|field| &field.ty),\n )),\n Fields::Unit => Box::new(iter::empty()),\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":1022,"symbol":"infer_state_type_from_field_attributes","kind":"function","lang":"rust","doc":"state: AppState, } ``` We can infer the state type to be `AppState` because it has `via(State)` and thus can be extracted with `State`","code":"fn infer_state_type_from_field_attributes(fields: &Fields) -> impl Iterator + '_ {\n match fields {\n Fields::Named(fields_named) => {\n Box::new(fields_named.named.iter().filter_map(|field| {\n // TODO(david): it's a little wasteful to parse the attributes again here\n // ideally we should parse things once and pass the data down\n let FromRequestFieldAttrs { via } =\n parse_attrs(\"from_request\", &field.attrs).ok()?;\n let (_, via_path) = via?;\n path_ident_is_state(&via_path).then(|| field.ty.clone())\n })) as Box>\n }\n Fields::Unnamed(fields_unnamed) => {\n Box::new(fields_unnamed.unnamed.iter().filter_map(|field| {\n // TODO(david): it's a little wasteful to parse the attributes again here\n // ideally we should parse things once and pass the data down\n let FromRequestFieldAttrs { via } =\n parse_attrs(\"from_request\", &field.attrs).ok()?;\n let (_, via_path) = via?;\n path_ident_is_state(&via_path).then(|| field.ty."} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":1048,"symbol":"path_ident_is_state","kind":"function","lang":"rust","code":"fn path_ident_is_state(path: &Path) -> bool {\n if let Some(last_segment) = path.segments.last() {\n last_segment.ident == \"State\"\n } else {\n false\n }\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":1056,"symbol":"state_from_via","kind":"function","lang":"rust","code":"fn state_from_via(ident: &Ident, via: &Path) -> Option {\n path_ident_is_state(via).then(|| parse_quote!(#ident))\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":1061,"symbol":"ui","kind":"function","lang":"rust","code":"fn ui() {\n crate::run_ui_tests(\"from_request\");\n}"} {"repo":"axum","file":"axum-macros/src/from_request/mod.rs","line":1075,"symbol":"test_field_doesnt_impl_from_request","kind":"function","lang":"rust","doc":"```compile_fail #[derive(axum_macros::FromRequest)] struct Extractor { thing: bool, } ```","code":"fn test_field_doesnt_impl_from_request() {}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":376,"symbol":"derive_from_request","kind":"function","lang":"rust","doc":"} ``` [`FromRequest`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRequest.html [`axum::response::Response`]: https://docs.rs/axum/0.8/axum/response/type.Response.html [`axum::extract::rejection::ExtensionRejection`]: https://docs.rs/axum/0.8/axum/extract/rejection/enum.ExtensionRejection.html","code":"pub fn derive_from_request(item: TokenStream) -> TokenStream {\n expand_with(item, |item| from_request::expand(item, FromRequest))\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":425,"symbol":"derive_from_request_parts","kind":"function","lang":"rust","doc":"} ``` Use `#[derive(FromRequest)]` for that. [`FromRequestParts`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRequestParts.html","code":"pub fn derive_from_request_parts(item: TokenStream) -> TokenStream {\n expand_with(item, |item| from_request::expand(item, FromRequestParts))\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":576,"symbol":"debug_handler","kind":"function","lang":"rust","doc":"This macro has no effect when compiled with the release profile. (eg. `cargo build --release`) [`axum`]: https://docs.rs/axum/0.8 [`Handler`]: https://docs.rs/axum/0.8/axum/handler/trait.Handler.html [`axum::extract::State`]: https://docs.rs/axum/0.8/axum/extract/struct.State.html [`debug_handler`]: macro@debug_handler","code":"pub fn debug_handler(_attr: TokenStream, input: TokenStream) -> TokenStream {\n #[cfg(not(debug_assertions))]\n return input;\n\n #[cfg(debug_assertions)]\n return expand_attr_with(_attr, input, |attrs, item_fn| {\n debug_handler::expand(attrs, &item_fn, FunctionKind::Handler)\n });\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":632,"symbol":"debug_middleware","kind":"function","lang":"rust","doc":"This macro has no effect when compiled with the release profile. (eg. `cargo build --release`) [`axum`]: https://docs.rs/axum/latest [`axum::middleware::from_fn`]: https://docs.rs/axum/0.8/axum/middleware/fn.from_fn.html [`debug_middleware`]: macro@debug_middleware","code":"pub fn debug_middleware(_attr: TokenStream, input: TokenStream) -> TokenStream {\n #[cfg(not(debug_assertions))]\n return input;\n\n #[cfg(debug_assertions)]\n return expand_attr_with(_attr, input, |attrs, item_fn| {\n debug_handler::expand(attrs, &item_fn, FunctionKind::Middleware)\n });\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":654,"symbol":"__private_axum_test","kind":"function","lang":"rust","doc":"1. One identical to the function it was placed on. 2. One where calls to `Router::nest` has been replaced with `Router::nest_service` This makes it easy to that `nest` and `nest_service` behaves in the same way, without having to manually write identical tests for both methods.","code":"pub fn __private_axum_test(_attr: TokenStream, input: TokenStream) -> TokenStream {\n expand_attr_with(_attr, input, axum_test::expand)\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":664,"symbol":"derive_typed_path","kind":"function","lang":"rust","doc":"Derive an implementation of [`axum_extra::routing::TypedPath`]. See that trait for more details. [`axum_extra::routing::TypedPath`]: https://docs.rs/axum-extra/latest/axum_extra/routing/trait.TypedPath.html","code":"pub fn derive_typed_path(input: TokenStream) -> TokenStream {\n expand_with(input, |item_struct| typed_path::expand(&item_struct))\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":714,"symbol":"derive_from_ref","kind":"function","lang":"rust","doc":".route(\"/\", get(handler).post(other_handler)) .with_state(state); # let _: axum::Router = app; ``` [`FromRef`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRef.html","code":"pub fn derive_from_ref(item: TokenStream) -> TokenStream {\n expand_with(item, from_ref::expand)\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":718,"symbol":"expand_with","kind":"function","lang":"rust","code":"fn expand_with(input: TokenStream, f: F) -> TokenStream\nwhere\n F: FnOnce(I) -> syn::Result,\n I: Parse,\n K: ToTokens,\n{\n expand(syn::parse(input).and_then(f))\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":727,"symbol":"expand_attr_with","kind":"function","lang":"rust","code":"fn expand_attr_with(attr: TokenStream, input: TokenStream, f: F) -> TokenStream\nwhere\n F: FnOnce(A, I) -> K,\n A: Parse,\n I: Parse,\n K: ToTokens,\n{\n let expand_result = (|| {\n let attr = syn::parse(attr)?;\n let input = syn::parse(input)?;\n Ok(f(attr, input))\n })();\n expand(expand_result)\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":742,"symbol":"expand","kind":"function","lang":"rust","code":"fn expand(result: syn::Result) -> TokenStream\nwhere\n T: ToTokens,\n{\n match result {\n Ok(tokens) => {\n let tokens = (quote! { #tokens }).into();\n if std::env::var_os(\"AXUM_MACROS_DEBUG\").is_some() {\n eprintln!(\"{tokens}\");\n }\n tokens\n }\n Err(err) => err.into_compile_error().into(),\n }\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":758,"symbol":"infer_state_types","kind":"function","lang":"rust","code":"fn infer_state_types<'a, I>(types: I) -> impl Iterator + 'a\nwhere\n I: Iterator + 'a,\n{\n types\n .filter_map(|ty| {\n if let Type::Path(path) = ty {\n Some(&path.path)\n } else {\n None\n }\n })\n .filter_map(|path| {\n if let Some(last_segment) = path.segments.last() {\n if last_segment.ident != \"State\" {\n return None;\n }\n\n match &last_segment.arguments {\n syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => {\n Some(args.args.first().unwrap())\n }\n _ => None,\n }\n } else {\n None\n }\n })\n .filter_map(|generic_arg| {\n if let syn::GenericArgument::Type(ty) = generic_arg {\n Some(ty)\n } else {\n None\n }\n })\n .cloned()\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":797,"symbol":"run_ui_tests","kind":"function","lang":"rust","code":"fn run_ui_tests(directory: &str) {\n #[rustversion::nightly]\n fn go(directory: &str) {\n let t = trybuild::TestCases::new();\n\n if let Ok(mut path) = std::env::var(\"AXUM_TEST_ONLY\") {\n if let Some(path_without_prefix) = path.strip_prefix(\"axum-macros/\") {\n path = path_without_prefix.to_owned();\n }\n\n if !path.contains(&format!(\"/{directory}/\")) {\n return;\n }\n\n if path.contains(\"/fail/\") {\n t.compile_fail(path);\n } else if path.contains(\"/pass/\") {\n t.pass(path);\n } else {\n panic!()\n }\n } else {\n t.compile_fail(format!(\"tests/{directory}/fail/*.rs\"));\n t.pass(format!(\"tests/{directory}/pass/*.rs\"));\n }\n }\n\n #[rustversion::not(nightly)]\n fn go(_directory: &str) {}\n\n go(directory);\n}"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":799,"symbol":"go","kind":"function","lang":"rust","code":"fn go(directory: &str) {\n let t = trybuild::TestCases::new();\n\n if let Ok(mut path) = std::env::var(\"AXUM_TEST_ONLY\") {\n if let Some(path_without_prefix) = path.strip_prefix(\"axum-macros/\") {\n path = path_without_prefix.to_owned();\n }\n\n if !path.contains(&format!(\"/{directory}/\")) {\n return;\n }\n\n if path.contains(\"/fail/\") {\n t.compile_fail(path);\n } else if path.contains(\"/pass/\") {\n t.pass(path);\n } else {\n panic!()\n }\n } else {\n t.compile_fail(format!(\"tests/{directory}/fail/*.rs\"));\n t.pass(format!(\"tests/{directory}/pass/*.rs\"));\n }\n }"} {"repo":"axum","file":"axum-macros/src/lib.rs","line":825,"symbol":"go","kind":"function","lang":"rust","code":"fn go(_directory: &str) {}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":7,"symbol":"expand","kind":"function","lang":"rust","code":"pub(crate) fn expand(item_struct: &ItemStruct) -> syn::Result {\n let ItemStruct {\n attrs,\n ident,\n generics,\n fields,\n ..\n } = item_struct;\n\n if !generics.params.is_empty() || generics.where_clause.is_some() {\n return Err(syn::Error::new_spanned(\n generics,\n \"`#[derive(TypedPath)]` doesn't support generics\",\n ));\n }\n\n let Attrs { path, rejection } = crate::attr_parsing::parse_attrs(\"typed_path\", attrs)?;\n\n let path = path.ok_or_else(|| {\n syn::Error::new(\n Span::call_site(),\n \"Missing path: `#[typed_path(\\\"/foo/bar\\\")]`\",\n )\n })?;\n\n let rejection = rejection.map(second);\n\n match fields {\n syn::Fields::Named(_) => {\n let segments = parse_path(&path)?;\n Ok(expand_named_fields(\n ident,\n &path,\n &segments,\n rejection.as_ref(),\n ))\n }\n syn::Fields::Unnamed(fields) => {\n let segments = parse_path(&path)?;\n expand_unnamed_fields(fields, ident, &path, &segments, rejection.as_ref())\n }\n syn::Fields:"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":57,"symbol":"Attrs","kind":"type","lang":"rust","code":"struct Attrs {\n path: Option,\n rejection: Option<(kw::rejection, syn::Path)>,\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":63,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result {\n let mut path = None;\n let mut rejection = None;\n\n while !input.is_empty() {\n let lh = input.lookahead1();\n if lh.peek(LitStr) {\n path = Some(input.parse()?);\n } else if lh.peek(kw::rejection) {\n parse_parenthesized_attribute(input, &mut rejection)?;\n } else {\n return Err(lh.error());\n }\n\n let _ = input.parse::();\n }\n\n Ok(Self { path, rejection })\n }"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":85,"symbol":"combine","kind":"function","lang":"rust","code":"fn combine(mut self, other: Self) -> syn::Result {\n let Self { path, rejection } = other;\n if let Some(path) = path {\n if self.path.is_some() {\n return Err(syn::Error::new_spanned(\n path,\n \"path specified more than once\",\n ));\n }\n self.path = Some(path);\n }\n combine_attribute(&mut self.rejection, rejection)?;\n Ok(self)\n }"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":101,"symbol":"expand_named_fields","kind":"function","lang":"rust","code":"fn expand_named_fields(\n ident: &syn::Ident,\n path: &LitStr,\n segments: &[Segment],\n rejection: Option<&syn::Path>,\n) -> TokenStream {\n let format_str = format_str_from_path(segments);\n let captures = captures_from_path(segments);\n\n let typed_path_impl = quote_spanned! {path.span()=>\n #[automatically_derived]\n impl ::axum_extra::routing::TypedPath for #ident {\n const PATH: &'static str = #path;\n }\n };\n\n let display_impl = quote_spanned! {path.span()=>\n #[automatically_derived]\n impl ::std::fmt::Display for #ident {\n #[allow(clippy::unnecessary_to_owned)]\n #[allow(clippy::implicit_clone)]\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n let Self { #(#captures,)* } = self;\n write!(\n f,\n #format_str,\n #(\n #captures = ::axum_extra::__private::utf8_percent_encode(\n &#captures.to_string(),\n ::axum_extra::__private::PATH_SEGMENT,\n )\n ),*\n )\n "} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":169,"symbol":"expand_unnamed_fields","kind":"function","lang":"rust","code":"fn expand_unnamed_fields(\n fields: &syn::FieldsUnnamed,\n ident: &syn::Ident,\n path: &LitStr,\n segments: &[Segment],\n rejection: Option<&syn::Path>,\n) -> syn::Result {\n let num_captures = segments\n .iter()\n .filter(|segment| match segment {\n Segment::Capture(_, _) => true,\n Segment::Static(_) => false,\n })\n .count();\n let num_fields = fields.unnamed.len();\n if num_fields != num_captures {\n return Err(syn::Error::new_spanned(\n fields,\n format!(\n \"Mismatch in number of captures and fields. Path has {} but struct has {}\",\n simple_pluralize(num_captures, \"capture\"),\n simple_pluralize(num_fields, \"field\"),\n ),\n ));\n }\n\n let destructure_self = segments\n .iter()\n .filter_map(|segment| match segment {\n Segment::Capture(capture, _) => Some(capture),\n Segment::Static(_) => None,\n })\n .enumerate()\n .map(|(idx, capture)| {\n let idx = syn::Index {\n index: idx as _,\n span: Span::call_site(),\n };\n "} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":274,"symbol":"simple_pluralize","kind":"function","lang":"rust","code":"fn simple_pluralize(count: usize, word: &str) -> String {\n if count == 1 {\n format!(\"{count} {word}\")\n } else {\n format!(\"{count} {word}s\")\n }\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":282,"symbol":"expand_unit_fields","kind":"function","lang":"rust","code":"fn expand_unit_fields(\n ident: &syn::Ident,\n path: &LitStr,\n rejection: Option<&syn::Path>,\n) -> syn::Result {\n for segment in parse_path(path)? {\n match segment {\n Segment::Capture(_, span) => {\n return Err(syn::Error::new(\n span,\n \"Typed paths for unit structs cannot contain captures\",\n ));\n }\n Segment::Static(_) => {}\n }\n }\n\n let typed_path_impl = quote_spanned! {path.span()=>\n #[automatically_derived]\n impl ::axum_extra::routing::TypedPath for #ident {\n const PATH: &'static str = #path;\n }\n };\n\n let display_impl = quote_spanned! {path.span()=>\n #[automatically_derived]\n impl ::std::fmt::Display for #ident {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n write!(f, #path)\n }\n }\n };\n\n let rejection_assoc_type = if let Some(rejection) = &rejection {\n quote! { #rejection }\n } else {\n quote! { ::axum::http::StatusCode }\n };\n let create_rejection = if let Some(rejection) = &rejection {\n "} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":358,"symbol":"format_str_from_path","kind":"function","lang":"rust","code":"fn format_str_from_path(segments: &[Segment]) -> String {\n segments\n .iter()\n .map(|segment| match segment {\n Segment::Capture(capture, _) => format!(\"{{{capture}}}\"),\n Segment::Static(segment) => segment.to_owned(),\n })\n .collect()\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":368,"symbol":"captures_from_path","kind":"function","lang":"rust","code":"fn captures_from_path(segments: &[Segment]) -> Vec {\n segments\n .iter()\n .filter_map(|segment| match segment {\n Segment::Capture(capture, span) => Some(format_ident!(\"{}\", capture, span = *span)),\n Segment::Static(_) => None,\n })\n .collect::>()\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":378,"symbol":"parse_path","kind":"function","lang":"rust","code":"fn parse_path(path: &LitStr) -> syn::Result> {\n let value = path.value();\n if value.is_empty() {\n return Err(syn::Error::new_spanned(\n path,\n \"paths must start with a `/`. Use \\\"/\\\" for root routes\",\n ));\n } else if !path.value().starts_with('/') {\n return Err(syn::Error::new_spanned(path, \"paths must start with a `/`\"));\n }\n\n validate_path_segments(&value, path)?;\n\n let mut segments = Vec::new();\n let mut rest = value.as_str();\n\n while let Some(start) = find_first_not_double(b'{', rest.as_bytes()) {\n if start > 0 {\n segments.push(Segment::Static(rest[..start].to_owned()));\n }\n\n rest = &rest[start + 1..];\n\n if let Some(end) = rest.find('}') {\n let capture = &rest[..end];\n if capture.is_empty() || capture.contains('{') {\n return Err(syn::Error::new_spanned(path, \"invalid capture in path\"));\n }\n\n segments.push(Segment::Capture(\n capture.strip_prefix('*').unwrap_or(capture).to_owned(),\n path.span(),\n ));\n\n rest = &rest[end + 1..];\n } else {\n "} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":426,"symbol":"validate_path_segments","kind":"function","lang":"rust","code":"fn validate_path_segments(value: &str, path: &LitStr) -> syn::Result<()> {\n let mut wildcard_seen = false;\n\n for segment in value.split('/') {\n if wildcard_seen {\n return Err(syn::Error::new_spanned(\n path,\n \"Wildcards must be at the end of the path\",\n ));\n }\n\n let mut capture_count = 0;\n let mut rest = segment;\n while let Some(start) = find_first_not_double(b'{', rest.as_bytes()) {\n capture_count += 1;\n rest = &rest[start + 1..];\n\n if rest.starts_with('*') {\n wildcard_seen = true;\n // a wildcard capture must cover its entire segment\n if start != 0 || rest.find('}') != Some(rest.len() - 1) {\n return Err(syn::Error::new_spanned(\n path,\n \"Wildcards must be at the end of the path\",\n ));\n }\n }\n }\n\n if capture_count > 1 {\n return Err(syn::Error::new_spanned(\n path,\n \"Cannot have multiple path parameters in a single segment\",\n ));\n }\n }\n"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":466,"symbol":"find_first_not_double","kind":"function","lang":"rust","code":"fn find_first_not_double(needle: u8, haystack: &[u8]) -> Option {\n let mut possible_capture = 0;\n while let Some(index) = haystack\n .get(possible_capture..)\n .and_then(|haystack| haystack.iter().position(|byte| byte == &needle))\n {\n let index = index + possible_capture;\n\n if haystack.get(index + 1) == Some(&needle) {\n possible_capture = index + 2;\n continue;\n }\n\n return Some(index);\n }\n\n None\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":485,"symbol":"Segment","kind":"type","lang":"rust","code":"enum Segment {\n Capture(String, Span),\n Static(String),\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":490,"symbol":"path_rejection","kind":"function","lang":"rust","code":"fn path_rejection() -> TokenStream {\n quote! {\n <::axum::extract::Path as ::axum::extract::FromRequestParts>::Rejection\n }\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":496,"symbol":"rejection_assoc_type","kind":"function","lang":"rust","code":"fn rejection_assoc_type(rejection: Option<&syn::Path>) -> TokenStream {\n match rejection {\n Some(rejection) => quote! { #rejection },\n None => path_rejection(),\n }\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":503,"symbol":"map_err_rejection","kind":"function","lang":"rust","code":"fn map_err_rejection(rejection: Option<&syn::Path>) -> TokenStream {\n rejection\n .as_ref()\n .map(|rejection| {\n let path_rejection = path_rejection();\n quote! {\n .map_err(|rejection| {\n <#rejection as ::std::convert::From<#path_rejection>>::from(rejection)\n })\n }\n })\n .unwrap_or_default()\n}"} {"repo":"axum","file":"axum-macros/src/typed_path.rs","line":518,"symbol":"ui","kind":"function","lang":"rust","code":"fn ui() {\n crate::run_ui_tests(\"typed_path\");\n}"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":31,"symbol":"WithPosition","kind":"type","lang":"rust","code":"pub(crate) struct WithPosition\nwhere\n I: Iterator,\n{\n handled_first: bool,\n peekable: Peekable>,\n}"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":43,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(iter: impl IntoIterator) -> Self {\n Self {\n handled_first: false,\n peekable: iter.into_iter().fuse().peekable(),\n }\n }"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":56,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Self {\n Self {\n handled_first: self.handled_first,\n peekable: self.peekable.clone(),\n }\n }"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":65,"symbol":"Position","kind":"type","lang":"rust","code":"pub(crate) enum Position {\n First(T),\n Middle(T),\n Last(T),\n Only(T),\n}"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":73,"symbol":"into_inner","kind":"function","lang":"rust","code":"pub(crate) fn into_inner(self) -> T {\n match self {\n Self::First(x) | Self::Middle(x) | Self::Last(x) | Self::Only(x) => x,\n }\n }"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":83,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option {\n match self.peekable.next() {\n Some(item) => {\n if !self.handled_first {\n // Haven't seen the first item yet, and there is one to give.\n self.handled_first = true;\n // Peek to see if this is also the last item,\n // in which case tag it as `Only`.\n match self.peekable.peek() {\n Some(_) => Some(Position::First(item)),\n None => Some(Position::Only(item)),\n }\n } else {\n // Have seen the first item, and there's something left.\n // Peek to see if this is the last item.\n match self.peekable.peek() {\n Some(_) => Some(Position::Middle(item)),\n None => Some(Position::Last(item)),\n }\n }\n }\n // Iterator is finished.\n None => None,\n }\n }"} {"repo":"axum","file":"axum-macros/src/with_position.rs","line":109,"symbol":"size_hint","kind":"function","lang":"rust","code":"fn size_hint(&self) -> (usize, Option) {\n self.peekable.size_hint()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/argument_not_extractor.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_foo: bool) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/argument_not_extractor.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/duplicate_args.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/duplicate_args.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extension_not_clone.rs","line":4,"symbol":"NonCloneType","kind":"type","lang":"rust","code":"struct NonCloneType;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extension_not_clone.rs","line":7,"symbol":"test_extension_non_clone","kind":"function","lang":"rust","code":"async fn test_extension_non_clone(_: Extension) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extension_not_clone.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_mut.rs","line":4,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_mut.rs","line":12,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_mut.rs","line":19,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(&mut self) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_mut.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_ref.rs","line":4,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_ref.rs","line":12,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_ref.rs","line":19,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(&self) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/extract_self_ref.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/generics.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_extract: T) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/generics.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/invalid_attrs.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/invalid_attrs.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/json_not_deserialize.rs","line":4,"symbol":"Struct","kind":"type","lang":"rust","code":"struct Struct {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/json_not_deserialize.rs","line":7,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_foo: Json) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/json_not_deserialize.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/multiple_paths.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Path, _: Path) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/multiple_paths.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/multiple_request_consumers.rs","line":9,"symbol":"one","kind":"function","lang":"rust","code":"async fn one(_: Json<()>, _: String, _: Uri) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/multiple_request_consumers.rs","line":12,"symbol":"two","kind":"function","lang":"rust","code":"async fn two(_: Json<()>, _: Method, _: Bytes, _: Uri, _: String) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/multiple_request_consumers.rs","line":14,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_a_function.rs","line":4,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_a_function.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_async.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"fn handler() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_async.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_send.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {\n let _rc = std::rc::Rc::new(());\n async {}.await;\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/not_send.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/output_tuple_too_many.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> (\n axum::http::StatusCode,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n axum::http::StatusCode,\n) {\n panic!()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/output_tuple_too_many.rs","line":28,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/returning_request_parts.rs","line":2,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> (\n axum::http::request::Parts, // this should be response parts, not request parts\n axum::http::StatusCode,\n) {\n panic!()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/returning_request_parts.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/single_wrong_return_tuple.rs","line":3,"symbol":"NotIntoResponse","kind":"type","lang":"rust","code":"struct NotIntoResponse;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/single_wrong_return_tuple.rs","line":6,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> (NotIntoResponse) {\n panic!()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/single_wrong_return_tuple.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/too_many_extractors.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(\n _e1: Uri,\n _e2: Uri,\n _e3: Uri,\n _e4: Uri,\n _e5: Uri,\n _e6: Uri,\n _e7: Uri,\n _e8: Uri,\n _e9: Uri,\n _e10: Uri,\n _e11: Uri,\n _e12: Uri,\n _e13: Uri,\n _e14: Uri,\n _e15: Uri,\n _e16: Uri,\n _e17: Uri,\n) {\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/too_many_extractors.rs","line":26,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_order.rs","line":5,"symbol":"one","kind":"function","lang":"rust","code":"async fn one(_: Json<()>, _: Uri) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_order.rs","line":8,"symbol":"two","kind":"function","lang":"rust","code":"async fn two(_: String, _: Uri) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_order.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs","line":4,"symbol":"named_type","kind":"function","lang":"rust","code":"async fn named_type() -> (\n axum::http::StatusCode,\n axum::Json<&'static str>,\n axum::response::AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n) {\n panic!()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs","line":12,"symbol":"CustomIntoResponse","kind":"type","lang":"rust","code":"struct CustomIntoResponse {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs","line":14,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> axum::response::Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs","line":19,"symbol":"custom_type","kind":"function","lang":"rust","code":"async fn custom_type() -> (\n axum::http::StatusCode,\n CustomIntoResponse,\n axum::response::AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,\n) {\n panic!()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs","line":27,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_type.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> bool {\n false\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/fail/wrong_return_type.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/associated_fn_without_self.rs","line":3,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/associated_fn_without_self.rs","line":7,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/associated_fn_without_self.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/deny_unreachable_code.rs","line":6,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(Path(_): Path) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/deny_unreachable_code.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/impl_future.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"fn handler() -> impl Future {\n async {}\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/impl_future.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/impl_into_response.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> impl IntoResponse {\n \"hi!\"\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/impl_into_response.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: State) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":8,"symbol":"handler_2","kind":"function","lang":"rust","code":"async fn handler_2(_: axum::extract::State) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":11,"symbol":"handler_3","kind":"function","lang":"rust","code":"async fn handler_3(_: axum::extract::State, _: axum::extract::State) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":14,"symbol":"handler_4","kind":"function","lang":"rust","code":"async fn handler_4(_: State, _: State) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":17,"symbol":"handler_5","kind":"function","lang":"rust","code":"async fn handler_5(_: axum::extract::State, _: State) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":20,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/infer_state.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/multiple_extractors.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_one: Method, _two: Uri, _three: String) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/multiple_extractors.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/mut_extractor.rs","line":4,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(mut foo: String) -> String {\n foo += \"bar\";\n foo\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/mut_extractor.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/ready.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"fn handler() -> Ready<()> {\n ready(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/ready.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/request_last.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Extension, _: Request) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/request_last.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":4,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":7,"symbol":"concrete_future","kind":"function","lang":"rust","code":"fn concrete_future() -> std::future::Ready> {\n std::future::ready(Ok(()))\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":12,"symbol":"impl_future","kind":"function","lang":"rust","code":"fn impl_future() -> impl std::future::Future> {\n std::future::ready(Ok(()))\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":19,"symbol":"handler_no_arg_one","kind":"function","lang":"rust","code":"async fn handler_no_arg_one() -> Result {\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":24,"symbol":"handler_no_arg_two","kind":"function","lang":"rust","code":"async fn handler_no_arg_two() -> Result<(), impl IntoResponse> {\n Err(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":29,"symbol":"handler_no_arg_three","kind":"function","lang":"rust","code":"async fn handler_no_arg_three() -> Result {\n Ok::<_, ()>(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":34,"symbol":"handler_no_arg_four","kind":"function","lang":"rust","code":"async fn handler_no_arg_four() -> Result {\n Err::<(), _>(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":41,"symbol":"handler_one","kind":"function","lang":"rust","code":"async fn handler_one(foo: String) -> Result {\n dbg!(foo);\n Ok(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":47,"symbol":"handler_two","kind":"function","lang":"rust","code":"async fn handler_two(foo: String) -> Result<(), impl IntoResponse> {\n dbg!(foo);\n Err(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":53,"symbol":"handler_three","kind":"function","lang":"rust","code":"async fn handler_three(foo: String) -> Result {\n dbg!(foo);\n Ok::<_, ()>(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":59,"symbol":"handler_four","kind":"function","lang":"rust","code":"async fn handler_four(foo: String) -> Result {\n dbg!(foo);\n Err::<(), _>(())\n}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":66,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":70,"symbol":"handler_no_arg_one","kind":"function","lang":"rust","code":"async fn handler_no_arg_one(self) -> Result {\n Ok(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":75,"symbol":"handler_no_arg_two","kind":"function","lang":"rust","code":"async fn handler_no_arg_two(self) -> Result<(), impl IntoResponse> {\n Err(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":80,"symbol":"handler_no_arg_three","kind":"function","lang":"rust","code":"async fn handler_no_arg_three(self) -> Result {\n Ok::<_, ()>(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":85,"symbol":"handler_no_arg_four","kind":"function","lang":"rust","code":"async fn handler_no_arg_four(self) -> Result {\n Err::<(), _>(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":94,"symbol":"handler_one","kind":"function","lang":"rust","code":"async fn handler_one(self, foo: String) -> Result {\n dbg!(foo);\n Ok(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":100,"symbol":"handler_two","kind":"function","lang":"rust","code":"async fn handler_two(self, foo: String) -> Result<(), impl IntoResponse> {\n dbg!(foo);\n Err(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":106,"symbol":"handler_three","kind":"function","lang":"rust","code":"async fn handler_three(self, foo: String) -> Result {\n dbg!(foo);\n Ok::<_, ()>(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":112,"symbol":"handler_four","kind":"function","lang":"rust","code":"async fn handler_four(self, foo: String) -> Result {\n dbg!(foo);\n Err::<(), _>(())\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/result_impl_into_response.rs","line":124,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/returns_self.rs","line":4,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/returns_self.rs","line":8,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Self {\n A\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/returns_self.rs","line":14,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/returns_self.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":4,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":12,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":23,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":30,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(self) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":33,"symbol":"handler_with_qualified_self","kind":"function","lang":"rust","code":"async fn handler_with_qualified_self(self: Box) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/self_receiver.rs","line":36,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/set_state.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: A) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/set_state.rs","line":8,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/set_state.rs","line":10,"symbol":"A","kind":"type","lang":"rust","code":"struct A;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/set_state.rs","line":19,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n unimplemented!()\n }"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/set_state.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/state_and_body.rs","line":5,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: State, _: Request) {}"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/state_and_body.rs","line":8,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState;"} {"repo":"axum","file":"axum-macros/tests/debug_handler/pass/state_and_body.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/doesnt_take_next.rs","line":8,"symbol":"my_middleware","kind":"function","lang":"rust","code":"async fn my_middleware(request: Request) -> Response {\n let _ = request;\n ().into_response()\n}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/doesnt_take_next.rs","line":13,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/next_not_last.rs","line":4,"symbol":"my_middleware","kind":"function","lang":"rust","code":"async fn my_middleware(next: Next, request: Request) -> Response {\n next.run(request).await\n}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/next_not_last.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/takes_next_twice.rs","line":4,"symbol":"my_middleware","kind":"function","lang":"rust","code":"async fn my_middleware(request: Request, next: Next, next2: Next) -> Response {\n let _ = next2;\n next.run(request).await\n}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/fail/takes_next_twice.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/pass/basic.rs","line":4,"symbol":"my_middleware","kind":"function","lang":"rust","code":"async fn my_middleware(request: Request, next: Next) -> Response {\n next.run(request).await\n}"} {"repo":"axum","file":"axum-macros/tests/debug_middleware/pass/basic.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_ref/fail/generics.rs","line":4,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n foo: T,\n}"} {"repo":"axum","file":"axum-macros/tests/from_ref/fail/generics.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/basic.rs","line":9,"symbol":"AppState","kind":"type","lang":"rust","doc":"This will implement `FromRef` for each field in the struct.","code":"struct AppState {\n auth_token: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/basic.rs","line":14,"symbol":"handler","kind":"function","lang":"rust","doc":"So those types can be extracted via `State`","code":"async fn handler(_: State) {}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/basic.rs","line":16,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let state = AppState {\n auth_token: Default::default(),\n };\n\n let _: axum::Router = Router::new().route(\"/\", get(handler)).with_state(state);\n}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/reference-types.rs","line":6,"symbol":"State","kind":"type","lang":"rust","code":"struct State {\n inner: &'static str,\n}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/reference-types.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/skip.rs","line":4,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n auth_token: String,\n #[from_ref(skip)]\n also_string: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_ref/pass/skip.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/double_via_attr.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(#[from_request(via(axum::Extension), via(axum::Extension))] State);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/double_via_attr.rs","line":7,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/double_via_attr.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_from_request_ident_in_variant.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"enum Extractor {\n Foo {\n #[from_request(via(axum::Extension))]\n foo: (),\n },\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_from_request_ident_in_variant.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_from_request_on_variant.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"enum Extractor {\n #[from_request(via(axum::Extension))]\n Foo,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_from_request_on_variant.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_no_via.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"enum Extractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/enum_no_via.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(Option);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(T);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via.rs","line":7,"symbol":"foo","kind":"function","lang":"rust","code":"async fn foo(_: Extractor<()>) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = Router::<()>::new().route(\"/\", get(foo));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via_rejection.rs","line":6,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(T);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via_rejection.rs","line":8,"symbol":"foo","kind":"function","lang":"rust","code":"async fn foo(_: Extractor<()>) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/generic_without_via_rejection.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = Router::<()>::new().route(\"/\", get(foo));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/not_enum_or_struct.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/option_without_optional_from_request.rs","line":4,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload;"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/option_without_optional_from_request.rs","line":7,"symbol":"Args","kind":"type","lang":"rust","code":"struct Args {\n payload: Option,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/option_without_optional_from_request.rs","line":11,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Args) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/option_without_optional_from_request.rs","line":13,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":13,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyExtractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":15,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":19,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"enum MyExtractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":21,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":24,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ExtensionRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs","line":30,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/parts_extracting_body.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n body: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/parts_extracting_body.rs","line":8,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequestParts<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/parts_extracting_body.rs","line":14,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n inner_state: State,\n other_state: State,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs","line":11,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs","line":14,"symbol":"OtherState","kind":"type","lang":"rust","code":"struct OtherState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs","line":16,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/unknown_attr_container.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor;"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/unknown_attr_container.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/unknown_attr_field.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(#[from_request(foo)] String);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/unknown_attr_field.rs","line":6,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/via_on_container_and_field.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(#[from_request(via(axum::Extension))] State);"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/via_on_container_and_field.rs","line":8,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/fail/via_on_container_and_field.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container.rs","line":10,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n one: i32,\n two: String,\n three: bool,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container.rs","line":16,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequest<(), Rejection = JsonRejection>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container_parts.rs","line":9,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n one: i32,\n two: String,\n three: bool,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container_parts.rs","line":15,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequestParts<(), Rejection = ExtensionRejection>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/container_parts.rs","line":21,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named_parts.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named_parts.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_named_parts.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor();"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple_parts.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor();"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple_parts.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/empty_tuple_parts.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via.rs","line":6,"symbol":"Extractor","kind":"type","lang":"rust","code":"enum Extractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via.rs","line":8,"symbol":"foo","kind":"function","lang":"rust","code":"async fn foo(_: Extractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = Router::<()>::new().route(\"/\", get(foo));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via_parts.rs","line":6,"symbol":"Extractor","kind":"type","lang":"rust","code":"enum Extractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via_parts.rs","line":8,"symbol":"foo","kind":"function","lang":"rust","code":"async fn foo(_: Extractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/enum_via_parts.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = Router::<()>::new().route(\"/\", get(foo));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named.rs","line":9,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n uri: axum::http::Uri,\n user_agent: TypedHeader,\n content_type: TypedHeader,\n etag: Option>,\n host: Result, TypedHeaderRejection>,\n body: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named.rs","line":18,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequest<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_parts.rs","line":9,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n uri: axum::http::Uri,\n user_agent: TypedHeader,\n content_type: TypedHeader,\n etag: Option>,\n host: Result, TypedHeaderRejection>,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_parts.rs","line":17,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequestParts<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_parts.rs","line":23,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via.rs","line":12,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n #[from_request(via(Extension))]\n state: State,\n #[from_request(via(TypedHeader))]\n user_agent: UserAgent,\n #[from_request(via(TypedHeader))]\n content_type: headers::ContentType,\n #[from_request(via(TypedHeader))]\n etag: Option,\n #[from_request(via(TypedHeader))]\n host: Result,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via.rs","line":25,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequest<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via.rs","line":32,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via.rs","line":34,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via_parts.rs","line":12,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n #[from_request(via(Extension))]\n state: State,\n #[from_request(via(TypedHeader))]\n user_agent: UserAgent,\n #[from_request(via(TypedHeader))]\n content_type: headers::ContentType,\n #[from_request(via(TypedHeader))]\n etag: Option,\n #[from_request(via(TypedHeader))]\n host: Result,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via_parts.rs","line":25,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequestParts<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via_parts.rs","line":32,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/named_via_parts.rs","line":34,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/{something}\", post(handler));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":14,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: Args) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":17,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {\n value: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":23,"symbol":"Args","kind":"type","lang":"rust","code":"struct Args {\n #[from_request(via(axum::extract::Path))]\n something: String,\n #[from_request(via(Json))]\n request: Option,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":30,"symbol":"MyError","kind":"type","lang":"rust","code":"struct MyError(Response);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":33,"symbol":"from","kind":"function","lang":"rust","code":"fn from(rejection: PathRejection) -> Self {\n Self(rejection.into_response())\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":39,"symbol":"from","kind":"function","lang":"rust","code":"fn from(rejection: JsonRejection) -> Self {\n Self(rejection.into_response())\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_json.rs","line":45,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.0\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":15,"symbol":"Extractor","kind":"type","lang":"rust","doc":"Option with via() in a FromRequestParts derive should use OptionalFromRequestParts, not .ok().","code":"struct Extractor {\n #[from_request(via(TypedHeader))]\n content_type: Option,\n #[from_request(via(TypedHeader))]\n user_agent: headers::UserAgent,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":22,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: FromRequestParts<(), Rejection = MyError>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":28,"symbol":"MyError","kind":"type","lang":"rust","code":"struct MyError(Response);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":31,"symbol":"from","kind":"function","lang":"rust","code":"fn from(rejection: TypedHeaderRejection) -> Self {\n Self(rejection.into_response())\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":37,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n self.0\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/option_via_parts.rs","line":42,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":13,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyExtractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":15,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":19,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"struct MyExtractor {\n one: Extension,\n #[from_request(via(Extension))]\n two: String,\n three: OtherExtractor,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":26,"symbol":"OtherExtractor","kind":"type","lang":"rust","code":"struct OtherExtractor;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":35,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(_req: Request, _state: &S) -> Result {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":40,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":43,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ExtensionRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":49,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: (StatusCode, String)) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection.rs","line":55,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":11,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":15,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyJson) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":17,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":22,"symbol":"MyJson","kind":"type","lang":"rust","code":"struct MyJson(HashMap);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":24,"symbol":"MyJsonRejection","kind":"type","lang":"rust","code":"struct MyJsonRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":27,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: JsonRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic.rs","line":33,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":11,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":15,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyQuery) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":17,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":22,"symbol":"MyQuery","kind":"type","lang":"rust","code":"struct MyQuery(HashMap);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":24,"symbol":"MyQueryRejection","kind":"type","lang":"rust","code":"struct MyQueryRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":27,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: QueryRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs","line":33,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":13,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyExtractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":15,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":19,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"struct MyExtractor {\n one: Extension,\n #[from_request(via(Extension))]\n two: String,\n three: OtherExtractor,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":26,"symbol":"OtherExtractor","kind":"type","lang":"rust","code":"struct OtherExtractor;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":35,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":40,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":43,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ExtensionRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":49,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: (StatusCode, String)) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_parts.rs","line":55,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":13,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyExtractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":15,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":19,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"enum MyExtractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":21,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":24,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ExtensionRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs","line":30,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":13,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyExtractor) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":15,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":19,"symbol":"MyExtractor","kind":"type","lang":"rust","code":"enum MyExtractor {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":21,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":24,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: ExtensionRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs","line":30,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":15,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":17,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyJson) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":19,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result, MyJsonRejection>) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":23,"symbol":"MyJson","kind":"type","lang":"rust","code":"struct MyJson(T);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":25,"symbol":"MyJsonRejection","kind":"type","lang":"rust","code":"struct MyJsonRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":28,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: JsonRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs","line":34,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Router = Router::new().route(\"/\", get(handler).post(handler_result));\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":15,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":17,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(_: MyQuery) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":19,"symbol":"handler_result","kind":"function","lang":"rust","code":"async fn handler_result(_: Result, MyQueryRejection>) {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":23,"symbol":"MyQuery","kind":"type","lang":"rust","code":"struct MyQuery(T);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":25,"symbol":"MyQueryRejection","kind":"type","lang":"rust","code":"struct MyQueryRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":28,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: QueryRejection) -> Self {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs","line":34,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n todo!()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_cookie.rs","line":7,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n cookies: PrivateCookieJar,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_cookie.rs","line":11,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n key: Key,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_cookie.rs","line":16,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.key.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_cookie.rs","line":21,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_cookie.rs","line":27,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/a\", get(|_: AppState| async {}))\n .route(\"/b\", get(|_: InnerState| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via.rs","line":17,"symbol":"AppState","kind":"type","lang":"rust","code":"enum AppState {\n One,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via.rs","line":22,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> AppState {\n Self::One\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via.rs","line":29,"symbol":"InnerState","kind":"type","lang":"rust","code":"enum InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via.rs","line":32,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(_: &AppState) -> Self {\n todo!(\"🤷\")\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via_parts.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/a\", get(|_: AppState| async {}))\n .route(\"/b\", get(|_: InnerState| async {}))\n .route(\"/c\", get(|_: AppState, _: InnerState| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via_parts.rs","line":18,"symbol":"AppState","kind":"type","lang":"rust","code":"enum AppState {\n One,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via_parts.rs","line":23,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> AppState {\n Self::One\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via_parts.rs","line":30,"symbol":"InnerState","kind":"type","lang":"rust","code":"enum InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_enum_via_parts.rs","line":33,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(_: &AppState) -> Self {\n todo!(\"🤷\")\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/b\", get(|_: Extractor| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":16,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n app_state: State,\n one: State,\n two: State,\n other_extractor: String,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":24,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n one: One,\n two: Two,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":30,"symbol":"One","kind":"type","lang":"rust","code":"struct One {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":33,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.one.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":39,"symbol":"Two","kind":"type","lang":"rust","code":"struct Two {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit.rs","line":42,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.two.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit_parts.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/b\", get(|_: Extractor| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit_parts.rs","line":17,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n inner_state: State,\n other: Query>,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit_parts.rs","line":23,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n inner: InnerState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit_parts.rs","line":28,"symbol":"InnerState","kind":"type","lang":"rust","code":"struct InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_explicit_parts.rs","line":31,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.inner.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_explicit.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/\", get(|_: Extractor| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_explicit.rs","line":16,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n #[from_request(via(State))]\n state: AppState,\n #[from_request(via(State))]\n inner: InnerState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_explicit.rs","line":24,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n inner: InnerState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_explicit.rs","line":29,"symbol":"InnerState","kind":"type","lang":"rust","code":"struct InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_explicit.rs","line":32,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.inner.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_infer.rs","line":4,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/\", get(|_: Extractor| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_infer.rs","line":11,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n #[from_request(via(State))]\n state: AppState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_field_infer.rs","line":17,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n inner_state: State,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer.rs","line":10,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer.rs","line":12,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_multiple.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n inner_state: State,\n also_inner_state: State,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_multiple.rs","line":11,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_multiple.rs","line":13,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_multiple.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_parts.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n inner_state: State,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_parts.rs","line":10,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_parts.rs","line":12,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_infer_parts.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/b\", get(|_: (), _: AppState| async {}))\n .route(\"/c\", get(|_: (), _: InnerState| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via.rs","line":17,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n inner: InnerState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via.rs","line":23,"symbol":"InnerState","kind":"type","lang":"rust","code":"struct InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via.rs","line":26,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.inner.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_infer.rs","line":4,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/b\", get(|_: AppState| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_infer.rs","line":14,"symbol":"AppState","kind":"type","lang":"rust","doc":"if we're extract \"via\" `State` and not specifying state assume `AppState` is the state","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_parts.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/a\", get(|_: AppState, _: InnerState, _: String| async {}))\n .route(\"/b\", get(|_: AppState, _: String| async {}))\n .route(\"/c\", get(|_: InnerState, _: String| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_parts.rs","line":18,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n inner: InnerState,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_parts.rs","line":24,"symbol":"InnerState","kind":"type","lang":"rust","code":"struct InnerState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_via_parts.rs","line":27,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(input: &AppState) -> Self {\n input.inner.clone()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: axum::Router = Router::new()\n .route(\"/a\", get(|_: Extractor| async {}))\n .with_state(AppState::default());\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":18,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor {\n state: State,\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":23,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":25,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":28,"symbol":"from","kind":"function","lang":"rust","code":"fn from(err: Infallible) -> Self {\n match err {}\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/state_with_rejection.rs","line":34,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n ().into_response()\n }"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(axum::http::HeaderMap, String);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_parts.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(axum::http::HeaderMap, axum::http::Method);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_parts.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_parts.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice.rs","line":6,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(Query, axum::extract::Json);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice.rs","line":9,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice.rs","line":11,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice.rs","line":17,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs","line":6,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(Query, axum::extract::Path);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs","line":9,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs","line":11,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs","line":17,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs","line":7,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(\n #[from_request(via(Query))] Payload,\n #[from_request(via(axum::extract::Json))] Payload,\n);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs","line":13,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs","line":15,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs","line":21,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs","line":7,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(\n #[from_request(via(Query))] Payload,\n #[from_request(via(axum::extract::Path))] Payload,\n);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs","line":13,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs","line":15,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<(), Rejection = Response>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs","line":21,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(#[from_request(via(Extension))] State);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via.rs","line":8,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via.rs","line":10,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via.rs","line":16,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via_parts.rs","line":5,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor(#[from_request(via(Extension))] State);"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via_parts.rs","line":8,"symbol":"State","kind":"type","lang":"rust","code":"struct State;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via_parts.rs","line":10,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<()>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/tuple_via_parts.rs","line":16,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit_parts.rs","line":4,"symbol":"Extractor","kind":"type","lang":"rust","code":"struct Extractor;"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit_parts.rs","line":6,"symbol":"assert_from_request","kind":"function","lang":"rust","code":"fn assert_from_request()\nwhere\n Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,\n{\n}"} {"repo":"axum","file":"axum-macros/tests/from_request/pass/unit_parts.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/catch_all_not_at_end.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n rest: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/catch_all_not_at_end.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/catch_all_not_whole_segment.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n rest: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/catch_all_not_whole_segment.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/missing_capture.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/missing_capture.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/missing_field.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/missing_field.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/multiple_params_in_segment.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n first: String,\n last: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/multiple_params_in_segment.rs","line":11,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/not_deserialize.rs","line":5,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/not_deserialize.rs","line":9,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/route_not_starting_with_slash.rs","line":5,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath;"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/route_not_starting_with_slash.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/route_not_starting_with_slash_non_empty.rs","line":5,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath;"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/route_not_starting_with_slash_non_empty.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/unit_with_capture.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath;"} {"repo":"axum","file":"axum-macros/tests/typed_path/fail/unit_with_capture.rs","line":8,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":6,"symbol":"PrefixedCapture","kind":"type","lang":"rust","code":"struct PrefixedCapture {\n username: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":12,"symbol":"SuffixedCapture","kind":"type","lang":"rust","code":"struct SuffixedCapture {\n name: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":18,"symbol":"MixedCaptures","kind":"type","lang":"rust","code":"struct MixedCaptures {\n user_id: u32,\n team_id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":25,"symbol":"EscapedBrace","kind":"type","lang":"rust","code":"struct EscapedBrace {\n id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":31,"symbol":"UnnamedPrefixedCapture","kind":"type","lang":"rust","code":"struct UnnamedPrefixedCapture(String);"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/affixed_captures.rs","line":33,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new().typed_get(|_: PrefixedCapture| async {});\n _ = axum::Router::<()>::new().typed_get(|_: SuffixedCapture| async {});\n _ = axum::Router::<()>::new().typed_get(|_: MixedCaptures| async {});\n _ = axum::Router::<()>::new().typed_get(|_: EscapedBrace| async {});\n\n assert_eq!(PrefixedCapture::PATH, \"/@{username}\");\n assert_eq!(\n format!(\n \"{}\",\n PrefixedCapture {\n username: \"alice\".to_owned(),\n }\n ),\n \"/@alice\"\n );\n\n assert_eq!(SuffixedCapture::PATH, \"/files/{name}.json\");\n assert_eq!(\n format!(\n \"{}\",\n SuffixedCapture {\n name: \"report final\".to_owned(),\n }\n ),\n \"/files/report%20final.json\"\n );\n\n assert_eq!(\n format!(\n \"{}\",\n MixedCaptures {\n user_id: 1,\n team_id: 2,\n }\n ),\n \"/users/1/teams/team-2\"\n );\n\n assert_eq!(EscapedBrace::PATH, \"/{{escaped_capture}}/{id}\");\n assert_eq!(format!(\"{}\", EscapedBrace { id: 7 }), \"/{escaped_capture}/7\");\n\n assert_eq!(\n format!(\"{}\", UnnamedPref"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":10,"symbol":"MyPathNamed","kind":"type","lang":"rust","code":"struct MyPathNamed {\n foo: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":16,"symbol":"MyPathUnit","kind":"type","lang":"rust","code":"struct MyPathUnit;"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":20,"symbol":"MyPathUnnamed","kind":"type","lang":"rust","code":"struct MyPathUnnamed(String);"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":22,"symbol":"MyRejection","kind":"type","lang":"rust","code":"struct MyRejection;"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":25,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n ().into_response()\n }"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":31,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: PathRejection) -> Self {\n Self\n }"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":37,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Self {\n Self\n }"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/customize_rejection.rs","line":42,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new()\n .typed_get(|_: Result| async {})\n .typed_post(|_: Result| async {})\n .typed_put(|_: Result| async {});\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/into_uri.rs","line":7,"symbol":"Named","kind":"type","lang":"rust","code":"struct Named {\n id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/into_uri.rs","line":13,"symbol":"Unnamed","kind":"type","lang":"rust","code":"struct Unnamed(u32);"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/into_uri.rs","line":17,"symbol":"Unit","kind":"type","lang":"rust","code":"struct Unit;"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/into_uri.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let _: Uri = Named { id: 1 }.to_uri();\n let _: Uri = Unnamed(1).to_uri();\n let _: Uri = Unit.to_uri();\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/named_fields_struct.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n user_id: u32,\n team_id: u32,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/named_fields_struct.rs","line":11,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new().route(\"/\", axum::routing::get(|_: MyPath| async {}));\n\n assert_eq!(MyPath::PATH, \"/users/{user_id}/teams/{team_id}\");\n assert_eq!(\n format!(\n \"{}\",\n MyPath {\n user_id: 1,\n team_id: 2\n }\n ),\n \"/users/1/teams/2\"\n );\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/result_handler.rs","line":7,"symbol":"UsersShow","kind":"type","lang":"rust","code":"struct UsersShow {\n id: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/result_handler.rs","line":11,"symbol":"result_handler","kind":"function","lang":"rust","code":"async fn result_handler(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/result_handler.rs","line":15,"symbol":"UsersIndex","kind":"type","lang":"rust","code":"struct UsersIndex;"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/result_handler.rs","line":17,"symbol":"result_handler_unit_struct","kind":"function","lang":"rust","code":"async fn result_handler_unit_struct(_: Result) {}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/result_handler.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new()\n .typed_post(result_handler)\n .typed_post(result_handler_unit_struct);\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/tuple_struct.rs","line":8,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath(u32, u32);"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/tuple_struct.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new().route(\"/\", axum::routing::get(|_: MyPath| async {}));\n\n assert_eq!(MyPath::PATH, \"/users/{user_id}/teams/{team_id}\");\n assert_eq!(format!(\"{}\", MyPath(1, 2)), \"/users/1/teams/2\");\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/unit_struct.rs","line":5,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath;"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/unit_struct.rs","line":7,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new().route(\"/\", axum::routing::get(|_: MyPath| async {}));\n\n assert_eq!(MyPath::PATH, \"/users\");\n assert_eq!(format!(\"{}\", MyPath), \"/users\");\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/url_encoding.rs","line":6,"symbol":"Named","kind":"type","lang":"rust","code":"struct Named {\n param: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/url_encoding.rs","line":12,"symbol":"Unnamed","kind":"type","lang":"rust","code":"struct Unnamed(String);"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/url_encoding.rs","line":14,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n assert_eq!(\n format!(\n \"{}\",\n Named {\n param: \"a b\".to_string()\n }\n ),\n \"/a%20b\"\n );\n\n assert_eq!(format!(\"{}\", Unnamed(\"a b\".to_string()),), \"/a%20b\");\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/wildcards.rs","line":6,"symbol":"MyPath","kind":"type","lang":"rust","code":"struct MyPath {\n rest: String,\n}"} {"repo":"axum","file":"axum-macros/tests/typed_path/pass/wildcards.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n _ = axum::Router::<()>::new().typed_get(|_: MyPath| async {});\n}"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":15,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let app = app();\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":25,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Result<(), AppError> {\n try_thing()?;\n Ok(())\n}"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":30,"symbol":"try_thing","kind":"function","lang":"rust","code":"fn try_thing() -> Result<(), anyhow::Error> {\n anyhow::bail!(\"it failed!\")\n}"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":35,"symbol":"AppError","kind":"type","lang":"rust","doc":"Make our own error that wraps `anyhow::Error`.","code":"struct AppError(anyhow::Error);"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":39,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"Something went wrong: {}\", self.0),\n )\n .into_response()\n }"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":48,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/\", get(handler))\n}"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":58,"symbol":"from","kind":"function","lang":"rust","code":"fn from(err: E) -> Self {\n Self(err.into())\n }"} {"repo":"axum","file":"examples/anyhow-error-response/src/main.rs","line":71,"symbol":"test_main_page","kind":"function","lang":"rust","code":"async fn test_main_page() {\n let response = app()\n .oneshot(Request::get(\"/\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);\n let body = response.into_body();\n let bytes = body.collect().await.unwrap().to_bytes();\n let html = String::from_utf8(bytes.to_vec()).unwrap();\n\n assert_eq!(html, \"Something went wrong: it failed!\");\n }"} {"repo":"axum","file":"examples/auto-reload/src/main.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // build our application with a route\n let app = Router::new().route(\"/\", get(handler));\n\n let mut listenfd = ListenFd::from_env();\n let listener = match listenfd.take_tcp_listener(0).unwrap() {\n // if we are given a tcp listener on listen fd 0, we use that one\n Some(listener) => {\n listener.set_nonblocking(true).unwrap();\n TcpListener::from_std(listener).unwrap()\n }\n // otherwise fall back to local listening\n None => TcpListener::bind(\"127.0.0.1:3000\").await.unwrap(),\n };\n\n // run it\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/auto-reload/src/main.rs","line":32,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Html<&'static str> {\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/chat/src/main.rs","line":27,"symbol":"AppState","kind":"type","lang":"rust","doc":"Our shared state","code":"struct AppState {\n // We require unique usernames. This tracks which usernames have been taken.\n user_set: Mutex>,\n // Channel used to send messages to all connected clients.\n tx: broadcast::Sender,\n}"} {"repo":"axum","file":"examples/chat/src/main.rs","line":35,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=trace\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Set up application state for use with with_state().\n let user_set = Mutex::new(HashSet::new());\n let (tx, _rx) = broadcast::channel(100);\n\n let app_state = Arc::new(AppState { user_set, tx });\n\n let app = Router::new()\n .route(\"/\", get(index))\n .route(\"/websocket\", get(websocket_handler))\n .with_state(app_state);\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/chat/src/main.rs","line":62,"symbol":"websocket_handler","kind":"function","lang":"rust","code":"async fn websocket_handler(\n ws: WebSocketUpgrade,\n State(state): State>,\n) -> impl IntoResponse {\n ws.on_upgrade(|socket| websocket(socket, state))\n}"} {"repo":"axum","file":"examples/chat/src/main.rs","line":72,"symbol":"websocket","kind":"function","lang":"rust","doc":"This function deals with a single websocket connection, i.e., a single connected client / user, for which we will spawn two independent tasks (for receiving / sending chat messages).","code":"async fn websocket(stream: WebSocket, state: Arc) {\n // By splitting, we can send and receive at the same time.\n let (mut sender, mut receiver) = stream.split();\n\n // Username gets set in the receive loop, if it's valid.\n let mut username = String::new();\n // Loop until a text message is found.\n while let Some(Ok(message)) = receiver.next().await {\n if let Message::Text(name) = message {\n // If username that is sent by client is not taken, fill username string.\n check_username(&state, &mut username, name.as_str());\n\n // If not empty we want to quit the loop else we want to quit function.\n if !username.is_empty() {\n break;\n } else {\n // Only send our client that username is taken.\n let _ = sender\n .send(Message::Text(Utf8Bytes::from_static(\n \"Username already taken.\",\n )))\n .await;\n\n return;\n }\n }\n }\n\n // We subscribe *before* sending the \"joined\" message, so that we will also\n // display it to our client.\n let mut rx = state.t"} {"repo":"axum","file":"examples/chat/src/main.rs","line":148,"symbol":"check_username","kind":"function","lang":"rust","code":"fn check_username(state: &AppState, string: &mut String, name: &str) {\n let mut user_set = state.user_set.lock().unwrap();\n\n if !user_set.contains(name) {\n user_set.insert(name.to_owned());\n\n string.push_str(name);\n }\n}"} {"repo":"axum","file":"examples/chat/src/main.rs","line":159,"symbol":"index","kind":"function","lang":"rust","doc":"Include utf-8 file at **compile** time.","code":"async fn index() -> Html<&'static str> {\n Html(std::include_str!(\"../chat.html\"))\n}"} {"repo":"axum","file":"examples/compression/src/main.rs","line":11,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=trace\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let app: Router = app();\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/compression/src/main.rs","line":29,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/\", post(root)).layer(\n ServiceBuilder::new()\n .layer(RequestDecompressionLayer::new())\n .layer(CompressionLayer::new()),\n )\n}"} {"repo":"axum","file":"examples/compression/src/main.rs","line":37,"symbol":"root","kind":"function","lang":"rust","code":"async fn root(Json(value): Json) -> Json {\n Json(value)\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":16,"symbol":"handle_uncompressed_request_bodies","kind":"function","lang":"rust","code":"async fn handle_uncompressed_request_bodies() {\n // Given\n\n let body = json();\n\n let compressed_request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .body(json_body(&body))\n .unwrap();\n\n // When\n\n let response = app().oneshot(compressed_request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_json_eq!(json_from_response(response).await, json());\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":37,"symbol":"decompress_gzip_request_bodies","kind":"function","lang":"rust","code":"async fn decompress_gzip_request_bodies() {\n // Given\n\n let body = compress_gzip(&json());\n\n let compressed_request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::CONTENT_ENCODING, \"gzip\")\n .body(Body::from(body))\n .unwrap();\n\n // When\n\n let response = app().oneshot(compressed_request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_json_eq!(json_from_response(response).await, json());\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":59,"symbol":"decompress_br_request_bodies","kind":"function","lang":"rust","code":"async fn decompress_br_request_bodies() {\n // Given\n\n let body = compress_br(&json());\n\n let compressed_request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::CONTENT_ENCODING, \"br\")\n .body(Body::from(body))\n .unwrap();\n\n // When\n\n let response = app().oneshot(compressed_request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_json_eq!(json_from_response(response).await, json());\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":81,"symbol":"decompress_zstd_request_bodies","kind":"function","lang":"rust","code":"async fn decompress_zstd_request_bodies() {\n // Given\n\n let body = compress_zstd(&json());\n\n let compressed_request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::CONTENT_ENCODING, \"zstd\")\n .body(Body::from(body))\n .unwrap();\n\n // When\n\n let response = app().oneshot(compressed_request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_json_eq!(json_from_response(response).await, json());\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":103,"symbol":"do_not_compress_response_bodies","kind":"function","lang":"rust","code":"async fn do_not_compress_response_bodies() {\n // Given\n let request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .body(json_body(&json()))\n .unwrap();\n\n // When\n\n let response = app().oneshot(request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_json_eq!(json_from_response(response).await, json());\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":121,"symbol":"compress_response_bodies_with_gzip","kind":"function","lang":"rust","code":"async fn compress_response_bodies_with_gzip() {\n // Given\n let request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::ACCEPT_ENCODING, \"gzip\")\n .body(json_body(&json()))\n .unwrap();\n\n // When\n\n let response = app().oneshot(request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n let response_body = byte_from_response(response).await;\n let mut decoder = GzDecoder::new(response_body.as_ref());\n let mut decompress_body = String::new();\n decoder.read_to_string(&mut decompress_body).unwrap();\n assert_json_eq!(\n serde_json::from_str::(&decompress_body).unwrap(),\n json()\n );\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":147,"symbol":"compress_response_bodies_with_br","kind":"function","lang":"rust","code":"async fn compress_response_bodies_with_br() {\n // Given\n let request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::ACCEPT_ENCODING, \"br\")\n .body(json_body(&json()))\n .unwrap();\n\n // When\n\n let response = app().oneshot(request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n let response_body = byte_from_response(response).await;\n let mut decompress_body = Vec::new();\n brotli::BrotliDecompress(&mut response_body.as_ref(), &mut decompress_body).unwrap();\n assert_json_eq!(\n serde_json::from_slice::(&decompress_body).unwrap(),\n json()\n );\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":172,"symbol":"compress_response_bodies_with_zstd","kind":"function","lang":"rust","code":"async fn compress_response_bodies_with_zstd() {\n // Given\n let request = http::Request::post(\"/\")\n .header(header::CONTENT_TYPE, \"application/json\")\n .header(header::ACCEPT_ENCODING, \"zstd\")\n .body(json_body(&json()))\n .unwrap();\n\n // When\n\n let response = app().oneshot(request).await.unwrap();\n\n // Then\n\n assert_eq!(response.status(), StatusCode::OK);\n let response_body = byte_from_response(response).await;\n let decompress_body = zstd::stream::decode_all(std::io::Cursor::new(response_body)).unwrap();\n assert_json_eq!(\n serde_json::from_slice::(&decompress_body).unwrap(),\n json()\n );\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":195,"symbol":"json","kind":"function","lang":"rust","code":"fn json() -> Value {\n json!({\n \"name\": \"foo\",\n \"mainProduct\": {\n \"typeId\": \"product\",\n \"id\": \"p1\"\n },\n })\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":205,"symbol":"json_body","kind":"function","lang":"rust","code":"fn json_body(input: &Value) -> Body {\n Body::from(serde_json::to_vec(&input).unwrap())\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":209,"symbol":"json_from_response","kind":"function","lang":"rust","code":"async fn json_from_response(response: Response) -> Value {\n let body = byte_from_response(response).await;\n body_as_json(body)\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":214,"symbol":"byte_from_response","kind":"function","lang":"rust","code":"async fn byte_from_response(response: Response) -> Bytes {\n axum::body::to_bytes(response.into_body(), usize::MAX)\n .await\n .unwrap()\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":220,"symbol":"body_as_json","kind":"function","lang":"rust","code":"fn body_as_json(body: Bytes) -> Value {\n serde_json::from_slice(body.as_ref()).unwrap()\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":224,"symbol":"compress_gzip","kind":"function","lang":"rust","code":"fn compress_gzip(json: &Value) -> Vec {\n let request_body = serde_json::to_vec(&json).unwrap();\n\n let mut encoder = GzEncoder::new(Vec::new(), Compression::default());\n encoder.write_all(&request_body).unwrap();\n encoder.finish().unwrap()\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":232,"symbol":"compress_br","kind":"function","lang":"rust","code":"fn compress_br(json: &Value) -> Vec {\n let request_body = serde_json::to_vec(&json).unwrap();\n let mut result = Vec::new();\n\n let params = BrotliEncoderParams::default();\n let _ = brotli::enc::BrotliCompress(&mut &request_body[..], &mut result, ¶ms).unwrap();\n\n result\n}"} {"repo":"axum","file":"examples/compression/src/tests.rs","line":242,"symbol":"compress_zstd","kind":"function","lang":"rust","code":"fn compress_zstd(json: &Value) -> Vec {\n let request_body = serde_json::to_vec(&json).unwrap();\n zstd::stream::encode_all(std::io::Cursor::new(request_body), 4).unwrap()\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":20,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let app = Router::new()\n .route(\"/\", post(handler))\n .layer(middleware::from_fn(print_request_body));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":42,"symbol":"print_request_body","kind":"function","lang":"rust","doc":"middleware that shows how to consume the request body upfront","code":"async fn print_request_body(request: Request, next: Next) -> Result {\n let request = buffer_request_body(request).await?;\n\n Ok(next.run(request).await)\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":51,"symbol":"buffer_request_body","kind":"function","lang":"rust","doc":"the trick is to take the request apart, buffer the body, do what you need to do, then put the request back together","code":"async fn buffer_request_body(request: Request) -> Result {\n let (parts, body) = request.into_parts();\n\n // this won't work if the body is a long-running stream\n let bytes = body\n .collect()\n .await\n .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response())?\n .to_bytes();\n\n do_thing_with_request_body(bytes.clone());\n\n Ok(Request::from_parts(parts, Body::from(bytes)))\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":66,"symbol":"do_thing_with_request_body","kind":"function","lang":"rust","code":"fn do_thing_with_request_body(bytes: Bytes) {\n tracing::debug!(body = ?bytes);\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":70,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(BufferRequestBody(body): BufferRequestBody) {\n tracing::debug!(?body, \"handler received body\");\n}"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":75,"symbol":"BufferRequestBody","kind":"type","lang":"rust","doc":"extractor that shows how to consume the request body upfront","code":"struct BufferRequestBody(Bytes);"} {"repo":"axum","file":"examples/consume-body-in-extractor-or-middleware/src/main.rs","line":84,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let body = Bytes::from_request(req, state)\n .await\n .map_err(|err| err.into_response())?;\n\n do_thing_with_request_body(body.clone());\n\n Ok(Self(body))\n }"} {"repo":"axum","file":"examples/cors/src/main.rs","line":17,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let frontend = async {\n let app = Router::new().route(\"/\", get(html));\n serve(app, 3000).await;\n };\n\n let backend = async {\n let app = Router::new().route(\"/json\", get(json)).layer(\n // see https://docs.rs/tower-http/latest/tower_http/cors/index.html\n // for more details\n //\n // pay attention that for some request types like posting content-type: application/json\n // it is required to add \".allow_headers([http::header::CONTENT_TYPE])\"\n // or see this issue https://github.com/tokio-rs/axum/issues/849\n CorsLayer::new()\n .allow_origin(\"http://localhost:3000\".parse::().unwrap())\n .allow_methods([Method::GET]),\n );\n serve(app, 4000).await;\n };\n\n tokio::join!(frontend, backend);\n}"} {"repo":"axum","file":"examples/cors/src/main.rs","line":41,"symbol":"serve","kind":"function","lang":"rust","code":"async fn serve(app: Router, port: u16) {\n let addr = SocketAddr::from(([127, 0, 0, 1], port));\n let listener = tokio::net::TcpListener::bind(addr).await.unwrap();\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/cors/src/main.rs","line":47,"symbol":"html","kind":"function","lang":"rust","code":"async fn html() -> impl IntoResponse {\n Html(\n r#\"\n \n \"#,\n )\n}"} {"repo":"axum","file":"examples/cors/src/main.rs","line":59,"symbol":"json","kind":"function","lang":"rust","code":"async fn json() -> impl IntoResponse {\n Json(vec![\"one\", \"two\", \"three\"])\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/custom_extractor.rs","line":15,"symbol":"handler","kind":"function","lang":"rust","code":"pub async fn handler(Json(value): Json) -> impl IntoResponse {\n Json(dbg!(value));\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/custom_extractor.rs","line":20,"symbol":"Json","kind":"type","lang":"rust","doc":"We define our own `Json` extractor that customizes the error from `axum::Json`","code":"pub struct Json(pub T);"} {"repo":"axum","file":"examples/customize-extractor-error/src/custom_extractor.rs","line":29,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let (mut parts, body) = req.into_parts();\n\n // We can use other extractors to provide better rejection messages.\n // For example, here we are using `axum::extract::MatchedPath` to\n // provide a better error message.\n //\n // Have to run that first since `Json` extraction consumes the request.\n let path = parts\n .extract::()\n .await\n .map(|path| path.as_str().to_owned())\n .ok();\n\n let req = Request::from_parts(parts, body);\n\n match axum::Json::::from_request(req, state).await {\n Ok(value) => Ok(Self(value.0)),\n // convert the error from `axum::Json` into whatever we want\n Err(rejection) => {\n let payload = json!({\n \"message\": rejection.body_text(),\n \"origin\": \"custom_extractor\",\n \"path\": path,\n });\n\n Err((rejection.status(), axum::Json(payload)))\n }\n }\n }"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":21,"symbol":"handler","kind":"function","lang":"rust","code":"pub async fn handler(Json(value): Json) -> impl IntoResponse {\n Json(dbg!(value))\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":28,"symbol":"Json","kind":"type","lang":"rust","doc":"create an extractor that internally uses `axum::Json` but has a custom rejection","code":"pub struct Json(T);"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":32,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> axum::response::Response {\n let Self(value) = self;\n axum::Json(value).into_response()\n }"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":40,"symbol":"ApiError","kind":"type","lang":"rust","doc":"We create our own rejection type","code":"pub struct ApiError {\n status: StatusCode,\n message: String,\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":47,"symbol":"from","kind":"function","lang":"rust","code":"fn from(rejection: JsonRejection) -> Self {\n Self {\n status: rejection.status(),\n message: rejection.body_text(),\n }\n }"} {"repo":"axum","file":"examples/customize-extractor-error/src/derive_from_request.rs","line":57,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> axum::response::Response {\n let payload = json!({\n \"message\": self.message,\n \"origin\": \"derive_from_request\"\n });\n\n (self.status, axum::Json(payload)).into_response()\n }"} {"repo":"axum","file":"examples/customize-extractor-error/src/main.rs","line":15,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=trace\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Build our application with some routes\n let app = Router::new()\n .route(\"/with-rejection\", post(with_rejection::handler))\n .route(\"/custom-extractor\", post(custom_extractor::handler))\n .route(\"/derive-from-request\", post(derive_from_request::handler));\n\n // Run our application\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/with_rejection.rs","line":21,"symbol":"handler","kind":"function","lang":"rust","code":"pub async fn handler(\n // `WithRejection` will extract `Json` from the request. If it fails,\n // `JsonRejection` will be transform into `ApiError` and returned as response\n // to the client.\n //\n // The second constructor argument is not meaningful and can be safely ignored\n WithRejection(Json(value), _): WithRejection, ApiError>,\n) -> impl IntoResponse {\n Json(dbg!(value))\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/with_rejection.rs","line":34,"symbol":"ApiError","kind":"type","lang":"rust","doc":"We derive `thiserror::Error`","code":"pub enum ApiError {\n // The `#[from]` attribute generates `From for ApiError`\n // implementation. See `thiserror` docs for more information\n #[error(transparent)]\n JsonExtractorRejection(#[from] JsonRejection),\n}"} {"repo":"axum","file":"examples/customize-extractor-error/src/with_rejection.rs","line":43,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> axum::response::Response {\n let (status, message) = match self {\n ApiError::JsonExtractorRejection(json_rejection) => {\n (json_rejection.status(), json_rejection.body_text())\n }\n };\n\n let payload = json!({\n \"message\": message,\n \"origin\": \"with_rejection\"\n });\n\n (status, Json(payload)).into_response()\n }"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with a route\n let app = Router::new().route(\"/users/{user_id}/teams/{team_id}\", get(handler));\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":38,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(Path(params): Path) -> impl IntoResponse {\n axum::Json(params)\n}"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":43,"symbol":"Params","kind":"type","lang":"rust","code":"struct Params {\n user_id: u32,\n team_id: u32,\n}"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":49,"symbol":"Path","kind":"type","lang":"rust","doc":"We define our own `Path` extractor that customizes the error from `axum::extract::Path`","code":"struct Path(T);"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":59,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n match axum::extract::Path::::from_request_parts(parts, state).await {\n Ok(value) => Ok(Self(value.0)),\n Err(rejection) => {\n let (status, body) = match rejection {\n PathRejection::FailedToDeserializePathParams(inner) => {\n let mut status = StatusCode::BAD_REQUEST;\n\n let kind = inner.into_kind();\n let body = match &kind {\n ErrorKind::WrongNumberOfParameters { .. } => PathError {\n message: kind.to_string(),\n location: None,\n },\n\n ErrorKind::ParseErrorAtKey { key, .. } => PathError {\n message: kind.to_string(),\n location: Some(key.clone()),\n },\n\n ErrorKind::ParseErrorAtIndex { index, .. } => PathError {\n message: kind.to_string(),\n location: Som"} {"repo":"axum","file":"examples/customize-path-rejection/src/main.rs","line":140,"symbol":"PathError","kind":"type","lang":"rust","code":"struct PathError {\n message: String,\n location: Option,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let user_repo = InMemoryUserRepo::default();\n\n // We generally have two ways to inject dependencies:\n //\n // 1. Using trait objects (`dyn SomeTrait`)\n // - Pros\n // - Likely leads to simpler code due to fewer type parameters.\n // - Cons\n // - Less flexible because we can only use object safe traits\n // - Small amount of additional runtime overhead due to dynamic dispatch.\n // This is likely to be negligible.\n // 2. Using generics (`T where T: SomeTrait`)\n // - Pros\n // - More flexible since all traits can be used.\n // - No runtime overhead.\n // - Cons:\n // - Additional type parameters and trait bounds can lead to more complex code and\n // boilerplate.\n //\n // Using trait objects is recommended unless you really need generics.\n\n let using_dyn = "} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":76,"symbol":"AppStateDyn","kind":"type","lang":"rust","code":"struct AppStateDyn {\n user_repo: Arc,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":81,"symbol":"AppStateGeneric","kind":"type","lang":"rust","code":"struct AppStateGeneric {\n user_repo: T,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":86,"symbol":"User","kind":"type","lang":"rust","code":"struct User {\n id: Uuid,\n name: String,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":92,"symbol":"UserParams","kind":"type","lang":"rust","code":"struct UserParams {\n name: String,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":96,"symbol":"create_user_dyn","kind":"function","lang":"rust","code":"async fn create_user_dyn(\n State(state): State,\n Json(params): Json,\n) -> Json {\n let user = User {\n id: Uuid::new_v4(),\n name: params.name,\n };\n\n state.user_repo.save_user(&user);\n\n Json(user)\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":110,"symbol":"get_user_dyn","kind":"function","lang":"rust","code":"async fn get_user_dyn(\n State(state): State,\n Path(id): Path,\n) -> Result, StatusCode> {\n match state.user_repo.get_user(id) {\n Some(user) => Ok(Json(user)),\n None => Err(StatusCode::NOT_FOUND),\n }\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":120,"symbol":"create_user_generic","kind":"function","lang":"rust","code":"async fn create_user_generic(\n State(state): State>,\n Json(params): Json,\n) -> Json\nwhere\n T: UserRepo,\n{\n let user = User {\n id: Uuid::new_v4(),\n name: params.name,\n };\n\n state.user_repo.save_user(&user);\n\n Json(user)\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":137,"symbol":"get_user_generic","kind":"function","lang":"rust","code":"async fn get_user_generic(\n State(state): State>,\n Path(id): Path,\n) -> Result, StatusCode>\nwhere\n T: UserRepo,\n{\n match state.user_repo.get_user(id) {\n Some(user) => Ok(Json(user)),\n None => Err(StatusCode::NOT_FOUND),\n }\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":150,"symbol":"UserRepo","kind":"type","lang":"rust","code":"trait UserRepo: Send + Sync {\n fn get_user(&self, id: Uuid) -> Option;\n\n fn save_user(&self, user: &User);\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":151,"symbol":"get_user","kind":"function","lang":"rust","code":"fn get_user(&self, id: Uuid) -> Option;"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":153,"symbol":"save_user","kind":"function","lang":"rust","code":"fn save_user(&self, user: &User);"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":157,"symbol":"InMemoryUserRepo","kind":"type","lang":"rust","code":"struct InMemoryUserRepo {\n map: Arc>>,\n}"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":162,"symbol":"get_user","kind":"function","lang":"rust","code":"fn get_user(&self, id: Uuid) -> Option {\n self.map.lock().unwrap().get(&id).cloned()\n }"} {"repo":"axum","file":"examples/dependency-injection/src/main.rs","line":166,"symbol":"save_user","kind":"function","lang":"rust","code":"fn save_user(&self, user: &User) {\n self.map.lock().unwrap().insert(user.id, user.clone());\n }"} {"repo":"axum","file":"examples/diesel-async-postgres/migrations/2023-03-14-180127_add_users/up.sql","line":2,"symbol":"\"users\"","kind":"type","lang":"sql","doc":"Your SQL goes here","code":"CREATE TABLE \"users\"(\n \"id\" SERIAL PRIMARY KEY,\n \"name\" TEXT NOT NULL,\n \"hair_color\" TEXT\n)"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":42,"symbol":"User","kind":"type","lang":"rust","code":"struct User {\n id: i32,\n name: String,\n hair_color: Option,\n}"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":50,"symbol":"NewUser","kind":"type","lang":"rust","code":"struct NewUser {\n name: String,\n hair_color: Option,\n}"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":58,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let db_url = std::env::var(\"DATABASE_URL\").unwrap();\n\n // set up connection pool\n let config = AsyncDieselConnectionManager::::new(db_url);\n let pool = bb8::Pool::builder().build(config).await.unwrap();\n\n let mut harness = AsyncMigrationHarness::new(pool.get_owned().await.unwrap());\n harness.run_pending_migrations(MIGRATIONS).unwrap();\n\n // build our application with some routes\n let app = Router::new()\n .route(\"/user/list\", get(list_users))\n .route(\"/user/create\", post(create_user))\n .with_state(pool);\n\n // run it with hyper\n let addr = SocketAddr::from(([127, 0, 0, 1], 3000));\n tracing::debug!(\"listening on {addr}\");\n let listener = tokio::net::TcpListener::bind(addr).await.unwrap();\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":89,"symbol":"create_user","kind":"function","lang":"rust","code":"async fn create_user(\n State(pool): State,\n Json(new_user): Json,\n) -> Result, (StatusCode, String)> {\n let mut conn = pool.get().await.map_err(internal_error)?;\n\n let res = diesel::insert_into(users::table)\n .values(new_user)\n .returning(User::as_returning())\n .get_result(&mut conn)\n .await\n .map_err(internal_error)?;\n Ok(Json(res))\n}"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":106,"symbol":"DatabaseConnection","kind":"type","lang":"rust","doc":"we can also write a custom extractor that grabs a connection from the pool which setup is appropriate depends on your application","code":"struct DatabaseConnection(bb8::PooledConnection<'static, AsyncPgConnection>);"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":115,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result {\n let pool = Pool::from_ref(state);\n\n let conn = pool.get_owned().await.map_err(internal_error)?;\n\n Ok(Self(conn))\n }"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":124,"symbol":"list_users","kind":"function","lang":"rust","code":"async fn list_users(\n DatabaseConnection(mut conn): DatabaseConnection,\n) -> Result>, (StatusCode, String)> {\n let res = User::query()\n .load(&mut conn)\n .await\n .map_err(internal_error)?;\n Ok(Json(res))\n}"} {"repo":"axum","file":"examples/diesel-async-postgres/src/main.rs","line":136,"symbol":"internal_error","kind":"function","lang":"rust","doc":"Utility function for mapping any error into a `500 Internal Server Error` response.","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/diesel-postgres/migrations/2023-03-14-180127_add_users/up.sql","line":2,"symbol":"\"users\"","kind":"type","lang":"sql","doc":"Your SQL goes here","code":"CREATE TABLE \"users\"(\n \"id\" SERIAL PRIMARY KEY,\n \"name\" TEXT NOT NULL,\n \"hair_color\" TEXT\n)"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":39,"symbol":"User","kind":"type","lang":"rust","code":"struct User {\n id: i32,\n name: String,\n hair_color: Option,\n}"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":47,"symbol":"NewUser","kind":"type","lang":"rust","code":"struct NewUser {\n name: String,\n hair_color: Option,\n}"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":53,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let db_url = std::env::var(\"DATABASE_URL\").unwrap();\n\n // set up connection pool\n let manager = deadpool_diesel::postgres::Manager::new(db_url, deadpool_diesel::Runtime::Tokio1);\n let pool = deadpool_diesel::postgres::Pool::builder(manager)\n .build()\n .unwrap();\n\n // run the migrations on server startup\n {\n let conn = pool.get().await.unwrap();\n conn.interact(|conn| conn.run_pending_migrations(MIGRATIONS).map(|_| ()))\n .await\n .unwrap()\n .unwrap();\n }\n\n // build our application with some routes\n let app = Router::new()\n .route(\"/user/list\", get(list_users))\n .route(\"/user/create\", post(create_user))\n .with_state(pool);\n\n // run it with hyper\n let addr = SocketAddr::from(([127, 0, 0, 1], 3000));\n tracing::debug!(\"listening on {addr}\");\n let listener = tokio::net::TcpL"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":92,"symbol":"create_user","kind":"function","lang":"rust","code":"async fn create_user(\n State(pool): State,\n Json(new_user): Json,\n) -> Result, (StatusCode, String)> {\n let conn = pool.get().await.map_err(internal_error)?;\n let res = conn\n .interact(|conn| {\n diesel::insert_into(users::table)\n .values(new_user)\n .returning(User::as_returning())\n .get_result(conn)\n })\n .await\n .map_err(internal_error)?\n .map_err(internal_error)?;\n Ok(Json(res))\n}"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":110,"symbol":"list_users","kind":"function","lang":"rust","code":"async fn list_users(\n State(pool): State,\n) -> Result>, (StatusCode, String)> {\n let conn = pool.get().await.map_err(internal_error)?;\n let res = conn\n .interact(|conn| User::query().load(conn))\n .await\n .map_err(internal_error)?\n .map_err(internal_error)?;\n Ok(Json(res))\n}"} {"repo":"axum","file":"examples/diesel-postgres/src/main.rs","line":124,"symbol":"internal_error","kind":"function","lang":"rust","doc":"Utility function for mapping any error into a `500 Internal Server Error` response.","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":46,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let state = AppState::default();\n\n let app = Router::new()\n // A dummy route that accepts some JSON but sometimes fails\n .route(\"/users\", post(users_create))\n // Layers wraps from the inside out, each new .layer() call becomes the outer one.\n // Putting TraceLayer outermost means its `request` span is entered before\n // log_app_errors runs, so our tracing::error! events inherit that span and get\n // prefixed with `request{method=… uri=… matched_path=…}:`.\n .layer(from_fn(log_app_errors)) // <- Inner layer\n .layer(\n TraceLayer::new_for_http()\n // Create our own span for the request and include the matched path. The matched\n // path is useful for figuring out which handler the request was routed to.\n .make_span_with(|req: &Request| {\n "} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":96,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n next_id: Arc,\n users: Arc>>,\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":102,"symbol":"UserParams","kind":"type","lang":"rust","code":"struct UserParams {\n name: String,\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":107,"symbol":"User","kind":"type","lang":"rust","code":"struct User {\n id: u64,\n name: String,\n created_at: Timestamp,\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":113,"symbol":"users_create","kind":"function","lang":"rust","code":"async fn users_create(\n State(state): State,\n // Make sure to use our own JSON extractor so we get input errors formatted in a way that\n // matches our application\n AppJson(params): AppJson,\n) -> Result, AppError> {\n let id = state.next_id.fetch_add(1, Ordering::SeqCst);\n\n // We have implemented `From for AppError` which allows us to use `?` to\n // automatically convert the error\n let created_at = Timestamp::now()?;\n\n let user = User {\n id,\n name: params.name,\n created_at,\n };\n\n state.users.lock().unwrap().insert(id, user.clone());\n\n Ok(AppJson(user))\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":142,"symbol":"AppJson","kind":"type","lang":"rust","doc":"Create our own JSON extractor by wrapping `axum::Json`. This makes it easy to override the rejection and provide our own which formats errors to match our application. `axum::Json` responds with plain text if the input is invalid.","code":"struct AppJson(T);"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":148,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n axum::Json(self.0).into_response()\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":155,"symbol":"AppError","kind":"type","lang":"rust","doc":"The kinds of errors we can hit in our application.","code":"enum AppError {\n // The request body contained invalid JSON\n JsonRejection(JsonRejection),\n // Some error from a third party library we're using\n TimeError(time_library::Error),\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":164,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n // How we want errors responses to be serialized\n #[derive(Serialize)]\n struct ErrorResponse {\n message: String,\n }\n\n let (status, message, err) = match &self {\n AppError::JsonRejection(rejection) => {\n // This error is caused by bad user input so don't log it\n (rejection.status(), rejection.body_text(), None)\n }\n AppError::TimeError(_err) => {\n // While we could simply log the error here we would introduce\n // a side-effect to our conversion, instead add the AppError to\n // the Response as an Extension\n // Don't expose any details about the error to the client\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n \"Something went wrong\".to_owned(),\n Some(self),\n )\n }\n };\n\n let mut response = (status, AppJson(ErrorResponse { message })).into_response();\n if let Some(err) = err {\n // Insert our error into the response, our logging middleware will use this.\n "} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":167,"symbol":"ErrorResponse","kind":"type","lang":"rust","doc":"How we want errors responses to be serialized","code":"struct ErrorResponse {\n message: String,\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":200,"symbol":"from","kind":"function","lang":"rust","code":"fn from(rejection: JsonRejection) -> Self {\n Self::JsonRejection(rejection)\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":206,"symbol":"from","kind":"function","lang":"rust","code":"fn from(error: time_library::Error) -> Self {\n Self::TimeError(error)\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":212,"symbol":"log_app_errors","kind":"function","lang":"rust","doc":"Our middleware is responsible for logging error details internally","code":"async fn log_app_errors(request: Request, next: Next) -> Response {\n let response = next.run(request).await;\n // If the response contains an AppError Extension, log it.\n if let Some(err) = response.extensions().get::>() {\n tracing::error!(?err, \"an unexpected error occurred inside a handler\");\n }\n response\n}"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":229,"symbol":"Timestamp","kind":"type","lang":"rust","code":"pub struct Timestamp(u64);"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":232,"symbol":"now","kind":"function","lang":"rust","code":"pub fn now() -> Result {\n static COUNTER: AtomicU64 = AtomicU64::new(0);\n\n // Fail on every third call just to simulate errors\n if COUNTER.fetch_add(1, Ordering::SeqCst).is_multiple_of(3) {\n Err(Error::FailedToGetTime)\n } else {\n Ok(Self(1337))\n }\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":245,"symbol":"Error","kind":"type","lang":"rust","code":"pub enum Error {\n FailedToGetTime,\n }"} {"repo":"axum","file":"examples/error-handling/src/main.rs","line":250,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"failed to get time\")\n }"} {"repo":"axum","file":"examples/form/src/main.rs","line":12,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with some routes\n let app = app();\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/form/src/main.rs","line":32,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/\", get(show_form).post(accept_form))\n}"} {"repo":"axum","file":"examples/form/src/main.rs","line":36,"symbol":"show_form","kind":"function","lang":"rust","code":"async fn show_form() -> Html<&'static str> {\n Html(\n r#\"\n \n \n \n \n
\n \n\n \n\n \n
\n \n \n \"#,\n )\n}"} {"repo":"axum","file":"examples/form/src/main.rs","line":64,"symbol":"Input","kind":"type","lang":"rust","code":"struct Input {\n name: String,\n email: String,\n}"} {"repo":"axum","file":"examples/form/src/main.rs","line":69,"symbol":"accept_form","kind":"function","lang":"rust","code":"async fn accept_form(Form(input): Form) -> Html {\n dbg!(&input);\n Html(format!(\"email='{}'\\nname='{}'\\n\", input.email, input.name))\n}"} {"repo":"axum","file":"examples/form/src/main.rs","line":85,"symbol":"test_get","kind":"function","lang":"rust","code":"async fn test_get() {\n let app = app();\n\n let response = app\n .oneshot(Request::get(\"/\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n let body = std::str::from_utf8(&body).unwrap();\n\n assert!(body.contains(r#\"\"#));\n }"} {"repo":"axum","file":"examples/form/src/main.rs","line":102,"symbol":"test_post","kind":"function","lang":"rust","code":"async fn test_post() {\n let app = app();\n\n let response = app\n .oneshot(\n Request::post(\"/\")\n .header(\n http::header::CONTENT_TYPE,\n mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),\n )\n .body(Body::from(\"name=foo&email=bar@axum\"))\n .unwrap(),\n )\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n let body = std::str::from_utf8(&body).unwrap();\n\n assert_eq!(body, \"email='bar@axum'\\nname='foo'\\n\");\n }"} {"repo":"axum","file":"examples/global-404-handler/src/main.rs","line":16,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with a route\n let app = Router::new().route(\"/\", get(handler));\n\n // add a fallback service for handling routes to unknown paths\n let app = app.fallback(handler_404);\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/global-404-handler/src/main.rs","line":39,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Html<&'static str> {\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/global-404-handler/src/main.rs","line":43,"symbol":"handler_404","kind":"function","lang":"rust","code":"async fn handler_404() -> impl IntoResponse {\n (StatusCode::NOT_FOUND, \"nothing to see here\")\n}"} {"repo":"axum","file":"examples/graceful-shutdown/src/main.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // Enable tracing.\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\n \"{}=debug,tower_http=debug,axum=trace\",\n env!(\"CARGO_CRATE_NAME\")\n )\n .into()\n }),\n )\n .with(tracing_subscriber::fmt::layer().without_time())\n .init();\n\n // Create a regular axum app.\n let app = Router::new()\n .route(\"/slow\", get(|| sleep(Duration::from_secs(5))))\n .route(\"/forever\", get(std::future::pending::<()>))\n .layer((\n TraceLayer::new_for_http(),\n // Graceful shutdown will wait for outstanding requests to complete. Add a timeout so\n // requests don't hang forever.\n TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_secs(10)),\n ));\n\n // Create a `TcpListener` using tokio.\n let listener = TcpListener::bind(\"0.0.0.0:3000\").await.unwrap();\n\n // Run the server with graceful shutdown\n axum::serve(listener, app)\n .with_graceful_shutdown(shutdown_signal())\n "} {"repo":"axum","file":"examples/graceful-shutdown/src/main.rs","line":54,"symbol":"shutdown_signal","kind":"function","lang":"rust","code":"async fn shutdown_signal() {\n let ctrl_c = async {\n signal::ctrl_c()\n .await\n .expect(\"failed to install Ctrl+C handler\");\n };\n\n #[cfg(unix)]\n let terminate = async {\n signal::unix::signal(signal::unix::SignalKind::terminate())\n .expect(\"failed to install signal handler\")\n .recv()\n .await;\n };\n\n #[cfg(not(unix))]\n let terminate = std::future::pending::<()>();\n\n tokio::select! {\n _ = ctrl_c => {},\n _ = terminate => {},\n }\n}"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":10,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/get-head\", get(get_head_handler))\n}"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":15,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app()).await;\n}"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":25,"symbol":"get_head_handler","kind":"function","lang":"rust","doc":"GET routes will also be called for HEAD requests but will have the response body removed. You can handle the HEAD method explicitly by extracting `http::Method` from the request.","code":"async fn get_head_handler(method: http::Method) -> Response {\n // it usually only makes sense to special-case HEAD\n // if computing the body has some relevant cost\n if method == http::Method::HEAD {\n return ([(\"x-some-header\", \"header from HEAD\")]).into_response();\n }\n\n // then do some computing task in GET\n do_some_computing_task();\n\n ([(\"x-some-header\", \"header from GET\")], \"body from GET\").into_response()\n}"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":38,"symbol":"do_some_computing_task","kind":"function","lang":"rust","code":"fn do_some_computing_task() {\n // TODO\n}"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":51,"symbol":"test_get","kind":"function","lang":"rust","code":"async fn test_get() {\n let app = app();\n\n let response = app\n .oneshot(Request::get(\"/get-head\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_eq!(response.headers()[\"x-some-header\"], \"header from GET\");\n\n let body = response.collect().await.unwrap().to_bytes();\n assert_eq!(&body[..], b\"body from GET\");\n }"} {"repo":"axum","file":"examples/handle-head-request/src/main.rs","line":67,"symbol":"test_implicit_head","kind":"function","lang":"rust","code":"async fn test_implicit_head() {\n let app = app();\n\n let response = app\n .oneshot(Request::head(\"/get-head\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n assert_eq!(response.headers()[\"x-some-header\"], \"header from HEAD\");\n\n let body = response.collect().await.unwrap().to_bytes();\n assert!(body.is_empty());\n }"} {"repo":"axum","file":"examples/hello-world/src/main.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // build our application with a route\n let app = Router::new().route(\"/\", get(handler));\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/hello-world/src/main.rs","line":22,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Html<&'static str> {\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/http-proxy/src/main.rs","line":36,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=trace,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let router_svc = Router::new().route(\"/\", get(|| async { \"Hello, World!\" }));\n\n let tower_service = tower::service_fn(move |req: Request<_>| {\n let router_svc = router_svc.clone();\n let req = req.map(Body::new);\n async move {\n if req.method() == Method::CONNECT {\n proxy(req).await\n } else {\n router_svc.oneshot(req).await.map_err(|err| match err {})\n }\n }\n });\n\n let hyper_service = hyper::service::service_fn(move |request: Request| {\n tower_service.clone().call(request)\n });\n\n let addr = SocketAddr::from(([127, 0, 0, 1], 3000));\n tracing::debug!(\"listening on {}\", addr);\n\n let listener = TcpListener::bind(addr).await.unwrap();\n loop {\n let (stream, _) = listener.accept().await.unwrap();\n let io = TokioIo::new"} {"repo":"axum","file":"examples/http-proxy/src/main.rs","line":86,"symbol":"proxy","kind":"function","lang":"rust","code":"async fn proxy(req: Request) -> Result {\n tracing::trace!(?req);\n\n if let Some(host_addr) = req.uri().authority().map(|auth| auth.to_string()) {\n tokio::task::spawn(async move {\n match hyper::upgrade::on(req).await {\n Ok(upgraded) => {\n if let Err(e) = tunnel(upgraded, host_addr).await {\n tracing::warn!(\"server io error: {}\", e);\n };\n }\n Err(e) => tracing::warn!(\"upgrade error: {}\", e),\n }\n });\n\n Ok(Response::new(Body::empty()))\n } else {\n tracing::warn!(\"CONNECT host is not socket addr: {:?}\", req.uri());\n Ok((\n StatusCode::BAD_REQUEST,\n \"CONNECT must be to a socket address\",\n )\n .into_response())\n }\n}"} {"repo":"axum","file":"examples/http-proxy/src/main.rs","line":112,"symbol":"tunnel","kind":"function","lang":"rust","code":"async fn tunnel(upgraded: Upgraded, addr: String) -> std::io::Result<()> {\n let mut server = TcpStream::connect(addr).await?;\n let mut upgraded = TokioIo::new(upgraded);\n\n let (from_client, from_server) =\n tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?;\n\n tracing::debug!(\n \"client wrote {} bytes and received {} bytes\",\n from_client,\n from_server\n );\n\n Ok(())\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":59,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let app = Router::new()\n .route(\"/protected\", get(protected))\n .route(\"/authorize\", post(authorize));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":79,"symbol":"protected","kind":"function","lang":"rust","code":"async fn protected(claims: Claims) -> Result {\n // Send the protected data to the user\n Ok(format!(\n \"Welcome to the protected area :)\\nYour data:\\n{claims}\",\n ))\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":86,"symbol":"authorize","kind":"function","lang":"rust","code":"async fn authorize(Json(payload): Json) -> Result, AuthError> {\n // Check if the user sent the credentials\n if payload.client_id.is_empty() || payload.client_secret.is_empty() {\n return Err(AuthError::MissingCredentials);\n }\n // Here you can check the user credentials from a database\n if payload.client_id != \"foo\" || payload.client_secret != \"bar\" {\n return Err(AuthError::WrongCredentials);\n }\n let claims = Claims {\n sub: \"b@b.com\".to_owned(),\n company: \"ACME\".to_owned(),\n // Mandatory expiry time as UTC timestamp\n exp: 2000000000, // May 2033\n };\n // Create the authorization token\n let token = encode(&Header::default(), &claims, &KEYS.encoding)\n .map_err(|_| AuthError::TokenCreation)?;\n\n // Send the authorized token\n Ok(Json(AuthBody::new(token)))\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":110,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"Email: {}\\nCompany: {}\", self.sub, self.company)\n }"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":116,"symbol":"new","kind":"function","lang":"rust","code":"fn new(access_token: String) -> Self {\n Self {\n access_token,\n token_type: \"Bearer\".to_string(),\n }\n }"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":130,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n // Extract the token from the authorization header\n let TypedHeader(Authorization(bearer)) = parts\n .extract::>>()\n .await\n .map_err(|_| AuthError::InvalidToken)?;\n // Decode the user data\n let token_data = decode::(bearer.token(), &KEYS.decoding, &Validation::default())\n .map_err(|_| AuthError::InvalidToken)?;\n\n Ok(token_data.claims)\n }"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":145,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n let (status, error_message) = match self {\n AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, \"Wrong credentials\"),\n AuthError::MissingCredentials => (StatusCode::BAD_REQUEST, \"Missing credentials\"),\n AuthError::TokenCreation => (StatusCode::INTERNAL_SERVER_ERROR, \"Token creation error\"),\n AuthError::InvalidToken => (StatusCode::BAD_REQUEST, \"Invalid token\"),\n };\n let body = Json(json!({\n \"error\": error_message,\n }));\n (status, body).into_response()\n }"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":159,"symbol":"Keys","kind":"type","lang":"rust","code":"struct Keys {\n encoding: EncodingKey,\n decoding: DecodingKey,\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":165,"symbol":"new","kind":"function","lang":"rust","code":"fn new(secret: &[u8]) -> Self {\n Self {\n encoding: EncodingKey::from_secret(secret),\n decoding: DecodingKey::from_secret(secret),\n }\n }"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":174,"symbol":"Claims","kind":"type","lang":"rust","code":"struct Claims {\n sub: String,\n company: String,\n exp: usize,\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":181,"symbol":"AuthBody","kind":"type","lang":"rust","code":"struct AuthBody {\n access_token: String,\n token_type: String,\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":187,"symbol":"AuthPayload","kind":"type","lang":"rust","code":"struct AuthPayload {\n client_id: String,\n client_secret: String,\n}"} {"repo":"axum","file":"examples/jwt/src/main.rs","line":193,"symbol":"AuthError","kind":"type","lang":"rust","code":"enum AuthError {\n WrongCredentials,\n MissingCredentials,\n TokenCreation,\n InvalidToken,\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":33,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let shared_state = SharedState::default();\n\n // Build our application by composing routes\n let app = Router::new()\n .route(\n \"/{key}\",\n // Add compression to `kv_get`\n get(kv_get.layer(CompressionLayer::new()))\n // But don't compress `kv_set`\n .post_service(\n kv_set\n .layer((\n DefaultBodyLimit::disable(),\n RequestBodyLimitLayer::new(1024 * 5_000 /* ~5mb */),\n ))\n .with_state(Arc::clone(&shared_state)),\n ),\n )\n .route(\"/keys\", get(list_keys))\n // Nest our admin routes under `/admin`\n .nest(\"/admin\", admin_routes())\n // Add middleware to all routes\n .layer(\n ServiceBuilder"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":87,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n db: HashMap,\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":91,"symbol":"kv_get","kind":"function","lang":"rust","code":"async fn kv_get(\n Path(key): Path,\n State(state): State,\n) -> Result {\n let db = &state.read().unwrap().db;\n\n if let Some(value) = db.get(&key) {\n Ok(value.clone())\n } else {\n Err(StatusCode::NOT_FOUND)\n }\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":104,"symbol":"kv_set","kind":"function","lang":"rust","code":"async fn kv_set(Path(key): Path, State(state): State, bytes: Bytes) {\n state.write().unwrap().db.insert(key, bytes);\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":108,"symbol":"list_keys","kind":"function","lang":"rust","code":"async fn list_keys(State(state): State) -> String {\n let db = &state.read().unwrap().db;\n\n db.keys()\n .map(|key| key.to_string())\n .collect::>()\n .join(\"\\n\")\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":118,"symbol":"admin_routes","kind":"function","lang":"rust","code":"fn admin_routes() -> Router {\n async fn delete_all_keys(State(state): State) {\n state.write().unwrap().db.clear();\n }\n\n async fn remove_key(Path(key): Path, State(state): State) {\n state.write().unwrap().db.remove(&key);\n }\n\n #[allow(deprecated)] // FIXME\n Router::new()\n .route(\"/keys\", delete(delete_all_keys))\n .route(\"/key/{key}\", delete(remove_key))\n // Require bearer auth for all admin routes\n .layer(ValidateRequestHeaderLayer::bearer(\"secret-token\"))\n}"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":119,"symbol":"delete_all_keys","kind":"function","lang":"rust","code":"async fn delete_all_keys(State(state): State) {\n state.write().unwrap().db.clear();\n }"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":123,"symbol":"remove_key","kind":"function","lang":"rust","code":"async fn remove_key(Path(key): Path, State(state): State) {\n state.write().unwrap().db.remove(&key);\n }"} {"repo":"axum","file":"examples/key-value-store/src/main.rs","line":135,"symbol":"handle_error","kind":"function","lang":"rust","code":"async fn handle_error(error: BoxError) -> impl IntoResponse {\n if error.is::() {\n return (StatusCode::REQUEST_TIMEOUT, Cow::from(\"request timed out\"));\n }\n\n if error.is::() {\n return (\n StatusCode::SERVICE_UNAVAILABLE,\n Cow::from(\"service is overloaded, try again later\"),\n );\n }\n\n (\n StatusCode::INTERNAL_SERVER_ERROR,\n Cow::from(format!(\"Unhandled internal error: {error}\")),\n )\n}"} {"repo":"axum","file":"examples/low-level-native-tls/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/low-level-native-tls/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/low-level-native-tls/src/main.rs","line":21,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"example_low_level_rustls=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let tls_acceptor = native_tls_acceptor(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n );\n\n let tls_acceptor = TlsAcceptor::from(tls_acceptor);\n let bind = \"[::1]:3000\";\n let tcp_listener = TcpListener::bind(bind).await.unwrap();\n info!(\"HTTPS server listening on {bind}. To contact curl -k https://localhost:3000\");\n let app = Router::new().route(\"/\", get(handler));\n\n loop {\n let tower_service = app.clone();\n let tls_acceptor = tls_acceptor.clone();\n\n // Wait for new tcp connection\n let (cnx, addr) = tcp_listener.accept().await.unwrap();\n\n tokio::spawn(async move {\n // Wait for tls handshake to happen\n let Ok(stream) = tls_accepto"} {"repo":"axum","file":"examples/low-level-native-tls/src/main.rs","line":85,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/low-level-native-tls/src/main.rs","line":89,"symbol":"native_tls_acceptor","kind":"function","lang":"rust","code":"fn native_tls_acceptor(key_file: PathBuf, cert_file: PathBuf) -> NativeTlsAcceptor {\n let key_pem = std::fs::read_to_string(&key_file).unwrap();\n let cert_pem = std::fs::read_to_string(&cert_file).unwrap();\n\n let id = Identity::from_pkcs8(cert_pem.as_bytes(), key_pem.as_bytes()).unwrap();\n NativeTlsAcceptor::builder(id)\n // let's be modern\n .min_protocol_version(Some(Protocol::Tlsv12))\n .build()\n .unwrap()\n}"} {"repo":"axum","file":"examples/low-level-openssl/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/low-level-openssl/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/low-level-openssl/src/main.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let mut tls_builder = SslAcceptor::mozilla_modern_v5(SslMethod::tls()).unwrap();\n\n tls_builder\n .set_certificate_file(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n SslFiletype::PEM,\n )\n .unwrap();\n\n tls_builder\n .set_private_key_file(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n SslFiletype::PEM,\n )\n .unwrap();\n\n tls_builder.check_private_key().unwrap();\n\n let tls_acceptor = tls_builder.build();\n\n let bind = \"[::1]:3000\";\n let tcp_listener = TcpListener::bind(bind).await.unwrap();\n info!(\"HTTPS server listening on {bind}. To contact curl -k https://localhost:3000\");\n let app = Router::new().route(\"/\", get(handler));\n\n loo"} {"repo":"axum","file":"examples/low-level-openssl/src/main.rs","line":101,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/low-level-rustls/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/low-level-rustls/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/low-level-rustls/src/main.rs","line":25,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let rustls_config = rustls_server_config(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n );\n\n let tls_acceptor = TlsAcceptor::from(rustls_config);\n let bind = \"[::1]:3000\";\n let tcp_listener = TcpListener::bind(bind).await.unwrap();\n info!(\"HTTPS server listening on {bind}. To contact curl -k https://localhost:3000\");\n let app = Router::new().route(\"/\", get(handler));\n\n loop {\n let tower_service = app.clone();\n let tls_acceptor = tls_acceptor.clone();\n\n // Wait for new tcp connection\n let (cnx, addr) = tcp_listener.accept().await.unwrap();\n\n tokio::spawn(async move {\n // Wait for tls handshake to happen\n let Ok(strea"} {"repo":"axum","file":"examples/low-level-rustls/src/main.rs","line":89,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/low-level-rustls/src/main.rs","line":93,"symbol":"rustls_server_config","kind":"function","lang":"rust","code":"fn rustls_server_config(key: impl AsRef, cert: impl AsRef) -> Arc {\n let key = PrivateKeyDer::from_pem_file(key).unwrap();\n\n let certs = CertificateDer::pem_file_iter(cert)\n .unwrap()\n .map(|cert| cert.unwrap())\n .collect();\n\n let mut config = ServerConfig::builder()\n .with_no_client_auth()\n .with_single_cert(certs, key)\n .expect(\"bad certificate/key\");\n\n config.alpn_protocols = vec![b\"h2\".to_vec(), b\"http/1.1\".to_vec()];\n\n Arc::new(config)\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":23,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // connecting to mongodb\n let db_connection_str = std::env::var(\"DATABASE_URL\").unwrap_or_else(|_| {\n \"mongodb://admin:password@127.0.0.1:27017/?authSource=admin\".to_string()\n });\n let client = Client::with_uri_str(db_connection_str).await.unwrap();\n\n // pinging the database\n client\n .database(\"axum-mongo\")\n .run_command(doc! { \"ping\": 1 })\n .await\n .unwrap();\n println!(\"Pinged your database. Successfully connected to MongoDB!\");\n\n // logging middleware\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"Listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app(client)).await;\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":57,"symbol":"app","kind":"function","lang":"rust","doc":"defining routes and state","code":"fn app(client: Client) -> Router {\n let collection: Collection = client.database(\"axum-mongo\").collection(\"members\");\n\n Router::new()\n .route(\"/create\", post(create_member))\n .route(\"/read/{id}\", get(read_member))\n .route(\"/update\", put(update_member))\n .route(\"/delete/{id}\", delete(delete_member))\n .layer(TraceLayer::new_for_http())\n .with_state(collection)\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":70,"symbol":"create_member","kind":"function","lang":"rust","doc":"handler to create a new member","code":"async fn create_member(\n State(db): State>,\n Json(input): Json,\n) -> Result, (StatusCode, String)> {\n let result = db.insert_one(input).await.map_err(internal_error)?;\n\n Ok(Json(result))\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":80,"symbol":"read_member","kind":"function","lang":"rust","doc":"handler to read an existing member","code":"async fn read_member(\n State(db): State>,\n Path(id): Path,\n) -> Result>, (StatusCode, String)> {\n let result = db\n .find_one(doc! { \"_id\": id })\n .await\n .map_err(internal_error)?;\n\n Ok(Json(result))\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":93,"symbol":"update_member","kind":"function","lang":"rust","doc":"handler to update an existing member","code":"async fn update_member(\n State(db): State>,\n Json(input): Json,\n) -> Result, (StatusCode, String)> {\n let result = db\n .replace_one(doc! { \"_id\": input.id }, input)\n .await\n .map_err(internal_error)?;\n\n Ok(Json(result))\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":106,"symbol":"delete_member","kind":"function","lang":"rust","doc":"handler to delete an existing member","code":"async fn delete_member(\n State(db): State>,\n Path(id): Path,\n) -> Result, (StatusCode, String)> {\n let result = db\n .delete_one(doc! { \"_id\": id })\n .await\n .map_err(internal_error)?;\n\n Ok(Json(result))\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":118,"symbol":"internal_error","kind":"function","lang":"rust","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/mongodb/src/main.rs","line":127,"symbol":"Member","kind":"type","lang":"rust","doc":"defining Member type","code":"struct Member {\n #[serde(rename = \"_id\")]\n id: u32,\n name: String,\n active: bool,\n}"} {"repo":"axum","file":"examples/multipart-form/src/main.rs","line":17,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with some routes\n let app = Router::new()\n .route(\"/\", get(show_form).post(accept_form))\n .layer(DefaultBodyLimit::disable())\n .layer(RequestBodyLimitLayer::new(\n 250 * 1024 * 1024, /* 250mb */\n ))\n .layer(tower_http::trace::TraceLayer::new_for_http());\n\n // run it with hyper\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/multipart-form/src/main.rs","line":44,"symbol":"show_form","kind":"function","lang":"rust","code":"async fn show_form() -> Html<&'static str> {\n Html(\n r#\"\n \n \n \n \n
\n \n\n \n
\n \n \n \"#,\n )\n}"} {"repo":"axum","file":"examples/multipart-form/src/main.rs","line":65,"symbol":"accept_form","kind":"function","lang":"rust","code":"async fn accept_form(mut multipart: Multipart) {\n while let Some(field) = multipart.next_field().await.unwrap() {\n let name = field.name().unwrap().to_string();\n let file_name = field.file_name().unwrap().to_string();\n let content_type = field.content_type().unwrap().to_string();\n let data = field.bytes().await.unwrap();\n\n println!(\n \"Length of `{name}` (`{file_name}`: `{content_type}`) is {} bytes\",\n data.len()\n );\n }\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":42,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // `MemoryStore` is just used as an example. Don't use this in production.\n let store = MemoryStore::new();\n let oauth_client = oauth_client().unwrap();\n let app_state = AppState {\n store,\n oauth_client,\n };\n\n let app = Router::new()\n .route(\"/\", get(index))\n .route(\"/auth/discord\", get(discord_auth))\n .route(\"/auth/authorized\", get(login_authorized))\n .route(\"/protected\", get(protected))\n .route(\"/logout\", get(logout))\n .with_state(app_state);\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .context(\"failed to bind TcpListener\")\n .unwrap();\n\n tracing::debug!(\n \"listening on {}\",\n listener\n .local_addr()\n .context(\"failed to return local address\")\n .unwrap()\n );\n\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":84,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n store: MemoryStore,\n oauth_client: BasicClient,\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":90,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(state: &AppState) -> Self {\n state.store.clone()\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":96,"symbol":"from_ref","kind":"function","lang":"rust","code":"fn from_ref(state: &AppState) -> Self {\n state.oauth_client.clone()\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":101,"symbol":"oauth_client","kind":"function","lang":"rust","code":"fn oauth_client() -> Result {\n // Environment variables (* = required):\n // *\"CLIENT_ID\" \"REPLACE_ME\";\n // *\"CLIENT_SECRET\" \"REPLACE_ME\";\n // \"REDIRECT_URL\" \"http://127.0.0.1:3000/auth/authorized\";\n // \"AUTH_URL\" \"https://discord.com/api/oauth2/authorize?response_type=code\";\n // \"TOKEN_URL\" \"https://discord.com/api/oauth2/token\";\n\n let client_id = env::var(\"CLIENT_ID\").context(\"Missing CLIENT_ID!\")?;\n let client_secret = env::var(\"CLIENT_SECRET\").context(\"Missing CLIENT_SECRET!\")?;\n let redirect_url = env::var(\"REDIRECT_URL\")\n .unwrap_or_else(|_| \"http://127.0.0.1:3000/auth/authorized\".to_string());\n\n let auth_url = env::var(\"AUTH_URL\").unwrap_or_else(|_| {\n \"https://discord.com/api/oauth2/authorize?response_type=code\".to_string()\n });\n\n let token_url = env::var(\"TOKEN_URL\")\n .unwrap_or_else(|_| \"https://discord.com/api/oauth2/token\".to_string());\n\n Ok(oauth2::basic::BasicClient::new(ClientId::new(client_id))\n .set_client_secret(ClientSecret::new(client_secret))\n .set_auth_uri(\n AuthUrl::new(auth_url).context(\"failed to create new authorization server URL\")?,"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":135,"symbol":"User","kind":"type","lang":"rust","doc":"The user data we'll get back from Discord. https://discord.com/developers/docs/resources/user#user-object-user-structure","code":"struct User {\n id: String,\n avatar: Option,\n username: String,\n discriminator: String,\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":143,"symbol":"index","kind":"function","lang":"rust","doc":"Session is optional","code":"async fn index(user: Option) -> impl IntoResponse {\n match user {\n Some(u) => format!(\n \"Hey {}! You're logged in!\\nYou may now access `/protected`.\\nLog out with `/logout`.\",\n u.username\n ),\n None => \"You're not logged in.\\nVisit `/auth/discord` to do so.\".to_string(),\n }\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":153,"symbol":"discord_auth","kind":"function","lang":"rust","code":"async fn discord_auth(\n State(client): State,\n State(store): State,\n) -> Result {\n let (auth_url, csrf_token) = client\n .authorize_url(CsrfToken::new_random)\n .add_scope(Scope::new(\"identify\".to_string()))\n .url();\n\n // Create session to store csrf_token\n let mut session = Session::new();\n session\n .insert(CSRF_TOKEN, &csrf_token)\n .context(\"failed in inserting CSRF token into session\")?;\n\n // Store the session in MemoryStore and retrieve the session cookie\n let cookie = store\n .store_session(session)\n .await\n .context(\"failed to store CSRF token session\")?\n .context(\"unexpected error retrieving CSRF cookie value\")?;\n\n // Attach the session cookie to the response header\n let cookie = format!(\"{COOKIE_NAME}={cookie}; SameSite=Lax; HttpOnly; Secure; Path=/\");\n let mut headers = HeaderMap::new();\n headers.insert(\n SET_COOKIE,\n cookie.parse().context(\"failed to parse cookie\")?,\n );\n\n Ok((headers, Redirect::to(auth_url.as_ref())))\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":187,"symbol":"protected","kind":"function","lang":"rust","doc":"Valid user session required. If there is none, redirect to the auth page","code":"async fn protected(user: User) -> impl IntoResponse {\n format!(\"Welcome to the protected area :)\\nHere's your info:\\n{user:?}\")\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":191,"symbol":"logout","kind":"function","lang":"rust","code":"async fn logout(\n State(store): State,\n TypedHeader(cookies): TypedHeader,\n) -> Result {\n let cookie = cookies\n .get(COOKIE_NAME)\n .context(\"unexpected error getting cookie name\")?;\n\n let session = match store\n .load_session(cookie.to_string())\n .await\n .context(\"failed to load session\")?\n {\n Some(s) => s,\n // No session active, just redirect\n None => return Ok(Redirect::to(\"/\")),\n };\n\n store\n .destroy_session(session)\n .await\n .context(\"failed to destroy session\")?;\n\n Ok(Redirect::to(\"/\"))\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":219,"symbol":"AuthRequest","kind":"type","lang":"rust","code":"struct AuthRequest {\n code: String,\n state: String,\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":224,"symbol":"csrf_token_validation_workflow","kind":"function","lang":"rust","code":"async fn csrf_token_validation_workflow(\n auth_request: &AuthRequest,\n cookies: &headers::Cookie,\n store: &MemoryStore,\n) -> Result<(), AppError> {\n // Extract the cookie from the request\n let cookie = cookies\n .get(COOKIE_NAME)\n .context(\"unexpected error getting cookie name\")?\n .to_string();\n\n // Load the session\n let session = match store\n .load_session(cookie)\n .await\n .context(\"failed to load session\")?\n {\n Some(session) => session,\n None => return Err(anyhow!(\"Session not found\").into()),\n };\n\n // Extract the CSRF token from the session\n let stored_csrf_token = session\n .get::(CSRF_TOKEN)\n .context(\"CSRF token not found in session\")?\n .to_owned();\n\n // Cleanup the CSRF token session\n store\n .destroy_session(session)\n .await\n .context(\"Failed to destroy old session\")?;\n\n // Validate CSRF token is the same as the one in the auth request\n if *stored_csrf_token.secret() != auth_request.state {\n return Err(anyhow!(\"CSRF token mismatch\").into());\n }\n\n Ok(())\n}"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":265,"symbol":"login_authorized","kind":"function","lang":"rust","code":"async fn login_authorized(\n Query(query): Query,\n State(store): State,\n State(oauth_client): State,\n TypedHeader(cookies): TypedHeader,\n) -> Result {\n csrf_token_validation_workflow(&query, &cookies, &store).await?;\n\n let client = reqwest::Client::new();\n\n // Get an auth token\n let token = oauth_client\n .exchange_code(AuthorizationCode::new(query.code.clone()))\n .request_async(&client)\n .await\n .context(\"failed in sending request to authorization server\")?;\n\n // Fetch user data from discord\n let user_data: User = client\n // https://discord.com/developers/docs/resources/user#get-current-user\n .get(\"https://discordapp.com/api/users/@me\")\n .bearer_auth(token.access_token().secret())\n .send()\n .await\n .context(\"failed in sending request to target Url\")?\n .json::()\n .await\n .context(\"failed to deserialize response as JSON\")?;\n\n // Create a new session filled with user data\n let mut session = Session::new();\n session\n .insert(\"user\", &user_data)\n .context(\""} {"repo":"axum","file":"examples/oauth/src/main.rs","line":320,"symbol":"AuthRedirect","kind":"type","lang":"rust","code":"struct AuthRedirect;"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":323,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n Redirect::temporary(\"/auth/discord\").into_response()\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":336,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, state: &S) -> Result {\n let store = MemoryStore::from_ref(state);\n\n let cookies = parts\n .extract::>()\n .await\n .map_err(|e| match *e.name() {\n header::COOKIE => match e.reason() {\n TypedHeaderRejectionReason::Missing => AuthRedirect,\n _ => panic!(\"unexpected error getting Cookie header(s): {e}\"),\n },\n _ => panic!(\"unexpected error getting cookies: {e}\"),\n })?;\n let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;\n\n let session = store\n .load_session(session_cookie.to_string())\n .await\n .unwrap()\n .ok_or(AuthRedirect)?;\n\n let user = session.get::(\"user\").ok_or(AuthRedirect)?;\n\n Ok(user)\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":370,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(\n parts: &mut Parts,\n state: &S,\n ) -> Result, Self::Rejection> {\n match >::from_request_parts(parts, state).await {\n Ok(res) => Ok(Some(res)),\n Err(AuthRedirect) => Ok(None),\n }\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":384,"symbol":"AppError","kind":"type","lang":"rust","doc":"Use anyhow, define error and enable '?' For a simplified example of using anyhow in axum check /examples/anyhow-error-response","code":"struct AppError(anyhow::Error);"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":388,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n tracing::error!(\"Application error: {:#}\", self.0);\n\n (StatusCode::INTERNAL_SERVER_ERROR, \"Something went wrong\").into_response()\n }"} {"repo":"axum","file":"examples/oauth/src/main.rs","line":401,"symbol":"from","kind":"function","lang":"rust","code":"fn from(err: E) -> Self {\n Self(err.into())\n }"} {"repo":"axum","file":"examples/parse-body-based-on-content-type/src/main.rs","line":20,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let app = Router::new().route(\"/\", post(handler));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/parse-body-based-on-content-type/src/main.rs","line":40,"symbol":"Payload","kind":"type","lang":"rust","code":"struct Payload {\n foo: String,\n}"} {"repo":"axum","file":"examples/parse-body-based-on-content-type/src/main.rs","line":44,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(JsonOrForm(payload): JsonOrForm) {\n dbg!(payload);\n}"} {"repo":"axum","file":"examples/parse-body-based-on-content-type/src/main.rs","line":48,"symbol":"JsonOrForm","kind":"type","lang":"rust","code":"struct JsonOrForm(T);"} {"repo":"axum","file":"examples/parse-body-based-on-content-type/src/main.rs","line":59,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, _state: &S) -> Result {\n let content_type_header = req.headers().get(CONTENT_TYPE);\n let content_type = content_type_header.and_then(|value| value.to_str().ok());\n\n if let Some(content_type) = content_type {\n if content_type.starts_with(\"application/json\") {\n let Json(payload) = req.extract().await.map_err(IntoResponse::into_response)?;\n return Ok(Self(payload));\n }\n\n if content_type.starts_with(\"application/x-www-form-urlencoded\") {\n let Form(payload) = req.extract().await.map_err(IntoResponse::into_response)?;\n return Ok(Self(payload));\n }\n }\n\n Err(StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response())\n }"} {"repo":"axum","file":"examples/print-request-response/src/main.rs","line":20,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let app = Router::new()\n .route(\"/\", post(|| async move { \"Hello from `POST /`\" }))\n .layer(middleware::from_fn(print_request_response));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/print-request-response/src/main.rs","line":41,"symbol":"print_request_response","kind":"function","lang":"rust","code":"async fn print_request_response(\n req: Request,\n next: Next,\n) -> Result {\n let (parts, body) = req.into_parts();\n let bytes = buffer_and_print(\"request\", body).await?;\n let req = Request::from_parts(parts, Body::from(bytes));\n\n let res = next.run(req).await;\n\n let (parts, body) = res.into_parts();\n let bytes = buffer_and_print(\"response\", body).await?;\n let res = Response::from_parts(parts, Body::from(bytes));\n\n Ok(res)\n}"} {"repo":"axum","file":"examples/print-request-response/src/main.rs","line":58,"symbol":"buffer_and_print","kind":"function","lang":"rust","code":"async fn buffer_and_print(direction: &str, body: B) -> Result\nwhere\n B: axum::body::HttpBody,\n B::Error: std::fmt::Display,\n{\n let bytes = match body.collect().await {\n Ok(collected) => collected.to_bytes(),\n Err(err) => {\n return Err((\n StatusCode::BAD_REQUEST,\n format!(\"failed to read {direction} body: {err}\"),\n ));\n }\n };\n\n if let Ok(body) = std::str::from_utf8(&bytes) {\n tracing::debug!(\"{direction} body = {body:?}\");\n }\n\n Ok(bytes)\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":24,"symbol":"metrics_app","kind":"function","lang":"rust","code":"fn metrics_app() -> Router {\n let recorder_handle = setup_metrics_recorder();\n Router::new().route(\"/metrics\", get(move || ready(recorder_handle.render())))\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":29,"symbol":"main_app","kind":"function","lang":"rust","code":"fn main_app() -> Router {\n Router::new()\n .route(\"/fast\", get(|| async {}))\n .route(\n \"/slow\",\n get(|| async {\n tokio::time::sleep(Duration::from_secs(1)).await;\n }),\n )\n .route_layer(middleware::from_fn(track_metrics))\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":41,"symbol":"start_main_server","kind":"function","lang":"rust","code":"async fn start_main_server() {\n let app = main_app();\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":51,"symbol":"start_metrics_server","kind":"function","lang":"rust","code":"async fn start_metrics_server() {\n let app = metrics_app();\n\n // NOTE: expose metrics endpoint on a different port\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3001\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":63,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // The `/metrics` endpoint should not be publicly available. If behind a reverse proxy, this\n // can be achieved by rejecting requests to `/metrics`. In this example, a second server is\n // started on another port to expose `/metrics`.\n let (_main_server, _metrics_server) = tokio::join!(start_main_server(), start_metrics_server());\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":79,"symbol":"setup_metrics_recorder","kind":"function","lang":"rust","code":"fn setup_metrics_recorder() -> PrometheusHandle {\n const EXPONENTIAL_SECONDS: &[f64] = &[\n 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,\n ];\n\n let recorder_handle = PrometheusBuilder::new()\n .set_buckets_for_metric(\n Matcher::Full(\"http_requests_duration_seconds\".to_string()),\n EXPONENTIAL_SECONDS,\n )\n .unwrap()\n .install_recorder()\n .unwrap();\n\n let upkeep_handle = recorder_handle.clone();\n tokio::spawn(async move {\n loop {\n tokio::time::sleep(Duration::from_secs(5)).await;\n upkeep_handle.run_upkeep();\n }\n });\n\n recorder_handle\n}"} {"repo":"axum","file":"examples/prometheus-metrics/src/main.rs","line":104,"symbol":"track_metrics","kind":"function","lang":"rust","code":"async fn track_metrics(req: Request, next: Next) -> impl IntoResponse {\n let start = Instant::now();\n let path = if let Some(matched_path) = req.extensions().get::() {\n matched_path.as_str().to_owned()\n } else {\n req.uri().path().to_owned()\n };\n let method = req.method().clone();\n\n let response = next.run(req).await;\n\n let latency = start.elapsed().as_secs_f64();\n let status = response.status().as_u16().to_string();\n\n let labels = [\n (\"method\", method.to_string()),\n (\"path\", path),\n (\"status\", status),\n ];\n\n metrics::counter!(\"http_requests_total\", &labels).increment(1);\n metrics::histogram!(\"http_requests_duration_seconds\", &labels).record(latency);\n\n response\n}"} {"repo":"axum","file":"examples/readme/src/main.rs","line":16,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // initialize tracing\n tracing_subscriber::fmt::init();\n\n // build our application with a route\n let app = Router::new()\n // `GET /` goes to `root`\n .route(\"/\", get(root))\n // `POST /users` goes to `create_user`\n .route(\"/users\", post(create_user));\n\n // run our app with hyper\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/readme/src/main.rs","line":36,"symbol":"root","kind":"function","lang":"rust","doc":"basic handler that responds with a static string","code":"async fn root() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/readme/src/main.rs","line":40,"symbol":"create_user","kind":"function","lang":"rust","code":"async fn create_user(\n // this argument tells axum to parse the request body\n // as JSON into a `CreateUser` type\n Json(payload): Json,\n) -> impl IntoResponse {\n // insert your application logic here\n let user = User {\n id: 1337,\n username: payload.username,\n };\n\n // this will be converted into a JSON response\n // with a status code of `201 Created`\n (StatusCode::CREATED, Json(user))\n}"} {"repo":"axum","file":"examples/readme/src/main.rs","line":58,"symbol":"CreateUser","kind":"type","lang":"rust","doc":"the input to our `create_user` handler","code":"struct CreateUser {\n username: String,\n}"} {"repo":"axum","file":"examples/readme/src/main.rs","line":64,"symbol":"User","kind":"type","lang":"rust","doc":"the output to our `create_user` handler","code":"struct User {\n id: u64,\n username: String,\n}"} {"repo":"axum","file":"examples/request-id/src/main.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n // axum logs rejections from built-in extractors with the `axum::rejection`\n // target, at `TRACE` level. `axum::rejection=trace` enables showing those events\n format!(\n \"{}=debug,tower_http=debug,axum::rejection=trace\",\n env!(\"CARGO_CRATE_NAME\")\n )\n .into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let middleware = ServiceBuilder::new()\n .set_x_request_id(MakeRequestUuid)\n .layer(\n TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {\n // Log the request id as generated.\n let request_id = request.extensions().get::().unwrap();\n\n match request_id.header_value().to_str() {\n Ok(request_id) => info_span!(\"http_request\", request_id),\n Err(_) => info_span!(\"http_request\", request_id = ?request_id),\n }\n }),\n "} {"repo":"axum","file":"examples/request-id/src/main.rs","line":61,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Html<&'static str> {\n info!(\"Hello world!\");\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/reqwest-response/src/main.rs","line":23,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let client = Client::new();\n\n let app = Router::new()\n .route(\"/\", get(stream_reqwest_response))\n .route(\"/stream\", get(stream_some_data))\n // Add some logging so we can see the streams going through\n .layer(TraceLayer::new_for_http().on_body_chunk(\n |chunk: &Bytes, _latency: Duration, _span: &Span| {\n tracing::debug!(\"streaming {} bytes\", chunk.len());\n },\n ))\n .with_state(client);\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/reqwest-response/src/main.rs","line":53,"symbol":"stream_reqwest_response","kind":"function","lang":"rust","code":"async fn stream_reqwest_response(State(client): State) -> Response {\n let reqwest_response = match client.get(\"http://127.0.0.1:3000/stream\").send().await {\n Ok(res) => res,\n Err(err) => {\n tracing::error!(%err, \"request failed\");\n return (StatusCode::BAD_REQUEST, Body::empty()).into_response();\n }\n };\n\n let mut response_builder = Response::builder().status(reqwest_response.status());\n *response_builder.headers_mut().unwrap() = reqwest_response.headers().clone();\n response_builder\n .body(Body::from_stream(reqwest_response.bytes_stream()))\n // This unwrap is fine because the body is empty here\n .unwrap()\n}"} {"repo":"axum","file":"examples/reqwest-response/src/main.rs","line":70,"symbol":"stream_some_data","kind":"function","lang":"rust","code":"async fn stream_some_data() -> Body {\n let stream = tokio_stream::iter(0..5)\n .throttle(Duration::from_secs(1))\n .map(|n| n.to_string())\n .map(Ok::<_, Infallible>);\n Body::from_stream(stream)\n}"} {"repo":"axum","file":"examples/reverse-proxy/src/main.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tokio::spawn(server());\n\n let client: Client =\n hyper_util::client::legacy::Client::<(), ()>::builder(TokioExecutor::new())\n .build(HttpConnector::new());\n\n let app = Router::new().route(\"/\", get(handler)).with_state(client);\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:4000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/reverse-proxy/src/main.rs","line":40,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(State(client): State, mut req: Request) -> Result {\n let path = req.uri().path();\n let path_query = req\n .uri()\n .path_and_query()\n .map(|v| v.as_str())\n .unwrap_or(path);\n\n let uri = format!(\"http://127.0.0.1:3000{path_query}\");\n\n *req.uri_mut() = Uri::try_from(uri).unwrap();\n\n Ok(client\n .request(req)\n .await\n .map_err(|_| StatusCode::BAD_REQUEST)?\n .into_response())\n}"} {"repo":"axum","file":"examples/reverse-proxy/src/main.rs","line":59,"symbol":"server","kind":"function","lang":"rust","code":"async fn server() {\n let app = Router::new().route(\"/\", get(|| async { \"Hello, world!\" }));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":13,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let app = Router::new()\n .merge(root())\n .merge(get_foo())\n .merge(post_foo());\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":26,"symbol":"root","kind":"function","lang":"rust","code":"fn root() -> Router {\n async fn handler() -> &'static str {\n \"Hello, World!\"\n }\n\n route(\"/\", get(handler))\n}"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":27,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n }"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":34,"symbol":"get_foo","kind":"function","lang":"rust","code":"fn get_foo() -> Router {\n async fn handler() -> &'static str {\n \"Hi from `GET /foo`\"\n }\n\n route(\"/foo\", get(handler))\n}"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":35,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hi from `GET /foo`\"\n }"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":42,"symbol":"post_foo","kind":"function","lang":"rust","code":"fn post_foo() -> Router {\n async fn handler() -> &'static str {\n \"Hi from `POST /foo`\"\n }\n\n route(\"/foo\", post(handler))\n}"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":43,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hi from `POST /foo`\"\n }"} {"repo":"axum","file":"examples/routes-and-handlers-close-together/src/main.rs","line":50,"symbol":"route","kind":"function","lang":"rust","code":"fn route(path: &str, method_router: MethodRouter<()>) -> Router {\n Router::new().route(path, method_router)\n}"} {"repo":"axum","file":"examples/serve-with-hyper/src/main.rs","line":26,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tokio::join!(serve_plain(), serve_with_connect_info());\n}"} {"repo":"axum","file":"examples/serve-with-hyper/src/main.rs","line":30,"symbol":"serve_plain","kind":"function","lang":"rust","code":"async fn serve_plain() {\n // Create a regular axum app.\n let app = Router::new().route(\"/\", get(|| async { \"Hello!\" }));\n\n // Create a `TcpListener` using tokio.\n let listener = TcpListener::bind(\"0.0.0.0:3000\").await.unwrap();\n\n // Continuously accept new connections.\n loop {\n // In this example we discard the remote address. See `fn serve_with_connect_info` for how\n // to expose that.\n let (socket, _remote_addr) = listener.accept().await.unwrap();\n\n // We don't need to call `poll_ready` because `Router` is always ready.\n let tower_service = app.clone();\n\n // Spawn a task to handle the connection. That way we can handle multiple connections\n // concurrently.\n tokio::spawn(async move {\n // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio.\n // `TokioIo` converts between them.\n let socket = TokioIo::new(socket);\n\n // Hyper also has its own `Service` trait and doesn't use tower. We can use\n // `hyper::service::service_fn` to create a hyper `Service` that calls our app through\n // `tower::Service::call`.\n let h"} {"repo":"axum","file":"examples/serve-with-hyper/src/main.rs","line":81,"symbol":"serve_with_connect_info","kind":"function","lang":"rust","doc":"Similar setup to `serve_plain` but captures the remote address and exposes it through the `ConnectInfo` extractor","code":"async fn serve_with_connect_info() {\n let app = Router::new().route(\n \"/\",\n get(\n |ConnectInfo(remote_addr): ConnectInfo| async move {\n format!(\"Hello {remote_addr}\")\n },\n ),\n );\n\n let mut make_service = app.into_make_service_with_connect_info::();\n\n let listener = TcpListener::bind(\"0.0.0.0:3001\").await.unwrap();\n\n loop {\n let (socket, remote_addr) = listener.accept().await.unwrap();\n\n // We don't need to call `poll_ready` because `IntoMakeServiceWithConnectInfo` is always\n // ready.\n let tower_service = unwrap_infallible(make_service.call(remote_addr).await);\n\n tokio::spawn(async move {\n let socket = TokioIo::new(socket);\n\n let hyper_service = hyper::service::service_fn(move |request: Request| {\n tower_service.clone().oneshot(request)\n });\n\n if let Err(err) = server::conn::auto::Builder::new(TokioExecutor::new())\n .serve_connection_with_upgrades(socket, hyper_service)\n .await\n {\n eprintln!(\"failed to serve connection: {err:#}\")"} {"repo":"axum","file":"examples/serve-with-hyper/src/main.rs","line":119,"symbol":"unwrap_infallible","kind":"function","lang":"rust","code":"fn unwrap_infallible(result: Result) -> T {\n match result {\n Ok(value) => value,\n Err(err) => match err {},\n }\n}"} {"repo":"axum","file":"examples/simple-router-wasm/src/main.rs","line":31,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let request: Request = Request::get(\"https://serverless.example/api/\")\n .body(\"Some Body Data\".into())\n .unwrap();\n\n let response: Response = block_on(app(request));\n assert_eq!(200, response.status());\n}"} {"repo":"axum","file":"examples/simple-router-wasm/src/main.rs","line":41,"symbol":"app","kind":"function","lang":"rust","code":"async fn app(request: Request) -> Response {\n let mut router = Router::new().route(\"/api/\", get(index));\n let response = router.call(request).await.unwrap();\n response\n}"} {"repo":"axum","file":"examples/simple-router-wasm/src/main.rs","line":47,"symbol":"index","kind":"function","lang":"rust","code":"async fn index() -> Html<&'static str> {\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":29,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let db_connection_str = std::env::var(\"DATABASE_URL\")\n .unwrap_or_else(|_| \"postgres://postgres:password@localhost\".to_string());\n\n // set up connection pool\n let pool = PgPoolOptions::new()\n .max_connections(5)\n .acquire_timeout(Duration::from_secs(3))\n .connect(&db_connection_str)\n .await\n .expect(\"can't connect to database\");\n\n // build our application with some routes\n let app = Router::new()\n .route(\n \"/\",\n get(using_connection_pool_extractor).post(using_connection_extractor),\n )\n .with_state(pool);\n\n // run it with hyper\n let listener = TcpListener::bind(\"127.0.0.1:3000\").await.unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":64,"symbol":"using_connection_pool_extractor","kind":"function","lang":"rust","doc":"we can extract the connection pool with `State`","code":"async fn using_connection_pool_extractor(\n State(pool): State,\n) -> Result {\n sqlx::query_scalar(\"select 'hello world from pg'\")\n .fetch_one(&pool)\n .await\n .map_err(internal_error)\n}"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":75,"symbol":"DatabaseConnection","kind":"type","lang":"rust","doc":"we can also write a custom extractor that grabs a connection from the pool which setup is appropriate depends on your application","code":"struct DatabaseConnection(sqlx::pool::PoolConnection);"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":84,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result {\n let pool = PgPool::from_ref(state);\n\n let conn = pool.acquire().await.map_err(internal_error)?;\n\n Ok(Self(conn))\n }"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":93,"symbol":"using_connection_extractor","kind":"function","lang":"rust","code":"async fn using_connection_extractor(\n DatabaseConnection(mut conn): DatabaseConnection,\n) -> Result {\n sqlx::query_scalar(\"select 'hello world from pg'\")\n .fetch_one(&mut *conn)\n .await\n .map_err(internal_error)\n}"} {"repo":"axum","file":"examples/sqlx-postgres/src/main.rs","line":104,"symbol":"internal_error","kind":"function","lang":"rust","doc":"Utility function for mapping any error into a `500 Internal Server Error` response.","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/sse/src/main.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application\n let app = app();\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/sse/src/main.rs","line":45,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n let assets_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\")).join(\"assets\");\n let static_files_service = ServeDir::new(assets_dir).append_index_html_on_directories(true);\n // build our application with a route\n Router::new()\n .fallback_service(static_files_service)\n .route(\"/sse\", get(sse_handler))\n .layer(TraceLayer::new_for_http())\n}"} {"repo":"axum","file":"examples/sse/src/main.rs","line":55,"symbol":"sse_handler","kind":"function","lang":"rust","code":"async fn sse_handler(\n TypedHeader(user_agent): TypedHeader,\n) -> Sse>> {\n println!(\"`{}` connected\", user_agent.as_str());\n\n // A `Stream` that repeats an event every second\n //\n // You can also create streams from tokio channels using the wrappers in\n // https://docs.rs/tokio-stream\n let stream = stream::repeat_with(|| Event::default().data(\"hi!\"))\n .map(Ok)\n .throttle(Duration::from_secs(1));\n\n Sse::new(stream).keep_alive(\n axum::response::sse::KeepAlive::new()\n .interval(Duration::from_secs(1))\n .text(\"keep-alive-text\"),\n )\n}"} {"repo":"axum","file":"examples/sse/src/main.rs","line":83,"symbol":"integration_test","kind":"function","lang":"rust","code":"async fn integration_test() {\n // A helper function that spawns our application in the background\n async fn spawn_app(host: impl Into) -> String {\n let host = host.into();\n // Bind to localhost at the port 0, which will let the OS assign an available port to us\n let listener = TcpListener::bind(format!(\"{host}:0\")).await.unwrap();\n // Retrieve the port assigned to us by the OS\n let port = listener.local_addr().unwrap().port();\n tokio::spawn(async {\n axum::serve(listener, app()).await;\n });\n // Returns address (e.g. http://127.0.0.1{random_port})\n format!(\"http://{host}:{port}\")\n }\n let listening_url = spawn_app(\"127.0.0.1\").await;\n\n let mut event_stream = reqwest::Client::new()\n .get(format!(\"{listening_url}/sse\"))\n .header(\"User-Agent\", \"integration_test\")\n .send()\n .await\n .unwrap()\n .bytes_stream()\n .eventsource()\n .take(1);\n\n let mut event_data: Vec = vec![];\n while let Some(event) = event_stream.next().await {\n "} {"repo":"axum","file":"examples/sse/src/main.rs","line":85,"symbol":"spawn_app","kind":"function","lang":"rust","doc":"A helper function that spawns our application in the background","code":"async fn spawn_app(host: impl Into) -> String {\n let host = host.into();\n // Bind to localhost at the port 0, which will let the OS assign an available port to us\n let listener = TcpListener::bind(format!(\"{host}:0\")).await.unwrap();\n // Retrieve the port assigned to us by the OS\n let port = listener.local_addr().unwrap().port();\n tokio::spawn(async {\n axum::serve(listener, app()).await;\n });\n // Returns address (e.g. http://127.0.0.1{random_port})\n format!(\"http://{host}:{port}\")\n }"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":20,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n tokio::join!(\n serve(using_serve_dir(), 3001),\n serve(using_serve_dir_with_assets_fallback(), 3002),\n serve(using_serve_dir_only_from_root_via_fallback(), 3003),\n serve(using_serve_dir_with_handler_as_service(), 3004),\n serve(two_serve_dirs(), 3005),\n serve(calling_serve_dir_from_a_handler(), 3006),\n serve(using_serve_file_from_a_route(), 3307),\n );\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":41,"symbol":"using_serve_dir","kind":"function","lang":"rust","code":"fn using_serve_dir() -> Router {\n // serve the file in the \"assets\" directory under `/assets`\n Router::new().nest_service(\"/assets\", ServeDir::new(\"assets\"))\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":46,"symbol":"using_serve_dir_with_assets_fallback","kind":"function","lang":"rust","code":"fn using_serve_dir_with_assets_fallback() -> Router {\n // `ServeDir` allows setting a fallback if an asset is not found\n // so with this `GET /assets/doesnt-exist.jpg` will return `index.html`\n // rather than a 404.\n // The `fallback_service` ensures that all other paths (the standard\n // SPA pattern) also return `index.html`. We wrap it in `SetStatus` so\n // the response uses 404 instead of 200 -- the path wasn't found, the SPA\n // just handles routing client-side.\n let index_html = SetStatus::new(ServeFile::new(\"assets/index.html\"), StatusCode::NOT_FOUND);\n let serve_dir = ServeDir::new(\"assets\").not_found_service(index_html.clone());\n\n Router::new()\n .route(\"/foo\", get(|| async { \"Hi from /foo\" }))\n .nest_service(\"/assets\", serve_dir)\n .fallback_service(index_html)\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":63,"symbol":"using_serve_dir_only_from_root_via_fallback","kind":"function","lang":"rust","code":"fn using_serve_dir_only_from_root_via_fallback() -> Router {\n // you can also serve the assets directly from the root (not nested under `/assets`)\n // by only setting a `ServeDir` as the fallback\n let serve_dir = ServeDir::new(\"assets\").not_found_service(ServeFile::new(\"assets/index.html\"));\n\n Router::new()\n .route(\"/foo\", get(|| async { \"Hi from /foo\" }))\n .fallback_service(serve_dir)\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":73,"symbol":"using_serve_dir_with_handler_as_service","kind":"function","lang":"rust","code":"fn using_serve_dir_with_handler_as_service() -> Router {\n async fn handle_404() -> (StatusCode, &'static str) {\n (StatusCode::NOT_FOUND, \"Not found\")\n }\n\n // you can convert handler function to service\n let service = handle_404.into_service();\n\n let serve_dir = ServeDir::new(\"assets\").not_found_service(service);\n\n Router::new()\n .route(\"/foo\", get(|| async { \"Hi from /foo\" }))\n .fallback_service(serve_dir)\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":74,"symbol":"handle_404","kind":"function","lang":"rust","code":"async fn handle_404() -> (StatusCode, &'static str) {\n (StatusCode::NOT_FOUND, \"Not found\")\n }"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":88,"symbol":"two_serve_dirs","kind":"function","lang":"rust","code":"fn two_serve_dirs() -> Router {\n // you can also have two `ServeDir`s nested at different paths\n let serve_dir_from_assets = ServeDir::new(\"assets\");\n let serve_dir_from_dist = ServeDir::new(\"dist\");\n\n Router::new()\n .nest_service(\"/assets\", serve_dir_from_assets)\n .nest_service(\"/dist\", serve_dir_from_dist)\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":99,"symbol":"calling_serve_dir_from_a_handler","kind":"function","lang":"rust","code":"fn calling_serve_dir_from_a_handler() -> Router {\n // via `tower::Service::call`, or more conveniently `tower::ServiceExt::oneshot` you can\n // call `ServeDir` yourself from a handler\n Router::new().nest_service(\n \"/foo\",\n get(|request: Request| async {\n let service = ServeDir::new(\"assets\");\n let result = service.oneshot(request).await;\n result\n }),\n )\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":112,"symbol":"using_serve_file_from_a_route","kind":"function","lang":"rust","code":"fn using_serve_file_from_a_route() -> Router {\n Router::new().route_service(\"/foo\", ServeFile::new(\"assets/index.html\"))\n}"} {"repo":"axum","file":"examples/static-file-server/src/main.rs","line":119,"symbol":"serve","kind":"function","lang":"rust","code":"async fn serve(app: Router, port: u16) {\n let addr = SocketAddr::from(([127, 0, 0, 1], port));\n let listener = tokio::net::TcpListener::bind(addr).await.unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app.layer(TraceLayer::new_for_http())).await;\n}"} {"repo":"axum","file":"examples/static-file-server/src/tests.rs","line":12,"symbol":"assets_not_served_at_root","kind":"function","lang":"rust","doc":"`/script.js` at the root is not an asset under `/assets`, so it falls through to the SPA fallback. The fallback serves `index.html` with a 404 status -- the path wasn't found, but the SPA handles routing client-side.","code":"async fn assets_not_served_at_root() {\n let app = using_serve_dir_with_assets_fallback();\n let response = app\n .oneshot(\n Request::builder()\n .uri(\"/script.js\")\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::NOT_FOUND);\n let body = response.into_body().collect().await.unwrap().to_bytes();\n let body_str = String::from_utf8(body.to_vec()).unwrap();\n assert_eq!(body_str, INDEX_HTML_CONTENT);\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":24,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // save files to a separate directory to not override files in the current directory\n tokio::fs::create_dir(UPLOADS_DIRECTORY)\n .await\n .expect(\"failed to create `uploads` directory\");\n\n let app = Router::new()\n .route(\"/\", get(show_form).post(accept_form))\n .route(\"/file/{file_name}\", post(save_request_body));\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":52,"symbol":"save_request_body","kind":"function","lang":"rust","doc":"Handler that streams the request body to a file. POST'ing to `/file/foo.txt` will create a file called `foo.txt`.","code":"async fn save_request_body(\n Path(file_name): Path,\n request: Request,\n) -> Result<(), (StatusCode, String)> {\n stream_to_file(&file_name, request.into_body().into_data_stream()).await\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":60,"symbol":"show_form","kind":"function","lang":"rust","doc":"Handler that returns HTML for a multipart form.","code":"async fn show_form() -> Html<&'static str> {\n Html(\n r#\"\n \n \n \n Upload something!\n \n \n
\n
\n \n
\n\n
\n \n
\n
\n \n \n \"#,\n )\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":88,"symbol":"accept_form","kind":"function","lang":"rust","doc":"Handler that accepts a multipart form upload and streams each field to a file.","code":"async fn accept_form(mut multipart: Multipart) -> Result {\n while let Ok(Some(field)) = multipart.next_field().await {\n let file_name = if let Some(file_name) = field.file_name() {\n file_name.to_owned()\n } else {\n continue;\n };\n\n stream_to_file(&file_name, field).await?;\n }\n\n Ok(Redirect::to(\"/\"))\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":103,"symbol":"stream_to_file","kind":"function","lang":"rust","doc":"Save a `Stream` to a file","code":"async fn stream_to_file(path: &str, stream: S) -> Result<(), (StatusCode, String)>\nwhere\n S: Stream>,\n E: Into,\n{\n if !path_is_valid(path) {\n return Err((StatusCode::BAD_REQUEST, \"Invalid path\".to_owned()));\n }\n\n async {\n // Convert the stream into an `AsyncRead`.\n let body_with_io_error = stream.map_err(io::Error::other);\n let mut body_reader = pin!(StreamReader::new(body_with_io_error));\n\n // Create the file. `File` implements `AsyncWrite`.\n let path = std::path::Path::new(UPLOADS_DIRECTORY).join(path);\n let mut file = BufWriter::new(File::create(path).await?);\n\n // Copy the body into the file.\n tokio::io::copy(&mut body_reader, &mut file).await?;\n\n Ok::<_, io::Error>(())\n }\n .await\n .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))\n}"} {"repo":"axum","file":"examples/stream-to-file/src/main.rs","line":132,"symbol":"path_is_valid","kind":"function","lang":"rust","doc":"to prevent directory traversal attacks we ensure the path consists of exactly one normal component","code":"fn path_is_valid(path: &str) -> bool {\n let path = std::path::Path::new(path);\n let mut components = path.components().peekable();\n\n if let Some(first) = components.peek() {\n if !matches!(first, std::path::Component::Normal(_)) {\n return false;\n }\n }\n\n components.count() == 1\n}"} {"repo":"axum","file":"examples/templates/src/main.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with some routes\n let app = app();\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/templates/src/main.rs","line":38,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/greet/{name}\", get(greet))\n}"} {"repo":"axum","file":"examples/templates/src/main.rs","line":42,"symbol":"greet","kind":"function","lang":"rust","code":"async fn greet(extract::Path(name): extract::Path) -> impl IntoResponse {\n let template = HelloTemplate { name };\n HtmlTemplate(template)\n}"} {"repo":"axum","file":"examples/templates/src/main.rs","line":49,"symbol":"HelloTemplate","kind":"type","lang":"rust","code":"struct HelloTemplate {\n name: String,\n}"} {"repo":"axum","file":"examples/templates/src/main.rs","line":53,"symbol":"HtmlTemplate","kind":"type","lang":"rust","code":"struct HtmlTemplate(T);"} {"repo":"axum","file":"examples/templates/src/main.rs","line":59,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self.0.render() {\n Ok(html) => Html(html).into_response(),\n Err(err) => (\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"Failed to render template. Error: {err}\"),\n )\n .into_response(),\n }\n }"} {"repo":"axum","file":"examples/templates/src/main.rs","line":82,"symbol":"test_main","kind":"function","lang":"rust","code":"async fn test_main() {\n let response = app()\n .oneshot(Request::get(\"/greet/Foo\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n let body = response.into_body();\n let bytes = body.collect().await.unwrap().to_bytes();\n let html = String::from_utf8(bytes.to_vec()).unwrap();\n\n assert_eq!(html, \"

Hello, Foo!

\");\n }"} {"repo":"axum","file":"examples/templates-minijinja/src/main.rs","line":15,"symbol":"AppState","kind":"type","lang":"rust","code":"struct AppState {\n env: Environment<'static>,\n}"} {"repo":"axum","file":"examples/templates-minijinja/src/main.rs","line":20,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n // init template engine and add templates\n let mut env = Environment::new();\n env.add_template(\"layout\", include_str!(\"../templates/layout.jinja\"))\n .unwrap();\n env.add_template(\"home\", include_str!(\"../templates/home.jinja\"))\n .unwrap();\n env.add_template(\"content\", include_str!(\"../templates/content.jinja\"))\n .unwrap();\n env.add_template(\"about\", include_str!(\"../templates/about.jinja\"))\n .unwrap();\n\n // pass env to handlers via state\n let app_state = Arc::new(AppState { env });\n\n // define routes\n let app = Router::new()\n .route(\"/\", get(handler_home))\n .route(\"/content\", get(handler_content))\n .route(\"/about\", get(handler_about))\n .with_state(app_state);\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/templates-minijinja/src/main.rs","line":50,"symbol":"handler_home","kind":"function","lang":"rust","code":"async fn handler_home(State(state): State>) -> Result, StatusCode> {\n let template = state.env.get_template(\"home\").unwrap();\n\n let rendered = template\n .render(context! {\n title => \"Home\",\n welcome_text => \"Hello World!\",\n })\n .unwrap();\n\n Ok(Html(rendered))\n}"} {"repo":"axum","file":"examples/templates-minijinja/src/main.rs","line":63,"symbol":"handler_content","kind":"function","lang":"rust","code":"async fn handler_content(State(state): State>) -> Result, StatusCode> {\n let template = state.env.get_template(\"content\").unwrap();\n\n let some_example_entries = vec![\"Data 1\", \"Data 2\", \"Data 3\"];\n\n let rendered = template\n .render(context! {\n title => \"Content\",\n entries => some_example_entries,\n })\n .unwrap();\n\n Ok(Html(rendered))\n}"} {"repo":"axum","file":"examples/templates-minijinja/src/main.rs","line":78,"symbol":"handler_about","kind":"function","lang":"rust","code":"async fn handler_about(State(state): State>) -> Result, StatusCode> {\n let template = state.env.get_template(\"about\").unwrap();\n\n let rendered = template.render(context!{\n title => \"About\",\n about_text => \"Simple demonstration layout for an axum project with minijinja as templating engine.\",\n }).unwrap();\n\n Ok(Html(rendered))\n}"} {"repo":"axum","file":"examples/testing/src/main.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app()).await;\n}"} {"repo":"axum","file":"examples/testing/src/main.rs","line":37,"symbol":"app","kind":"function","lang":"rust","doc":"Having a function that produces our app makes it easy to call it from tests without having to create an HTTP server.","code":"fn app() -> Router {\n Router::new()\n .route(\"/\", get(|| async { \"Hello, World!\" }))\n .route(\n \"/json\",\n post(|payload: Json| async move {\n Json(serde_json::json!({ \"data\": payload.0 }))\n }),\n )\n .route(\n \"/requires-connect-info\",\n get(|ConnectInfo(addr): ConnectInfo| async move { format!(\"Hi {addr}\") }),\n )\n // We can still add middleware\n .layer(TraceLayer::new_for_http())\n}"} {"repo":"axum","file":"examples/testing/src/main.rs","line":68,"symbol":"hello_world","kind":"function","lang":"rust","code":"async fn hello_world() {\n let app = app();\n\n // `Router` implements `tower::Service>` so we can\n // call it like any tower service, no need to run an HTTP server.\n let response = app\n .oneshot(Request::get(\"/\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n assert_eq!(&body[..], b\"Hello, World!\");\n }"} {"repo":"axum","file":"examples/testing/src/main.rs","line":85,"symbol":"json","kind":"function","lang":"rust","code":"async fn json() {\n let app = app();\n\n let response = app\n .oneshot(\n Request::post(\"/json\")\n .header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())\n .body(Body::from(\n serde_json::to_vec(&json!([1, 2, 3, 4])).unwrap(),\n ))\n .unwrap(),\n )\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n let body: Value = serde_json::from_slice(&body).unwrap();\n assert_eq!(body, json!({ \"data\": [1, 2, 3, 4] }));\n }"} {"repo":"axum","file":"examples/testing/src/main.rs","line":108,"symbol":"not_found","kind":"function","lang":"rust","code":"async fn not_found() {\n let app = app();\n\n let response = app\n .oneshot(Request::get(\"/does-not-exist\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::NOT_FOUND);\n let body = response.into_body().collect().await.unwrap().to_bytes();\n assert!(body.is_empty());\n }"} {"repo":"axum","file":"examples/testing/src/main.rs","line":123,"symbol":"the_real_deal","kind":"function","lang":"rust","doc":"You can also spawn a server and talk to it like any other HTTP server:","code":"async fn the_real_deal() {\n let listener = TcpListener::bind(\"0.0.0.0:0\").await.unwrap();\n let addr = listener.local_addr().unwrap();\n\n tokio::spawn(async move {\n axum::serve(listener, app()).await;\n });\n\n let client =\n hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())\n .build_http();\n\n let response = client\n .request(\n Request::get(format!(\"http://{addr}\"))\n .header(\"Host\", \"localhost\")\n .body(Body::empty())\n .unwrap(),\n )\n .await\n .unwrap();\n\n let body = response.into_body().collect().await.unwrap().to_bytes();\n assert_eq!(&body[..], b\"Hello, World!\");\n }"} {"repo":"axum","file":"examples/testing/src/main.rs","line":152,"symbol":"multiple_request","kind":"function","lang":"rust","doc":"You can use `ready()` and `call()` to avoid using `clone()` in multiple request","code":"async fn multiple_request() {\n let mut app = app().into_service();\n\n let request = Request::get(\"/\").body(Body::empty()).unwrap();\n let response = ServiceExt::>::ready(&mut app)\n .await\n .unwrap()\n .call(request)\n .await\n .unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n\n let request = Request::get(\"/\").body(Body::empty()).unwrap();\n let response = ServiceExt::>::ready(&mut app)\n .await\n .unwrap()\n .call(request)\n .await\n .unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"examples/testing/src/main.rs","line":180,"symbol":"with_into_make_service_with_connect_info","kind":"function","lang":"rust","doc":"Here we're calling `/requires-connect-info` which requires `ConnectInfo` That is normally set with `Router::into_make_service_with_connect_info` but we can't easily use that during tests. The solution is instead to set the `MockConnectInfo` layer during tests.","code":"async fn with_into_make_service_with_connect_info() {\n let mut app = app()\n .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000))))\n .into_service();\n\n let request = Request::get(\"/requires-connect-info\")\n .body(Body::empty())\n .unwrap();\n let response = app.ready().await.unwrap().call(request).await.unwrap();\n assert_eq!(response.status(), StatusCode::OK);\n }"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n println!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app()).await;\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":27,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n // WebSocket routes can generally be tested in two ways:\n //\n // - Integration tests where you run the server and connect with a real WebSocket client.\n // - Unit tests where you mock the socket as some generic send/receive type\n //\n // Which version you pick is up to you. Generally we recommend the integration test version\n // unless your app has a lot of setup that makes it hard to run in a test.\n Router::new()\n .route(\"/integration-testable\", get(integration_testable_handler))\n .route(\"/unit-testable\", get(unit_testable_handler))\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":43,"symbol":"integration_testable_handler","kind":"function","lang":"rust","doc":"A WebSocket handler that echos any message it receives. This one we'll be integration testing so it can be written in the regular way.","code":"async fn integration_testable_handler(ws: WebSocketUpgrade) -> Response {\n ws.on_upgrade(integration_testable_handle_socket)\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":47,"symbol":"integration_testable_handle_socket","kind":"function","lang":"rust","code":"async fn integration_testable_handle_socket(mut socket: WebSocket) {\n while let Some(Ok(msg)) = socket.recv().await {\n if let Message::Text(msg) = msg {\n if socket\n .send(Message::Text(format!(\"You said: {msg}\").into()))\n .await\n .is_err()\n {\n break;\n }\n }\n }\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":65,"symbol":"unit_testable_handler","kind":"function","lang":"rust","doc":"The unit testable version requires some changes. By splitting the socket into an `impl Sink` and `impl Stream` we can test without providing a real socket and instead using channels, which also implement `Sink` and `Stream`.","code":"async fn unit_testable_handler(ws: WebSocketUpgrade) -> Response {\n ws.on_upgrade(|socket| {\n let (write, read) = socket.split();\n unit_testable_handle_socket(write, read)\n })\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":74,"symbol":"unit_testable_handle_socket","kind":"function","lang":"rust","doc":"The implementation is largely the same as `integration_testable_handle_socket` except we call methods from `SinkExt` and `StreamExt`.","code":"async fn unit_testable_handle_socket(mut write: W, mut read: R)\nwhere\n W: Sink + Unpin,\n R: Stream> + Unpin,\n{\n while let Some(Ok(msg)) = read.next().await {\n if let Message::Text(msg) = msg {\n if write\n .send(Message::Text(format!(\"You said: {msg}\").into()))\n .await\n .is_err()\n {\n break;\n }\n }\n }\n}"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":104,"symbol":"integration_test","kind":"function","lang":"rust","doc":"We can integration test one handler by running the server in a background task and connecting to it like any other client would.","code":"async fn integration_test() {\n let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let addr = listener.local_addr().unwrap();\n tokio::spawn(axum::serve(listener, app()).into_future());\n\n let (mut socket, _response) =\n tokio_tungstenite::connect_async(format!(\"ws://{addr}/integration-testable\"))\n .await\n .unwrap();\n\n socket\n .send(tungstenite::Message::text(\"foo\"))\n .await\n .unwrap();\n\n let msg = match socket.next().await.unwrap().unwrap() {\n tungstenite::Message::Text(msg) => msg,\n other => panic!(\"expected a text message but got {other:?}\"),\n };\n\n assert_eq!(msg.as_str(), \"You said: foo\");\n }"} {"repo":"axum","file":"examples/testing-websockets/src/main.rs","line":131,"symbol":"unit_test","kind":"function","lang":"rust","doc":"We can unit test the other handler by creating channels to read and write from.","code":"async fn unit_test() {\n // Need to use \"futures\" channels rather than \"tokio\" channels as they implement `Sink` and\n // `Stream`\n let (socket_write, mut test_rx) = futures_channel::mpsc::channel(1024);\n let (mut test_tx, socket_read) = futures_channel::mpsc::channel(1024);\n\n tokio::spawn(unit_testable_handle_socket(socket_write, socket_read));\n\n test_tx.send(Ok(Message::Text(\"foo\".into()))).await.unwrap();\n\n let msg = match test_rx.next().await.unwrap() {\n Message::Text(msg) => msg,\n other => panic!(\"expected a text message but got {other:?}\"),\n };\n\n assert_eq!(msg.as_str(), \"You said: foo\");\n }"} {"repo":"axum","file":"examples/tls-graceful-shutdown/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/tls-graceful-shutdown/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":20,"symbol":"Ports","kind":"type","lang":"rust","code":"struct Ports {\n http: u16,\n https: u16,\n}"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":26,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let ports = Ports {\n http: 7878,\n https: 3000,\n };\n\n //Create a handle for our TLS server so the shutdown signal can all shutdown\n let handle = axum_server::Handle::new();\n //save the future for easy shutting down of redirect server\n let shutdown_future = shutdown_signal(handle.clone());\n\n // optional: spawn a second server to redirect http requests to this server\n tokio::spawn(redirect_http_to_https(ports, shutdown_future));\n\n // configure certificate and private key used by https\n let config = RustlsConfig::from_pem_file(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n )\n .await\n .unwrap();\n\n let app = Router::new().route(\"/\", get(handler))"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":72,"symbol":"shutdown_signal","kind":"function","lang":"rust","code":"async fn shutdown_signal(handle: axum_server::Handle) {\n let ctrl_c = async {\n signal::ctrl_c()\n .await\n .expect(\"failed to install Ctrl+C handler\");\n };\n\n #[cfg(unix)]\n let terminate = async {\n signal::unix::signal(signal::unix::SignalKind::terminate())\n .expect(\"failed to install signal handler\")\n .recv()\n .await;\n };\n\n #[cfg(not(unix))]\n let terminate = std::future::pending::<()>();\n\n tokio::select! {\n _ = ctrl_c => {},\n _ = terminate => {},\n }\n\n tracing::info!(\"Received termination signal shutting down\");\n handle.graceful_shutdown(Some(Duration::from_secs(10))); // 10 secs is how long docker will wait\n // to force shutdown\n}"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":100,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":104,"symbol":"redirect_http_to_https","kind":"function","lang":"rust","code":"async fn redirect_http_to_https(ports: Ports, signal: F)\nwhere\n F: Future + Send + 'static,\n{\n fn make_https(uri: Uri, https_port: u16) -> Result {\n let mut parts = uri.into_parts();\n\n parts.scheme = Some(axum::http::uri::Scheme::HTTPS);\n parts.authority = Some(format!(\"localhost:{https_port}\").parse()?);\n\n if parts.path_and_query.is_none() {\n parts.path_and_query = Some(\"/\".parse().unwrap());\n }\n\n Ok(Uri::from_parts(parts)?)\n }\n\n let redirect = move |uri: Uri| async move {\n match make_https(uri, ports.https) {\n Ok(uri) => Ok(Redirect::permanent(uri.to_string())),\n Err(error) => {\n tracing::warn!(%error, \"failed to convert URI to HTTPS\");\n Err(StatusCode::BAD_REQUEST)\n }\n }\n };\n\n let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));\n let listener = tokio::net::TcpListener::bind(addr).await.unwrap();\n tracing::debug!(\"listening on {addr}\");\n axum::serve(listener, redirect.into_make_service())\n .with_graceful_shutdown(signal)\n .await;\n}"} {"repo":"axum","file":"examples/tls-graceful-shutdown/src/main.rs","line":108,"symbol":"make_https","kind":"function","lang":"rust","code":"fn make_https(uri: Uri, https_port: u16) -> Result {\n let mut parts = uri.into_parts();\n\n parts.scheme = Some(axum::http::uri::Scheme::HTTPS);\n parts.authority = Some(format!(\"localhost:{https_port}\").parse()?);\n\n if parts.path_and_query.is_none() {\n parts.path_and_query = Some(\"/\".parse().unwrap());\n }\n\n Ok(Uri::from_parts(parts)?)\n }"} {"repo":"axum","file":"examples/tls-rustls/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/tls-rustls/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/tls-rustls/src/main.rs","line":22,"symbol":"Ports","kind":"type","lang":"rust","code":"struct Ports {\n http: u16,\n https: u16,\n}"} {"repo":"axum","file":"examples/tls-rustls/src/main.rs","line":28,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let ports = Ports {\n http: 7878,\n https: 3000,\n };\n // optional: spawn a second server to redirect http requests to this server\n tokio::spawn(redirect_http_to_https(ports));\n\n // configure certificate and private key used by https\n let config = RustlsConfig::from_pem_file(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n )\n .await\n .unwrap();\n\n let app = Router::new().route(\"/\", get(handler));\n\n // run https server\n let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));\n tracing::debug!(\"listening on {}\", addr);\n axum_server::bind_rustls(addr, config)\n .serve(app.into_make_service())\n .await\n .unwrap();\n}"} {"repo":"axum","file":"examples/tls-rustls/src/main.rs","line":68,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> &'static str {\n \"Hello, World!\"\n}"} {"repo":"axum","file":"examples/tls-rustls/src/main.rs","line":73,"symbol":"redirect_http_to_https","kind":"function","lang":"rust","code":"async fn redirect_http_to_https(ports: Ports) {\n fn make_https(uri: Uri, https_port: u16) -> Result {\n let mut parts = uri.into_parts();\n\n parts.scheme = Some(axum::http::uri::Scheme::HTTPS);\n parts.authority = Some(format!(\"localhost:{https_port}\").parse()?);\n\n if parts.path_and_query.is_none() {\n parts.path_and_query = Some(\"/\".parse().unwrap());\n }\n\n Ok(Uri::from_parts(parts)?)\n }\n\n let redirect = move |uri: Uri| async move {\n match make_https(uri, ports.https) {\n Ok(uri) => Ok(Redirect::permanent(uri.to_string())),\n Err(error) => {\n tracing::warn!(%error, \"failed to convert URI to HTTPS\");\n Err(StatusCode::BAD_REQUEST)\n }\n }\n };\n\n let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));\n let listener = tokio::net::TcpListener::bind(addr).await.unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, redirect.into_make_service()).await;\n}"} {"repo":"axum","file":"examples/tls-rustls/src/main.rs","line":74,"symbol":"make_https","kind":"function","lang":"rust","code":"fn make_https(uri: Uri, https_port: u16) -> Result {\n let mut parts = uri.into_parts();\n\n parts.scheme = Some(axum::http::uri::Scheme::HTTPS);\n parts.authority = Some(format!(\"localhost:{https_port}\").parse()?);\n\n if parts.path_and_query.is_none() {\n parts.path_and_query = Some(\"/\".parse().unwrap());\n }\n\n Ok(Uri::from_parts(parts)?)\n }"} {"repo":"axum","file":"examples/todos/src/main.rs","line":36,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let db = Db::default();\n\n // Compose the routes\n let app = Router::new()\n .route(\"/todos\", get(todos_index).post(todos_create))\n .route(\"/todos/{id}\", patch(todos_update).delete(todos_delete))\n // Add middleware to all routes\n .layer(\n ServiceBuilder::new()\n .layer(HandleErrorLayer::new(|error: BoxError| async move {\n if error.is::() {\n Ok(StatusCode::REQUEST_TIMEOUT)\n } else {\n Err((\n StatusCode::INTERNAL_SERVER_ERROR,\n format!(\"Unhandled internal error: {error}\"),\n ))\n }\n }))\n .timeout(Duration::from_secs(10))\n .layer(TraceLayer::new_for_"} {"repo":"axum","file":"examples/todos/src/main.rs","line":80,"symbol":"Pagination","kind":"type","lang":"rust","doc":"The query parameters for todos index","code":"pub struct Pagination {\n pub offset: Option,\n pub limit: Option,\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":85,"symbol":"todos_index","kind":"function","lang":"rust","code":"async fn todos_index(pagination: Query, State(db): State) -> impl IntoResponse {\n let todos = db.read().unwrap();\n\n let todos = todos\n .values()\n .skip(pagination.offset.unwrap_or(0))\n .take(pagination.limit.unwrap_or(usize::MAX))\n .cloned()\n .collect::>();\n\n Json(todos)\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":99,"symbol":"CreateTodo","kind":"type","lang":"rust","code":"struct CreateTodo {\n text: String,\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":103,"symbol":"todos_create","kind":"function","lang":"rust","code":"async fn todos_create(State(db): State, Json(input): Json) -> impl IntoResponse {\n let todo = Todo {\n id: Uuid::new_v4(),\n text: input.text,\n completed: false,\n };\n\n db.write().unwrap().insert(todo.id, todo.clone());\n\n (StatusCode::CREATED, Json(todo))\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":116,"symbol":"UpdateTodo","kind":"type","lang":"rust","code":"struct UpdateTodo {\n text: Option,\n completed: Option,\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":121,"symbol":"todos_update","kind":"function","lang":"rust","code":"async fn todos_update(\n Path(id): Path,\n State(db): State,\n Json(input): Json,\n) -> Result {\n let mut todo = db\n .read()\n .unwrap()\n .get(&id)\n .cloned()\n .ok_or(StatusCode::NOT_FOUND)?;\n\n if let Some(text) = input.text {\n todo.text = text;\n }\n\n if let Some(completed) = input.completed {\n todo.completed = completed;\n }\n\n db.write().unwrap().insert(todo.id, todo.clone());\n\n Ok(Json(todo))\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":146,"symbol":"todos_delete","kind":"function","lang":"rust","code":"async fn todos_delete(Path(id): Path, State(db): State) -> impl IntoResponse {\n if db.write().unwrap().remove(&id).is_some() {\n StatusCode::NO_CONTENT\n } else {\n StatusCode::NOT_FOUND\n }\n}"} {"repo":"axum","file":"examples/todos/src/main.rs","line":157,"symbol":"Todo","kind":"type","lang":"rust","code":"struct Todo {\n id: Uuid,\n text: String,\n completed: bool,\n}"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":19,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // set up connection pool\n let manager =\n PostgresConnectionManager::new_from_stringlike(\"host=localhost user=postgres\", NoTls)\n .unwrap();\n let pool = Pool::builder().build(manager).await.unwrap();\n\n // build our application with some routes\n let app = Router::new()\n .route(\n \"/\",\n get(using_connection_pool_extractor).post(using_connection_extractor),\n )\n .with_state(pool);\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":52,"symbol":"using_connection_pool_extractor","kind":"function","lang":"rust","code":"async fn using_connection_pool_extractor(\n State(pool): State,\n) -> Result {\n let conn = pool.get().await.map_err(internal_error)?;\n\n let row = conn\n .query_one(\"select 1 + 1\", &[])\n .await\n .map_err(internal_error)?;\n let two: i32 = row.try_get(0).map_err(internal_error)?;\n\n Ok(two.to_string())\n}"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":68,"symbol":"DatabaseConnection","kind":"type","lang":"rust","doc":"we can also write a custom extractor that grabs a connection from the pool which setup is appropriate depends on your application","code":"struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager>);"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":77,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result {\n let pool = ConnectionPool::from_ref(state);\n\n let conn = pool.get_owned().await.map_err(internal_error)?;\n\n Ok(Self(conn))\n }"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":86,"symbol":"using_connection_extractor","kind":"function","lang":"rust","code":"async fn using_connection_extractor(\n DatabaseConnection(conn): DatabaseConnection,\n) -> Result {\n let row = conn\n .query_one(\"select 1 + 1\", &[])\n .await\n .map_err(internal_error)?;\n let two: i32 = row.try_get(0).map_err(internal_error)?;\n\n Ok(two.to_string())\n}"} {"repo":"axum","file":"examples/tokio-postgres/src/main.rs","line":100,"symbol":"internal_error","kind":"function","lang":"rust","doc":"Utility function for mapping any error into a `500 Internal Server Error` response.","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":17,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n tracing::debug!(\"connecting to redis\");\n let client = redis::Client::open(\"redis://localhost\").unwrap();\n let pool = bb8::Pool::builder().build(client).await.unwrap();\n\n {\n // ping the database before starting\n let mut conn = pool.get().await.unwrap();\n conn.set::<&str, &str, ()>(\"foo\", \"bar\").await.unwrap();\n let result: String = conn.get(\"foo\").await.unwrap();\n assert_eq!(result, \"bar\");\n }\n tracing::debug!(\"successfully connected to redis and pinged it\");\n\n // build our application with some routes\n let app = Router::new()\n .route(\n \"/\",\n get(using_connection_pool_extractor).post(using_connection_extractor),\n )\n .with_state(pool);\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\","} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":57,"symbol":"using_connection_pool_extractor","kind":"function","lang":"rust","code":"async fn using_connection_pool_extractor(\n State(pool): State,\n) -> Result {\n let mut conn = pool.get().await.map_err(internal_error)?;\n let result: String = conn.get(\"foo\").await.map_err(internal_error)?;\n Ok(result)\n}"} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":67,"symbol":"DatabaseConnection","kind":"type","lang":"rust","doc":"we can also write a custom extractor that grabs a connection from the pool which setup is appropriate depends on your application","code":"struct DatabaseConnection(bb8::PooledConnection<'static, redis::Client>);"} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":76,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result {\n let pool = ConnectionPool::from_ref(state);\n\n let conn = pool.get_owned().await.map_err(internal_error)?;\n\n Ok(Self(conn))\n }"} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":85,"symbol":"using_connection_extractor","kind":"function","lang":"rust","code":"async fn using_connection_extractor(\n DatabaseConnection(mut conn): DatabaseConnection,\n) -> Result {\n let result: String = conn.get(\"foo\").await.map_err(internal_error)?;\n\n Ok(result)\n}"} {"repo":"axum","file":"examples/tokio-redis/src/main.rs","line":95,"symbol":"internal_error","kind":"function","lang":"rust","doc":"Utility function for mapping any error into a `500 Internal Server Error` response.","code":"fn internal_error(err: E) -> (StatusCode, String)\nwhere\n E: std::error::Error,\n{\n (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())\n}"} {"repo":"axum","file":"examples/tracing-aka-logging/src/main.rs","line":22,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n // axum logs rejections from built-in extractors with the `axum::rejection`\n // target, at `TRACE` level. `axum::rejection=trace` enables showing those events\n format!(\n \"{}=debug,tower_http=debug,axum::rejection=trace\",\n env!(\"CARGO_CRATE_NAME\")\n )\n .into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with a route\n let app = Router::new()\n .route(\"/\", get(handler))\n // `TraceLayer` is provided by tower-http so you have to add that as a dependency.\n // It provides good defaults but is also very customizable.\n //\n // See https://docs.rs/tower-http/0.6.1/tower_http/trace/index.html for more details.\n //\n // If you want to customize the behavior using closures here is how.\n .layer(\n TraceLayer::new_for_http()\n .make_span_with(|request: &Request<_>| {\n "} {"repo":"axum","file":"examples/tracing-aka-logging/src/main.rs","line":94,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler() -> Html<&'static str> {\n Html(\"

Hello, World!

\")\n}"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":8,"symbol":"main","kind":"function","lang":"rust","doc":"Run with ```not_rust cargo run -p example-unix-domain-socket ```","code":"async fn main() {\n unix::server().await;\n}"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":13,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n println!(\"This example requires unix\")\n}"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":33,"symbol":"server","kind":"function","lang":"rust","code":"pub async fn server() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let path = PathBuf::from(\"/tmp/axum/helloworld\");\n\n let _ = tokio::fs::remove_file(&path).await;\n tokio::fs::create_dir_all(path.parent().unwrap())\n .await\n .unwrap();\n\n let uds = UnixListener::bind(path.clone()).unwrap();\n tokio::spawn(async move {\n let app = Router::new()\n .route(\"/\", get(handler))\n .into_make_service_with_connect_info::();\n\n axum::serve(uds, app).await;\n });\n\n let stream = TokioIo::new(UnixStream::connect(path).await.unwrap());\n let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();\n tokio::task::spawn(async move {\n if let Err(err) = conn.await {\n println!(\"Connection failed: {err:?}\");\n }\n });\n\n let request = Request::get(\"http://uri-doe"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":79,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ConnectInfo(info): ConnectInfo) -> &'static str {\n println!(\"new connection from `{info:?}`\");\n\n \"Hello, World!\"\n }"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":87,"symbol":"UdsConnectInfo","kind":"type","lang":"rust","code":"struct UdsConnectInfo {\n peer_addr: Arc,\n peer_cred: UCred,\n }"} {"repo":"axum","file":"examples/unix-domain-socket/src/main.rs","line":93,"symbol":"connect_info","kind":"function","lang":"rust","code":"fn connect_info(stream: IncomingStream<'_, UnixListener>) -> Self {\n let peer_addr = stream.io().peer_addr().unwrap();\n let peer_cred = stream.io().peer_cred().unwrap();\n Self {\n peer_addr: Arc::new(peer_addr),\n peer_cred,\n }\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":27,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with a route\n let app = app();\n\n // run it\n let listener = TcpListener::bind(\"127.0.0.1:3000\").await.unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/validator/src/main.rs","line":45,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/\", get(handler))\n}"} {"repo":"axum","file":"examples/validator/src/main.rs","line":50,"symbol":"NameInput","kind":"type","lang":"rust","code":"pub struct NameInput {\n #[validate(length(min = 2, message = \"Must be at least 2 characters\"))]\n pub name: String,\n}"} {"repo":"axum","file":"examples/validator/src/main.rs","line":55,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(ValidatedForm(input): ValidatedForm) -> Html {\n Html(format!(\"

Hello, {}!

\", input.name))\n}"} {"repo":"axum","file":"examples/validator/src/main.rs","line":60,"symbol":"ValidatedForm","kind":"type","lang":"rust","code":"pub struct ValidatedForm(pub T);"} {"repo":"axum","file":"examples/validator/src/main.rs","line":70,"symbol":"from_request","kind":"function","lang":"rust","code":"async fn from_request(req: Request, state: &S) -> Result {\n let Form(value) = Form::::from_request(req, state).await?;\n value.validate()?;\n Ok(ValidatedForm(value))\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":78,"symbol":"ServerError","kind":"type","lang":"rust","code":"pub enum ServerError {\n #[error(transparent)]\n ValidationError(#[from] validator::ValidationErrors),\n\n #[error(transparent)]\n AxumFormRejection(#[from] FormRejection),\n}"} {"repo":"axum","file":"examples/validator/src/main.rs","line":87,"symbol":"into_response","kind":"function","lang":"rust","code":"fn into_response(self) -> Response {\n match self {\n ServerError::ValidationError(_) => {\n let message = format!(\"Input validation error: [{self}]\").replace('\\n', \", \");\n (StatusCode::BAD_REQUEST, message)\n }\n ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),\n }\n .into_response()\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":109,"symbol":"get_html","kind":"function","lang":"rust","code":"async fn get_html(response: Response) -> String {\n let body = response.into_body();\n let bytes = body.collect().await.unwrap().to_bytes();\n String::from_utf8(bytes.to_vec()).unwrap()\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":116,"symbol":"test_no_param","kind":"function","lang":"rust","code":"async fn test_no_param() {\n let response = app()\n .oneshot(Request::get(\"/\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::BAD_REQUEST);\n let html = get_html(response).await;\n assert_eq!(html, \"Failed to deserialize form: missing field `name`\");\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":128,"symbol":"test_with_param_without_value","kind":"function","lang":"rust","code":"async fn test_with_param_without_value() {\n let response = app()\n .oneshot(Request::get(\"/?name=\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::BAD_REQUEST);\n let html = get_html(response).await;\n assert_eq!(\n html,\n \"Input validation error: [name: Must be at least 2 characters]\"\n );\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":143,"symbol":"test_with_param_with_short_value","kind":"function","lang":"rust","code":"async fn test_with_param_with_short_value() {\n let response = app()\n .oneshot(Request::get(\"/?name=X\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::BAD_REQUEST);\n let html = get_html(response).await;\n assert_eq!(\n html,\n \"Input validation error: [name: Must be at least 2 characters]\"\n );\n }"} {"repo":"axum","file":"examples/validator/src/main.rs","line":158,"symbol":"test_with_param_and_value","kind":"function","lang":"rust","code":"async fn test_with_param_and_value() {\n let response = app()\n .oneshot(Request::get(\"/?name=LT\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n let html = get_html(response).await;\n assert_eq!(html, \"

Hello, LT!

\");\n }"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":18,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // build our application with some routes\n let app = app();\n\n // run it\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(listener, app).await;\n}"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":38,"symbol":"app","kind":"function","lang":"rust","code":"fn app() -> Router {\n Router::new().route(\"/{version}/foo\", get(handler))\n}"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":42,"symbol":"handler","kind":"function","lang":"rust","code":"async fn handler(version: Version) -> Html {\n Html(format!(\"received request with version {version:?}\"))\n}"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":47,"symbol":"Version","kind":"type","lang":"rust","code":"enum Version {\n V1,\n V2,\n V3,\n}"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":59,"symbol":"from_request_parts","kind":"function","lang":"rust","code":"async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result {\n let params: Path> =\n parts.extract().await.map_err(IntoResponse::into_response)?;\n\n let version = params\n .get(\"version\")\n .ok_or_else(|| (StatusCode::NOT_FOUND, \"version param missing\").into_response())?;\n\n match version.as_str() {\n \"v1\" => Ok(Version::V1),\n \"v2\" => Ok(Version::V2),\n \"v3\" => Ok(Version::V3),\n _ => Err((StatusCode::NOT_FOUND, \"unknown version\").into_response()),\n }\n }"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":84,"symbol":"test_v1","kind":"function","lang":"rust","code":"async fn test_v1() {\n let response = app()\n .oneshot(Request::get(\"/v1/foo\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::OK);\n let body = response.into_body();\n let bytes = body.collect().await.unwrap().to_bytes();\n let html = String::from_utf8(bytes.to_vec()).unwrap();\n\n assert_eq!(html, \"received request with version V1\");\n }"} {"repo":"axum","file":"examples/versioning/src/main.rs","line":99,"symbol":"test_v4","kind":"function","lang":"rust","code":"async fn test_v4() {\n let response = app()\n .oneshot(Request::get(\"/v4/foo\").body(Body::empty()).unwrap())\n .await\n .unwrap();\n\n assert_eq!(response.status(), StatusCode::NOT_FOUND);\n let body = response.into_body();\n let bytes = body.collect().await.unwrap().to_bytes();\n let html = String::from_utf8(bytes.to_vec()).unwrap();\n\n assert_eq!(html, \"unknown version\");\n }"} {"repo":"axum","file":"examples/websockets/src/client.rs","line":29,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n let start_time = Instant::now();\n //spawn several clients that will concurrently talk to the server\n let mut clients = (0..N_CLIENTS).map(spawn_client).collect::>();\n\n //wait for all our clients to exit\n while clients.join_next().await.is_some() {}\n\n let end_time = Instant::now();\n\n //total time should be the same no matter how many clients we spawn\n println!(\n \"Total time taken {:#?} with {N_CLIENTS} concurrent clients, should be about 6.45 seconds.\",\n end_time - start_time\n );\n}"} {"repo":"axum","file":"examples/websockets/src/client.rs","line":47,"symbol":"spawn_client","kind":"function","lang":"rust","doc":"creates a client. quietly exits on failure.","code":"async fn spawn_client(who: usize) {\n let ws_stream = match connect_async(SERVER).await {\n Ok((stream, response)) => {\n println!(\"Handshake for client {who} has been completed\");\n // This will be the HTTP response, same as with server this is the last moment we\n // can still access HTTP stuff.\n println!(\"Server response was {response:?}\");\n stream\n }\n Err(e) => {\n println!(\"WebSocket handshake for client {who} failed with {e}!\");\n return;\n }\n };\n\n let (mut sender, mut receiver) = ws_stream.split();\n\n //we can ping the server for start\n sender\n .send(Message::Ping(axum::body::Bytes::from_static(\n b\"Hello, Server!\",\n )))\n .await\n .expect(\"Can not send!\");\n\n //spawn an async sender to push some more messages into the server\n let mut send_task = tokio::spawn(async move {\n for i in 1..30 {\n // In any websocket error, break loop.\n if sender\n .send(Message::Text(format!(\"Message number {i}...\").into()))\n .await\n .is_err()\n {\n //j"} {"repo":"axum","file":"examples/websockets/src/client.rs","line":124,"symbol":"process_message","kind":"function","lang":"rust","doc":"Function to handle messages we get (with a slight twist that Frame variant is visible since we are working with the underlying tungstenite library directly without axum here).","code":"fn process_message(msg: Message, who: usize) -> ControlFlow<(), ()> {\n match msg {\n Message::Text(t) => {\n println!(\">>> {who} got str: {t:?}\");\n }\n Message::Binary(d) => {\n println!(\">>> {who} got {} bytes: {d:?}\", d.len());\n }\n Message::Close(c) => {\n if let Some(cf) = c {\n println!(\n \">>> {who} got close with code {} and reason `{}`\",\n cf.code, cf.reason\n );\n } else {\n println!(\">>> {who} somehow got close message without CloseFrame\");\n }\n return ControlFlow::Break(());\n }\n\n Message::Pong(v) => {\n println!(\">>> {who} got pong with {v:?}\");\n }\n // Just as with axum server, the underlying tungstenite websocket library\n // will handle Ping for you automagically by replying with Pong and copying the\n // v according to spec. But if you need the contents of the pings you can see them here.\n Message::Ping(v) => {\n println!(\">>> {who} got ping with {v:?}\");\n }\n\n Message::Frame(_) => {\n unreachable!(\"This is n"} {"repo":"axum","file":"examples/websockets/src/main.rs","line":45,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {\n format!(\"{}=debug,tower_http=debug\", env!(\"CARGO_CRATE_NAME\")).into()\n }),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let assets_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\")).join(\"assets\");\n\n // build our application with some routes\n let app = Router::new()\n .fallback_service(ServeDir::new(assets_dir).append_index_html_on_directories(true))\n .route(\"/ws\", any(ws_handler))\n // logging so we can see what's going on\n .layer(\n TraceLayer::new_for_http()\n .make_span_with(DefaultMakeSpan::default().include_headers(true)),\n );\n\n // run it with hyper\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\")\n .await\n .unwrap();\n tracing::debug!(\"listening on {}\", listener.local_addr().unwrap());\n axum::serve(\n listener,\n app.into_make_service_with_connect_info::(),\n )\n .await;\n}"} {"repo":"axum","file":"examples/websockets/src/main.rs","line":84,"symbol":"ws_handler","kind":"function","lang":"rust","doc":"The handler for the HTTP request (this gets called when the HTTP request lands at the start of websocket negotiation). After this completes, the actual switching from HTTP to websocket protocol will occur. This is the last point where we can extract TCP/IP metadata such as IP address of the client as well as things from HTTP headers such as user-agent of the browser etc.","code":"async fn ws_handler(\n ws: WebSocketUpgrade,\n user_agent: Option>,\n ConnectInfo(addr): ConnectInfo,\n) -> impl IntoResponse {\n let user_agent = if let Some(TypedHeader(user_agent)) = user_agent {\n user_agent.to_string()\n } else {\n String::from(\"Unknown browser\")\n };\n println!(\"`{user_agent}` at {addr} connected.\");\n // finalize the upgrade process by returning upgrade callback.\n // we can customize the callback by sending additional info such as address.\n ws.on_upgrade(move |socket| handle_socket(socket, addr))\n}"} {"repo":"axum","file":"examples/websockets/src/main.rs","line":101,"symbol":"handle_socket","kind":"function","lang":"rust","doc":"Actual websocket statemachine (one will be spawned per connection)","code":"async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {\n // send a ping (unsupported by some browsers) just to kick things off and get a response\n if socket\n .send(Message::Ping(Bytes::from_static(&[1, 2, 3])))\n .await\n .is_ok()\n {\n println!(\"Pinged {who}...\");\n } else {\n println!(\"Could not send ping {who}!\");\n // no Error here since the only thing we can do is to close the connection.\n // If we can not send messages, there is no way to salvage the statemachine anyway.\n return;\n }\n\n // receive single message from a client (we can either receive or send with socket).\n // this will likely be the Pong for our Ping or a hello message from client.\n // waiting for message from a client will block this task, but will not block other client's\n // connections.\n if let Some(msg) = socket.recv().await {\n if let Ok(msg) = msg {\n if process_message(msg, who).is_break() {\n return;\n }\n } else {\n println!(\"client {who} abruptly disconnected\");\n return;\n }\n }\n\n // Since each client gets individual statemachine, we can p"} {"repo":"axum","file":"examples/websockets/src/main.rs","line":216,"symbol":"process_message","kind":"function","lang":"rust","doc":"helper to print contents of messages to stdout. Has special treatment for Close.","code":"fn process_message(msg: Message, who: SocketAddr) -> ControlFlow<(), ()> {\n match msg {\n Message::Text(t) => {\n println!(\">>> {who} sent str: {t:?}\");\n }\n Message::Binary(d) => {\n println!(\">>> {who} sent {} bytes: {d:?}\", d.len());\n }\n Message::Close(c) => {\n if let Some(cf) = c {\n println!(\n \">>> {who} sent close with code {} and reason `{}`\",\n cf.code, cf.reason\n );\n } else {\n println!(\">>> {who} somehow sent close message without CloseFrame\");\n }\n return ControlFlow::Break(());\n }\n\n Message::Pong(v) => {\n println!(\">>> {who} sent pong with {v:?}\");\n }\n // You should never need to manually handle Message::Ping, as axum's websocket library\n // will do so for you automagically by replying with Pong and copying the v according to\n // spec. But if you need the contents of the pings you can see them here.\n Message::Ping(v) => {\n println!(\">>> {who} sent ping with {v:?}\");\n }\n }\n ControlFlow::Continue(())\n}"} {"repo":"axum","file":"examples/websockets-http2/self_signed_certs/cert.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"} {"repo":"axum","file":"examples/websockets-http2/self_signed_certs/key.pem","line":1,"symbol":"PRIVATE KEY","kind":"field","lang":"pem","code":"-----BEGIN PRIVATE KEY-----"} {"repo":"axum","file":"examples/websockets-http2/src/main.rs","line":23,"symbol":"main","kind":"function","lang":"rust","code":"async fn main() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| format!(\"{}=debug\", env!(\"CARGO_CRATE_NAME\")).into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n let assets_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\")).join(\"assets\");\n\n // configure certificate and private key used by https\n let config = RustlsConfig::from_pem_file(\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"cert.pem\"),\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n .join(\"self_signed_certs\")\n .join(\"key.pem\"),\n )\n .await\n .unwrap();\n\n // build our application with some routes and a broadcast channel\n let app = Router::new()\n .fallback_service(ServeDir::new(assets_dir).append_index_html_on_directories(true))\n .route(\"/ws\", any(ws_handler))\n .with_state(broadcast::channel::(16).0);\n\n let addr = SocketAddr::from(([127, 0, 0, 1], 3000));\n tracing::debug!(\"listening on {}\", addr);\n\n let mut server = axum_server::bind_rustls(addr,"} {"repo":"axum","file":"examples/websockets-http2/src/main.rs","line":64,"symbol":"ws_handler","kind":"function","lang":"rust","code":"async fn ws_handler(\n ws: WebSocketUpgrade,\n version: Version,\n State(sender): State>,\n) -> axum::response::Response {\n tracing::debug!(\"accepted a WebSocket using {version:?}\");\n let mut receiver = sender.subscribe();\n ws.on_upgrade(|mut ws| async move {\n loop {\n tokio::select! {\n // Since `ws` is a `Stream`, it is by nature cancel-safe.\n res = ws.recv() => {\n match res {\n Some(Ok(ws::Message::Text(s))) => {\n let _ = sender.send(s.to_string());\n }\n Some(Ok(_)) => {}\n Some(Err(e)) => tracing::debug!(\"client disconnected abruptly: {e}\"),\n None => break,\n }\n }\n // Tokio guarantees that `broadcast::Receiver::recv` is cancel-safe.\n res = receiver.recv() => {\n match res {\n Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg.into())).await {\n tracing::debug!(\"client disconnected abruptly: {e}\");\n "}