### WebSocketUpgrade Usage Example Source: https://docs.rs/axum/0.7.9/axum/extract/struct.WebSocketUpgrade.html Example demonstrating how to use the WebSocketUpgrade extractor with a GET request and configure supported protocols. ```APIDOC ## Example ```rust use axum::extract::ws::{WebSocketUpgrade, WebSocket}; use axum::{routing::get, response::Response, Router}; let app = Router::new().route("/ws", get(handler)); async fn handler(ws: WebSocketUpgrade) -> Response { ws.protocols(["graphql-ws", "graphql-transport-ws"]) .on_upgrade(|socket: WebSocket| async { // Handle the WebSocket connection }) } ``` ``` -------------------------------- ### Routing Different HTTP Methods to Services Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html This example demonstrates how to route different HTTP methods to distinct services for a single route path. POST requests to '/' are handled by `service`, while GET requests are handled by `other_service`. Note that GET routes also implicitly handle HEAD requests with the body removed. ```rust use axum::{ extract::Request, Router, routing::post_service, body::Body, }; use http::Response; use std::convert::Infallible; let service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); let other_service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); // Requests to `POST /` will go to `service` and `GET /` will go to // `other_service`. let app = Router::new().route("/", post_service(service).get_service(other_service)); ``` -------------------------------- ### Basic Axum Server Setup Source: https://docs.rs/axum/0.7.9/axum/attr.debug_handler.html This is a basic axum server setup. The `debug_handler` macro is useful here to catch errors if the handler function is not correctly defined. ```rust use axum::{ routing::get, Router, }; #[tokio::main] async fn main() { let app = Router::new().route("/", get(handler)); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } fn handler() -> &'static str { "Hello, world" } ``` -------------------------------- ### SSE Handler Example Source: https://docs.rs/axum/0.7.9/axum/response/sse/index.html An example of an SSE handler that sends a 'hi!' message every second. This requires the `tokio` feature to be enabled. ```APIDOC ## GET /sse ### Description Handles Server-Sent Events (SSE) by providing a stream of messages. ### Method GET ### Endpoint /sse ### Parameters None ### Request Body None ### Response #### Success Response (200) - `Sse>>`: A stream of Server-Sent Events. ### Response Example ```rust use axum::response::sse::{Event, KeepAlive, Sse}; use std::{time::Duration, convert::Infallible}; use tokio_stream::StreamExt as _; use futures_util::stream::{self, Stream}; async fn sse_handler() -> Sse>> { let stream = stream::repeat_with(|| Event::default().data("hi!")) .map(Ok) .throttle(Duration::from_secs(1)); Sse::new(stream).keep_alive(KeepAlive::default()) } ``` ``` -------------------------------- ### Comprehensive Router example with various routes Source: https://docs.rs/axum/0.7.9/axum/routing/struct.Router.html An example demonstrating the creation of a Router with multiple routes, including static paths, dynamic captures for single values (like user IDs), and wildcard paths for serving assets. ```rust use axum::{Router, routing::{get, delete}, extract::Path}; let app = Router::new() .route("/", get(root)) .route("/users", get(list_users).post(create_user)) .route("/users/:id", get(show_user)) .route("/api/:version/users/:id/action", delete(do_users_action)) .route("/assets/*path", get(serve_asset)); async fn root() {} async fn list_users() {} async fn create_user() {} async fn show_user(Path(id): Path) {} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {} async fn serve_asset(Path(path): Path) {} ``` -------------------------------- ### Handling Failed Upgrades Example Source: https://docs.rs/axum/0.7.9/axum/extract/struct.WebSocketUpgrade.html Example showing how to provide a callback for handling failed WebSocket upgrades. ```APIDOC ## Example ```rust use axum::extract::ws::WebSocketUpgrade; use axum::response::Response; async fn handler(ws: WebSocketUpgrade) -> Response { ws.on_failed_upgrade(|error| { // Report the error, e.g., using a logging framework eprintln!("WebSocket upgrade failed: {:?}", error); }) .on_upgrade(|socket| async { // Handle the WebSocket connection }) } ``` ``` -------------------------------- ### Request::get() Source: https://docs.rs/axum/0.7.9/axum/extract/type.Request.html Creates a new `Builder` initialized with a GET method and the given URI. This is a convenient way to start building a GET request. ```APIDOC ## Request::get() ### Description Creates a new `Builder` initialized with a GET method and the given URI. ### Method `pub fn get(uri: T) -> Builder` ### Example ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` ``` -------------------------------- ### Example of handling multipart uploads Source: https://docs.rs/axum/0.7.9/axum/extract/multipart/struct.Multipart.html Demonstrates how to use the Multipart extractor to process fields from a multipart/form-data request, including iterating through fields and accessing their data. This example requires the `futures-util` crate. ```rust use axum::{ extract::Multipart, routing::post, Router, }; use futures_util::stream::StreamExt; async fn upload(mut multipart: Multipart) { while let Some(mut field) = multipart.next_field().await.unwrap() { let name = field.name().unwrap().to_string(); let data = field.bytes().await.unwrap(); println!("Length of `{}` is {} bytes", name, data.len()); } } let app = Router::new().route("/upload", post(upload)); ``` -------------------------------- ### Example of setting WebSocket protocols Source: https://docs.rs/axum/0.7.9/axum/extract/ws/struct.WebSocketUpgrade.html Demonstrates how to configure known WebSocket protocols using `protocols` and then upgrade the connection with `on_upgrade`. ```rust use axum::{ extract::ws::{WebSocketUpgrade, WebSocket}, routing::get, response::{IntoResponse, Response}, Router, }; let app = Router::new().route("/ws", get(handler)); async fn handler(ws: WebSocketUpgrade) -> Response { ws.protocols(["graphql-ws", "graphql-transport-ws"]) .on_upgrade(|socket| async { // ... }) } ``` -------------------------------- ### Serve a single MethodRouter with into_make_service Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html Converts a MethodRouter into a `MakeService` for serving when path-based routing is not needed. This example demonstrates serving a router that handles GET and POST requests. ```rust use axum:: handler::Handler, http::{Uri, Method}, response::IntoResponse, routing::get, }; use std::net::SocketAddr; async fn handler(method: Method, uri: Uri, body: String) -> String { format!("received `{method} {uri}` with body `{body:?}`") } let router = get(handler).post(handler); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router.into_make_service()).await.unwrap(); ``` -------------------------------- ### Extracting Path Parameters into a HashMap Source: https://docs.rs/axum/0.7.9/axum/extract/struct.Path.html This example demonstrates capturing all path parameters into a HashMap. ```APIDOC ## GET /users/:user_id/team/:team_id ### Description Captures all path parameters (`user_id` and `team_id`) into a `HashMap`. ### Method GET ### Endpoint /users/:user_id/team/:team_id ### Parameters #### Path Parameters - **user_id** (String) - Captured - The user ID. - **team_id** (String) - Captured - The team ID. ### Request Example ```rust use axum::extract::Path; use std::collections::HashMap; async fn params_map(Path(params): Path>) { // ... } ``` ### Response #### Success Response (200) - The `params` HashMap will contain key-value pairs for all captured path segments. ``` -------------------------------- ### Example Usage of map_response_with_state Source: https://docs.rs/axum/0.7.9/axum/middleware/fn.map_response_with_state.html This example demonstrates how to use `map_response_with_state` to create a middleware that can access application state. The middleware function `my_middleware` receives the state and the response, allowing for modifications. ```rust use axum::{ Router, http::StatusCode, routing::get, response::Response, middleware::map_response_with_state, extract::State, }; #[derive(Clone)] struct AppState { /* ... */ } async fn my_middleware( State(state): State, // you can add more extractors here but they must // all implement `FromRequestParts` // `FromRequest` is not allowed response: Response, ) -> Response { // do something with `state` and `response`... response } let state = AppState { /* ... */ }; let app = Router::new() .route("/", get(|| async { /* ... */ })) .route_layer(map_response_with_state(state.clone(), my_middleware)) .with_state(state); ``` -------------------------------- ### Example of Custom Extractor with FromRequestParts Source: https://docs.rs/axum/0.7.9/axum/extract/derive.FromRequestParts.html This example demonstrates how to create a custom extractor `MyExtractor` using `#[derive(FromRequestParts)]`. It extracts query parameters and a `ContentType` header. ```rust use axum_macros::FromRequestParts; use axum::{ extract::Query, }; use axum_extra::{ TypedHeader, headers::ContentType, }; use std::collections::HashMap; #[derive(FromRequestParts)] struct MyExtractor { #[from_request(via(Query))] query_params: HashMap, content_type: TypedHeader, } async fn handler(extractor: MyExtractor) {} ``` -------------------------------- ### Allocating Box with a custom allocator Source: https://docs.rs/axum/0.7.9/axum/type.BoxError.html Examples of creating a Box using a specific allocator instance. ```rust #![feature(allocator_api)] use std::alloc::System; let five = Box::new_in(5, System); ``` ```rust #![feature(allocator_api)] use std::alloc::System; ``` -------------------------------- ### into_make_service Source: https://docs.rs/axum/0.7.9/axum/routing/struct.Router.html Converts the router into a `MakeService`, which is a `Service` whose response is another service. This is commonly used for starting an Axum server. ```APIDOC ## pub fn into_make_service(self) -> IntoMakeService ### Description Convert this router into a `MakeService`, that is a `Service` whose response is another service. ### Method `into_make_service()` ### Example ```rust use axum::{ routing::get, Router, }; let app = Router::new().route("/", get(|| async {{ "Hi!" }})); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); ``` ``` -------------------------------- ### Example of handling failed WebSocket upgrades Source: https://docs.rs/axum/0.7.9/axum/extract/ws/struct.WebSocketUpgrade.html Shows how to provide a callback to `on_failed_upgrade` to handle errors during the WebSocket upgrade process. ```rust use axum::{ extract::{WebSocketUpgrade}, response::Response, }; async fn handler(ws: WebSocketUpgrade) -> Response { ws.on_failed_upgrade(|error| { report_error(error); }) .on_upgrade(|socket| async { /* ... */ }) } ``` -------------------------------- ### Create a Router with Redirects Source: https://docs.rs/axum/0.7.9/axum/response/struct.Redirect.html This example demonstrates how to use `Redirect::permanent` to set up a route that redirects to a new location. Ensure the target route exists. ```rust use axum::{ routing::get, response::Redirect, Router, }; let app = Router::new() .route("/old", get(|| async { Redirect::permanent("/new") })) .route("/new", get(|| async { "Hello!" })); ``` -------------------------------- ### head Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.head.html Routes HEAD requests to the given handler. See `get` for an example. ```APIDOC ## HEAD ### Description Routes `HEAD` requests to the given handler. ### Method HEAD ### Endpoint (Not specified, but typically inferred from router setup) ### Parameters #### Path Parameters None explicitly defined. #### Query Parameters None explicitly defined. #### Request Body None explicitly defined. ### Request Example (Not provided in source) ### Response #### Success Response (200) (Not specified, but typically an empty body for HEAD requests) #### Response Example (Not provided in source) ``` -------------------------------- ### Basic Axum "Hello, World!" Application Source: https://docs.rs/axum/0.7.9/axum/index.html This is the simplest Axum application, demonstrating how to set up a single route for "/" that responds with "Hello, World!". It requires Tokio's `macros` and `rt-multi-thread` features. ```rust use axum:: routing::get, Router, ; #[tokio::main] async fn main() { // build our application with a single route let app = Router::new().route("/", get(|| async { "Hello, World!" })); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } ``` -------------------------------- ### Function delete Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.delete.html Routes `DELETE` requests to the given handler. See `get` for an example. ```rust pub fn delete(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### RawPathParams Usage Example Source: https://docs.rs/axum/0.7.9/axum/extract/struct.RawPathParams.html This example demonstrates how to use the RawPathParams extractor to access and iterate over raw path parameters from a URL. It shows a basic setup with a Router and a handler function that prints the key-value pairs of the parameters. ```APIDOC ## GET /users/:user_id/team/:team_id ### Description Extracts raw path parameters from the URL without deserializing them. This can be more efficient than using the `Path` extractor if you only need the raw parameter values. ### Method GET ### Endpoint `/users/:user_id/team/:team_id` ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **team_id** (string) - Required - The ID of the team. ### Request Example ```rust use axum::extract::RawPathParams; async fn users_teams_show(params: RawPathParams) { for (key, value) in ¶ms { println!("{key:?} = {value:?}"); } } // Example usage within an Axum application: // let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show)); ``` ### Response #### Success Response (200) - The handler function `users_teams_show` does not return a response body in this example, but it processes the path parameters. #### Error Response - **400 Bad Request**: Returned if any percent-encoded parameters are invalid or if the decoded parameters are not valid UTF-8. ``` -------------------------------- ### Extracting Path Parameters into a Vec Source: https://docs.rs/axum/0.7.9/axum/extract/struct.Path.html This example shows how to capture all path parameters into a Vec of tuples. ```APIDOC ## POST /users/:user_id/team/:team_id ### Description Captures all path parameters (`user_id` and `team_id`) into a `Vec<(String, String)>`. ### Method POST ### Endpoint /users/:user_id/team/:team_id ### Parameters #### Path Parameters - **user_id** (String) - Captured - The user ID. - **team_id** (String) - Captured - The team ID. ### Request Example ```rust use axum::extract::Path; use std::collections::HashMap; async fn params_vec(Path(params): Path>) { // ... } ``` ### Response #### Success Response (200) - The `params` Vec will contain tuples of (key, value) for all captured path segments. ``` -------------------------------- ### Route HEAD requests to a handler Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.head.html Use this function to define a handler for HEAD requests. Refer to the `get` function documentation for usage examples. ```rust pub fn head(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Router State Initialization and Serving Source: https://docs.rs/axum/0.7.9/axum/struct.Router.html Demonstrates initializing a router that requires `AppState`, providing the state using `with_state`, and then serving requests. The router type changes from `Router` to `Router<()>` after the state is provided. ```rust use axum::extract::State; use axum::{Router, routing::get}; struct AppState {} // A router that _needs_ an `AppState` to handle requests let router: Router = Router::new() .route("/", get(|_: State| async {})); // Once we call `Router::with_state` the router isn't missing // the state anymore, because we just provided it // // Therefore the router type becomes `Router<()>`, i.e a router // that is not missing any state let router: Router<()> = router.with_state(AppState {}); // Only `Router<()>` has the `into_make_service` method. // // You cannot call `into_make_service` on a `Router` // because it is still missing an `AppState`. let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); ``` -------------------------------- ### ConnectionNotUpgradable Source: https://docs.rs/axum/0.7.9/axum/extract/ws/rejection/struct.ConnectionNotUpgradable.html This rejection is returned if the connection cannot be upgraded, for example, if the request is HTTP/1.0. It provides methods to get the status code and response body text. ```APIDOC ## Struct ConnectionNotUpgradable Available on **crate feature`ws`** only. Rejection type for `WebSocketUpgrade`. This rejection is returned if the connection cannot be upgraded for example if the request is HTTP/1.0. See MDN for more details about connection upgrades. ### Methods #### `body_text()` * **Description**: Get the response body text used for this rejection. * **Returns**: `String` #### `status()` * **Description**: Get the status code used for this rejection. * **Returns**: `StatusCode` ``` -------------------------------- ### Demonstrating ambiguous Pin conversion Source: https://docs.rs/axum/0.7.9/axum/type.BoxError.html An example of an discouraged From implementation that causes ambiguity when calling Pin::from. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Get Query String from Absolute URI Source: https://docs.rs/axum/0.7.9/axum/extract/struct.OriginalUri.html Extracts the query string from an absolute URI. The query string starts after the '?' and ends before the '#' or end of the URI. ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` -------------------------------- ### Convert Router to MakeService for axum::serve Source: https://docs.rs/axum/0.7.9/axum/routing/struct.Router.html Demonstrates converting a Router into a `MakeService` which is required by `axum::serve`. ```rust use axum::{ routing::get, Router, }; let app = Router::new().route("/", get(|| async {{ "Hi!" }})); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); ``` -------------------------------- ### Route PUT requests with `put` Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.put.html Use this function to define a handler for HTTP PUT requests. Refer to the `get` function documentation for a usage example. ```rust pub fn put(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Serve with Graceful Shutdown and TCP_NODELAY Source: https://docs.rs/axum/0.7.9/axum/serve/struct.WithGracefulShutdown.html Demonstrates how to serve a router with graceful shutdown enabled and configure TCP_NODELAY for accepted connections. This is useful for optimizing network performance on accepted connections. ```rust use axum::{Router, routing::get}; let router = Router::new().route("/", get(|| async { "Hello, World!" })); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router) .with_graceful_shutdown(shutdown_signal()) .tcp_nodelay(true) .await .unwrap(); async fn shutdown_signal() { // ... } ``` -------------------------------- ### Serve IntoFuture Implementation Source: https://docs.rs/axum/0.7.9/axum/serve/struct.Serve.html Allows the `Serve` struct to be converted into a future, enabling it to be used with `await`. This is the primary way to start and run the server. ```APIDOC ## Serve IntoFuture Implementation ### Description Converts the `Serve` struct into a `ServeFuture`, which can be awaited to run the server. ### Method `into_future` ### Returns A `ServeFuture` that represents the running server. ### Type Alias `type Output = Result<(), Error>` `type IntoFuture = ServeFuture` ``` -------------------------------- ### Use RawForm Extractor in Handler Source: https://docs.rs/axum/0.7.9/axum/extract/struct.RawForm.html Example of using the RawForm extractor in an Axum handler. It extracts raw query for GET requests or raw form-encoded body for other methods. ```rust use axum::{ extract::RawForm, routing::get, Router }; async fn handler(RawForm(form): RawForm) {} let app = Router::new().route("/", get(handler)); ``` -------------------------------- ### fn ready_oneshot(self) -> ReadyOneshot Source: https://docs.rs/axum/0.7.9/axum/routing/struct.RouterIntoService.html Yields the service when it is ready to accept a request. ```APIDOC ## fn ready_oneshot(self) -> ReadyOneshot ### Description Yields the service when it is ready to accept a request. ### Method This is a method signature, not an HTTP endpoint. ### Parameters - `self`: The service instance. ### Return Value A `ReadyOneshot` future that yields the service. ``` -------------------------------- ### Axum Router Configuration Source: https://docs.rs/axum/0.7.9/axum/index.html Defines a router with multiple routes, mapping different HTTP methods and paths to specific handler functions. This example shows how to set up routes for GET and POST requests. ```rust use axum::{Router, routing::get}; // our router let app = Router::new() .route("/", get(root)) .route("/foo", get(get_foo).post(post_foo)) .route("/foo/bar", get(foo_bar)); // which calls one of these handlers async fn root() {} async fn get_foo() {} async fn post_foo() {} async fn foo_bar() {} ``` -------------------------------- ### Route POST requests to a service Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.on_service.html This example demonstrates how to use `on_service` to route all POST requests to a specific `tower::Service`. Ensure the service is properly defined and returns a `Response`. ```rust use axum::{ extract::Request, routing::on, Router, body::Body, routing::{MethodFilter, on_service}, }; use http::Response; use std::convert::Infallible; let service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); // Requests to `POST /` will go to `service`. let app = Router::new().route("/", on_service(MethodFilter::POST, service)); ``` -------------------------------- ### Extracting OriginalUri in a Route Handler Source: https://docs.rs/axum/0.7.9/axum/extract/struct.OriginalUri.html Use OriginalUri as a route extractor to get the full request URI, even if the service is nested. This example shows how to access both the stripped `uri` and the original `original_uri`. ```rust use axum::{ routing::get, Router, extract::OriginalUri, http::Uri }; let api_routes = Router::new() .route( "/users", get(|uri: Uri, OriginalUri(original_uri): OriginalUri| async { // `uri` is `/users` // `original_uri` is `/api/users` }), ); let app = Router::new().nest("/api", api_routes); ``` -------------------------------- ### query() Source: https://docs.rs/axum/0.7.9/axum/extract/struct.OriginalUri.html Get the query string of this `Uri`, starting after the `?`. The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI’s scheme and naming authority (if any). ```APIDOC ## pub fn query(&self) -> Option<&str> ### Description Get the query string of this `Uri`, starting after the `?`. ### Method GET (conceptual, as this is a method call) ### Endpoint N/A (method on a struct) ### Parameters None ### Request Example ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` ### Response #### Success Response - `Option<&str>`: The query string of the URI, or None if not present. ``` -------------------------------- ### serve Source: https://docs.rs/axum/0.7.9/axum/serve/index.html Serve the service with the supplied listener. Available on crate feature `tokio` and (crate features `http1` or `http2`) only. ```APIDOC ## serve ### Description Serve the service with the supplied listener. Available on **crate feature `tokio` and (crate features `http1` or `http2`)** only. ### Function Signature ```rust pub async fn serve(listener: L, service: S) -> Result<(), Error> where L: TokioListener + Send + 'static, S: Service + Send + 'static, S::Future: Send + 'static, { // implementation details } ``` ### Parameters * `listener`: A type that implements `TokioListener`, `Send`, and `'static`. This is the network listener to accept incoming connections. * `service`: A `Service` that handles requests and responses. It must be `Send` and `'static`, and its future must also be `Send` and `'static`. ### Returns A `Result` which is `Ok(())` on success or an `Err(Error)` on failure. ``` -------------------------------- ### Define a GET route Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.get.html Use `get` to route GET requests to a handler. Requests to `GET /` will go to `handler`. Note that `HEAD` requests will also be handled by `get` routes, but will have the response body removed. ```rust use axum::routing::get; use axum::Router; async fn handler() {} // Requests to `GET /` will go to `handler`. let app = Router::new().route("/", get(handler)); ``` -------------------------------- ### Chaining GET Handlers Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html Chain an additional handler that only accepts `GET` requests using the `get` method. Note that `HEAD` requests are also handled by `GET` routes but without a response body; explicit `HEAD` routes should be added afterwards. ```rust use axum::{routing::post, Router}; async fn handler() {} async fn other_handler() {} // Requests to `POST /` will go to `handler` and `GET /` will go to // `other_handler`. let app = Router::new().route("/", post(handler).get(other_handler)); ``` -------------------------------- ### into_make_service_with_connect_info Source: https://docs.rs/axum/0.7.9/axum/handler/trait.HandlerWithoutStateExt.html Converts the handler into a MakeService that stores connection info and has no state. Available on `tokio` crate feature. ```APIDOC ## into_make_service_with_connect_info ### Description 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. ### Availability Available on **crate feature`tokio`** only. ### Signature ```rust fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo, C> ``` ``` -------------------------------- ### into_make_service_with_connect_info Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html Converts a service into a `MakeService` that stores `ConnectInfo` in request extensions. Available only on the `tokio` crate feature. ```APIDOC ## fn into_make_service_with_connect_info( self, ) -> IntoMakeServiceWithConnectInfo ### Description Convert this service into a `MakeService`, that will store `C`’s associated `ConnectInfo` in a request extension such that `ConnectInfo` can extract it. ### Available on `crate feature="tokio"` only. ``` -------------------------------- ### get Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/index.html Route `GET` requests to the given handler. ```APIDOC ## GET ### Description Route `GET` requests to the given handler. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Chain a service for GET requests Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html Adds a `Service` to the router that specifically handles `GET` requests. This is a common way to integrate existing `tower::Service` implementations into an Axum application for GET endpoints. ```rust let router = axum::routing::MethodRouter::new().get_service(service); ``` -------------------------------- ### Serve with graceful shutdown Source: https://docs.rs/axum/0.7.9/axum/serve/struct.Serve.html Prepares a server to handle graceful shutdown when a provided future completes. Ensure the shutdown signal is properly implemented. ```rust use axum::{Router, routing::get}; let router = Router::new().route("/", get(|| async { "Hello, World!" })); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router) .with_graceful_shutdown(shutdown_signal()) .await .unwrap(); async fn shutdown_signal() { // ... } ``` -------------------------------- ### Getting Request Method Source: https://docs.rs/axum/0.7.9/axum/extract/type.Request.html Retrieves the HTTP method associated with a request. Defaults to GET. ```rust let request: Request<()> = Request::default(); assert_eq!(*request.method(), Method::GET); ``` -------------------------------- ### fn ready(&mut self) -> Ready<'_, Self, Request> Source: https://docs.rs/axum/0.7.9/axum/routing/struct.RouterIntoService.html Yields a mutable reference to the service when it is ready to accept a request. ```APIDOC ## fn ready(&mut self) -> Ready<'_, Self, Request> ### Description Yields a mutable reference to the service when it is ready to accept a request. ### Method This is a method signature, not an HTTP endpoint. ### Parameters - `self`: A mutable reference to the service. ### Return Value A `Ready` future that yields a mutable reference to the service. ``` -------------------------------- ### Create GET Request Source: https://docs.rs/axum/0.7.9/axum/extract/type.Request.html Conveniently create a `Request` with the GET method using `Request::get()`. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Streaming Field Data Example Source: https://docs.rs/axum/0.7.9/axum/extract/multipart/struct.Field.html Example demonstrating how to stream chunks of data from a multipart field. ```APIDOC ## Streaming Field Data Example ### Description This example shows how to iterate through multipart fields and stream their content in chunks. ### Code ```rust use axum::extract::Multipart; use axum::routing::post; use axum::response::IntoResponse; use axum::http::StatusCode; use axum::Router; async fn upload(mut multipart: Multipart) -> Result<(), (StatusCode, String)> { while let Some(mut field) = multipart .next_field() .await .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))? { while let Some(chunk) = field .chunk() .await .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))? { println!("received {} bytes", chunk.len()); } } Ok(()) } let app = Router::new().route("/upload", post(upload)); ``` ``` -------------------------------- ### Define and Use AppState with Router Source: https://docs.rs/axum/0.7.9/axum/extract/struct.State.html Demonstrates how to define application state, provide it to a `Router` using `with_state`, and access it within a handler using the `State` extractor. Ensure your state type implements `Clone`. ```rust use axum::{Router, routing::get, extract::State}; // the application state // // here you can put configuration, database connection pools, or whatever // state you need // // see "When states need to implement `Clone`" for more details on why we need // `#[derive(Clone)]` here. #[derive(Clone)] struct AppState {} let state = AppState {}; // create a `Router` that holds our state let app = Router::new() .route("/", get(handler)) // provide the state so the router can access it .with_state(state); async fn handler( // access the state via the `State` extractor // extracting a state of the wrong type results in a compile error State(state): State, ) { // use `state`... } ``` -------------------------------- ### RawPathParams Usage Example Source: https://docs.rs/axum/0.7.9/axum/extract/path/struct.RawPathParams.html This example demonstrates how to use RawPathParams to extract and iterate over path parameters from a URL. ```APIDOC ## GET /users/:user_id/team/:team_id ### Description Extracts raw path parameters from the URL without deserializing them. This can be more efficient than the `Path` extractor if you only need the raw values. ### Method GET ### Endpoint `/users/:user_id/team/:team_id` ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **team_id** (string) - Required - The ID of the team. ### Request Example ```rust use axum::extract::RawPathParams; async fn users_teams_show(params: RawPathParams) { for (key, value) in ¶ms { println!("{key:?} = {value:?}"); } } ``` ### Response #### Success Response (200) Returns the raw path parameters as key-value pairs. #### Response Example (No specific response body example provided in source, but conceptually it would be the extracted parameters.) **Note**: Any percent-encoded parameters will be automatically decoded. The decoded parameters must be valid UTF-8, otherwise `RawPathParams` will fail and return a `400 Bad Request` response. ``` -------------------------------- ### into_make_service_with_connect_info Source: https://docs.rs/axum/0.7.9/axum/extract/connect_info/struct.IntoMakeServiceWithConnectInfo.html Converts a service into a MakeService, storing ConnectInfo in request extensions. Available only with the 'tokio' crate feature. ```APIDOC ## fn into_make_service_with_connect_info( self, ) -> IntoMakeServiceWithConnectInfo ### Description Convert this service into a `MakeService`, that will store `C`’s associated `ConnectInfo` in a request extension such that `ConnectInfo` can extract it. ### Method `into_make_service_with_connect_info` ### Feature `tokio` ``` -------------------------------- ### Serve MethodRouter with connection info Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html Converts a MethodRouter into a `MakeService` that captures connection information. This example shows how to access the client's socket address within a handler. ```rust use axum:: handler::Handler, response::IntoResponse, extract::ConnectInfo, routing::get, }; use std::net::SocketAddr; async fn handler(ConnectInfo(addr): ConnectInfo) -> String { format!("Hello {addr}") } let router = get(handler).post(handler); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router.into_make_service()).await.unwrap(); ``` -------------------------------- ### MockConnectInfo Example Usage Source: https://docs.rs/axum/0.7.9/axum/extract/connect_info/struct.MockConnectInfo.html This example demonstrates how to use MockConnectInfo in tests to provide a mocked SocketAddr for a handler that expects ConnectInfo. ```APIDOC ## §Example ```rust use axum::* use axum::extract::connect_info::{MockConnectInfo, ConnectInfo}; use axum::body::Body; use axum::routing::get; use axum::http::{Request, StatusCode}; use std::net::SocketAddr; use tower::ServiceExt; async fn handler(ConnectInfo(addr): ConnectInfo) {} // this router you can run with `app.into_make_service_with_connect_info::()` fn app() -> Router { Router::new().route("/", get(handler)) } // use this router for tests fn test_app() -> Router { app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))) } // #[tokio::test] async fn some_test() { let app = test_app(); let request = Request::new(Body::empty()); let response = app.oneshot(request).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); } ``` ``` -------------------------------- ### Converting Handlers into Services Source: https://docs.rs/axum/0.7.9/axum/handler/trait.Handler.html Demonstrates how to convert handlers into `tower::Service`s using `into_service` for handlers without state and `with_state` for handlers requiring state. ```APIDOC ## Converting `Handler`s into `Service`s To convert `Handler`s into `Service`s you have to call either `HandlerWithoutStateExt::into_service` or `Handler::with_state`: ```rust use tower::Service; use axum::* // this handler doesn't require any state async fn one() {} // so it can be converted to a service with `HandlerWithoutStateExt::into_service` assert_service(one.into_service()); // this handler requires state async fn two(_: State) {} // so we have to provide it let handler_with_state = two.with_state(String::new()); // which gives us a `Service` assert_service(handler_with_state); // helper to check that a value implements `Service` fn assert_service(service: S) where S: Service, {} ``` ``` -------------------------------- ### into_make_service_with_connect_info Source: https://docs.rs/axum/0.7.9/axum/struct.Json.html Convert the handler into a `MakeService` that stores connection info and has no state. Available on `crate feature`tokio` only. ```APIDOC ## fn into_make_service_with_connect_info( self, ) -> IntoMakeServiceWithConnectInfo, C> ### Description Converts the handler into a `MakeService` which stores information about the incoming connection and has no state. This feature requires the `tokio` crate feature to be enabled. ``` -------------------------------- ### Basic Usage of any() Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.any.html This snippet demonstrates how to use the `any` function to route all requests to a specific path to a given handler. ```APIDOC ## POST / ### Description Route requests with the given handler regardless of the method. ### Method ANY ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use axum::{ routing::any, Router, }; async fn handler() {} // All requests to `/` will go to `handler`. let app = Router::new().route("/", any(handler)); ``` ### Response #### Success Response (200) None explicitly defined, depends on handler. #### Response Example None explicitly defined, depends on handler. ``` -------------------------------- ### Serve a Router with axum::serve Source: https://docs.rs/axum/0.7.9/axum/fn.serve.html Use this to serve an Axum `Router` instance. Ensure you have the necessary features enabled. ```rust use axum::{Router, routing::get}; let router = Router::new().route("/", get(|| async { "Hello, World!" })); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); ``` -------------------------------- ### Providing State to Router Source: https://docs.rs/axum/0.7.9/axum/routing/struct.Router.html Demonstrates how to initialize a router that requires state and then provide that state using `with_state`, changing the router type to `Router<()>` which allows it to be served. ```rust use axum::extract::State; use axum::Router; struct AppState {} // A router that _needs_ an `AppState` to handle requests let router: Router = Router::new() .route("/", get(|_: State| async {})); // Once we call `Router::with_state` the router isn't missing // the state anymore, because we just provided it // // Therefore the router type becomes `Router<()>`, i.e a router // that is not missing any state let router: Router<()> = router.with_state(AppState {}); // Only `Router<()>` has the `into_make_service` method. // // You cannot call `into_make_service` on a `Router` // because it is still missing an `AppState`. // let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); // axum::serve(listener, router).await.unwrap(); ``` -------------------------------- ### Fallback Service with MethodRouter::merge - Panic Example Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/struct.MethodRouter.html This example illustrates a scenario where merging two MethodRouters, each with its own fallback service, will result in a panic. This is because a router cannot have multiple fallback services when merged. ```rust use axum::{ routing::{get, post}, handler::Handler, response::IntoResponse, http::{StatusCode, Uri}, }; let one = get(|| async {{}}).fallback(fallback_one); let two = post(|| async {{}}).fallback(fallback_two); let method_route = one.merge(two); async fn fallback_one() -> impl IntoResponse {{ /* ... */ }} async fn fallback_two() -> impl IntoResponse {{ /* ... */ }} ``` -------------------------------- ### any_service with chained methods Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.any_service.html Demonstrates chaining additional methods onto `any_service`. ```APIDOC ## any_service with chained methods ### Description Additional methods can still be chained to `any_service`. ### Method Any (default), specific methods for chained services. ### Endpoint Any ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use axum::{ extract::Request, Router, routing::any_service, body::Body, }; use http::Response; use std::convert::Infallible; let service = tower::service_fn(|request: Request| async { // ... }); let other_service = tower::service_fn(|request: Request| async { // ... }); // `POST /` goes to `other_service`. All other requests go to `service` let app = Router::new().route("/", any_service(service).post_service(other_service)); ``` ### Response #### Success Response (200) Depends on the provided services. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### get_service Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.get_service.html Routes GET requests to a provided service. Note that HEAD requests are also handled by GET routes, but their response bodies are removed. Explicit HEAD routes should be added afterwards if needed. ```APIDOC ## get_service ### Description Routes `GET` requests to the given service. ### Method GET ### Endpoint `/` (example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use axum::{ extract::Request, Router, routing::get_service, body::Body, }; use http::Response; use std::convert::Infallible; let service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); // Requests to `GET /` will go to `service`. let app = Router::new().route("/", get_service(service)); ``` ### Response #### Success Response (200) Depends on the `Service` implementation. #### Response Example ```json { "example": "response body" } ``` Note that `get` routes will also be called for `HEAD` requests but will have the response body removed. Make sure to add explicit `HEAD` routes afterwards. ``` -------------------------------- ### Serve a MethodRouter with axum::serve Source: https://docs.rs/axum/0.7.9/axum/fn.serve.html This snippet demonstrates serving a single `MethodRouter` using `axum::serve`. It's suitable for simpler endpoints. ```rust use axum::routing::get; let router = get(|| async { "Hello, World!" }); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); ``` -------------------------------- ### Get Message as Text Slice Source: https://docs.rs/axum/0.7.9/axum/extract/ws/enum.Message.html Attempts to get a &str from the WebSocket message. This method will try to convert binary data to UTF-8. Returns a Result which is Ok if the conversion is successful, or an Error otherwise. ```rust pub fn to_text(&self) -> Result<&str, Error> ``` -------------------------------- ### into_make_service_with_connect_info Source: https://docs.rs/axum/0.7.9/axum/struct.Form.html Converts the handler into a `MakeService` which stores information about the incoming connection and has no state. Available on `tokio` feature only. ```APIDOC ## fn into_make_service_with_connect_info( self, ) -> IntoMakeServiceWithConnectInfo, C> ### Description Converts the handler into a `MakeService` which stores information about the incoming connection and has no state. ### Available On `crate feature`tokio` only. ### Source [Source Link] ``` -------------------------------- ### GET Method Router Source: https://docs.rs/axum/0.7.9/axum/routing/method_routing/fn.get.html This function creates a router that responds to GET requests. It also handles HEAD requests by default, but without a response body. Explicit HEAD routes should be added afterwards if needed. ```APIDOC ## GET / ### Description Route `GET` requests to the given handler. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use axum::routing::get; async fn handler() {} let app = Router::new().route("/", get(handler)); ``` ### Response #### Success Response (200) - The response depends on the handler implementation. #### Response Example None provided in source. ```