### Basic Axum App Setup Source: https://docs.rs/axum/latest/axum/attr.debug_handler.html A standard Axum application setup with a basic handler function. This example demonstrates the context in which `debug_handler` is typically used. ```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" } ``` -------------------------------- ### Comprehensive Router Configuration Example Source: https://docs.rs/axum/latest/axum/routing/struct.Router.html An example demonstrating the definition of multiple routes with static paths, captures, wildcards, and handling of different HTTP methods. ```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) {} ``` -------------------------------- ### Multipart Example Source: https://docs.rs/axum/latest/axum/extract/struct.Multipart.html An example demonstrating how to use the Multipart extractor to process uploaded files. ```APIDOC ## §Example ```rust use axum::* use axum::extract::Multipart; use axum::routing::post; use axum::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)); ``` ``` -------------------------------- ### Axum Router Example with Multiple Routes Source: https://docs.rs/axum/latest/axum/struct.Router.html A comprehensive example demonstrating the definition of various routes including static paths, captures, and wildcards, along with handlers for different HTTP methods. ```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) {{}} ``` -------------------------------- ### Define Router with RawQuery Handler Source: https://docs.rs/axum/latest/axum/extract/struct.RawQuery.html This example shows how to integrate a handler that uses the `RawQuery` extractor into an axum `Router`. It demonstrates setting up a GET route for `/users` that will invoke the `handler` function. ```rust use axum::routing::get; use axum::Router; let app = Router::new().route("/users", get(handler)); ``` -------------------------------- ### Example: Different Limits for Different Routes Source: https://docs.rs/axum/latest/axum/extract/struct.DefaultBodyLimit.html This example shows how to apply different body limits to specific routes within an Axum application. ```APIDOC ## §Different limits for different routes `DefaultBodyLimit` can also be selectively applied to have different limits for different routes: ```rust use axum::{ Router, routing::post, body::Body, extract::{Request, DefaultBodyLimit}, }; let app = Router::new() // this route has a different limit .route("/", post(|request: Request| async {{}})).layer(DefaultBodyLimit::max(1024)) // this route still has the default limit .route("/foo", post(|request: Request| async {{}})); ``` ``` -------------------------------- ### Response Example Source: https://docs.rs/axum/latest/axum/response/type.Response.html Example usage of the Response struct, demonstrating response creation and body mapping. ```APIDOC ## Examples ```rust let response = Response::builder().body("some string").unwrap(); let mapped_response: Response<&[u8]> = response.map(|b| { assert_eq!(b, "some string"); b.as_bytes() }); assert_eq!(mapped_response.body(), &"some string".as_bytes()); ``` ``` -------------------------------- ### Example: Setting a Default Body Limit Source: https://docs.rs/axum/latest/axum/extract/struct.DefaultBodyLimit.html This example demonstrates how to set a custom default body limit for all routes in an Axum application. ```APIDOC ## §Example ```rust use axum::{ Router, routing::post, body::Body, extract::{Request, DefaultBodyLimit}, }; let app = Router::new() .route("/", post(|request: Request| async {{}})) // change the default limit .layer(DefaultBodyLimit::max(1024)); ``` ``` -------------------------------- ### Axum Router with Response Handlers Source: https://docs.rs/axum/latest/axum/index.html Example of an Axum Router setup that includes routes for both plain text and JSON responses. ```rust use axum::{ body::Body, routing::get, response::Json, Router, }; use serde_json::{Value, json}; // `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8` async fn plain_text() -> &'static str { "foo" } // `Json` gives a content-type of `application/json` and works with any type // that implements `serde::Serialize` async fn json() -> Json { Json(json!({ "data": 42 })) } let app = Router::new() .route("/plain_text", get(plain_text)) .route("/json", get(json)); ``` -------------------------------- ### Create GET Request Source: https://docs.rs/axum/latest/axum/extract/type.Request.html Use `Request::get()` to quickly create a `Builder` initialized with the GET method and a specified URI. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Converting Handlers into Services Source: https://docs.rs/axum/latest/axum/handler/trait.Handler.html Examples of converting handlers into services using `into_service` and `with_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::{ extract::{State, Request}, body::Body, handler::{HandlerWithoutStateExt, Handler}, }; // 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, {} ``` ``` -------------------------------- ### MockConnectInfo Example Usage in Tests Source: https://docs.rs/axum/latest/axum/extract/connect_info/struct.MockConnectInfo.html Demonstrates how to use MockConnectInfo to mock SocketAddr for testing axum applications. This setup is for tests, while Router::into_make_service_with_connect_info is used for running the application. ```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); } ``` -------------------------------- ### Example: Asserting Error Status Source: https://docs.rs/axum/latest/axum/test_helpers/struct.TestResponse.html This example demonstrates how to use `error_for_status_ref` to check if a response resulted in an error, specifically asserting a 400 Bad Request status code. ```rust fn on_response(res: &Response) { match res.error_for_status_ref() { Ok(_res) => (), Err(err) => { // asserting a 400 as an example // it could be any status between 400...599 assert_eq!( err.status(), Some(reqwest::StatusCode::BAD_REQUEST) ); } } } ``` -------------------------------- ### Example Custom Extractor with FromRequestParts Source: https://docs.rs/axum/latest/axum/extract/derive.FromRequestParts.html This example shows how to define a custom extractor `MyExtractor` using `#[derive(FromRequestParts)]` to extract 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) {} ``` -------------------------------- ### Axum "Hello, World!" Example Source: https://docs.rs/axum/latest/axum/index.html A basic "Hello, World!" application using Axum. Requires tokio with 'macros' and 'rt-multi-thread' features enabled. ```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(); } ``` -------------------------------- ### Get String Slice Ranges Source: https://docs.rs/axum/latest/axum/extract/ws/struct.Utf8Bytes.html This example demonstrates how to obtain `Range` objects representing the start and end indices of substrings within a larger string using `substr_range`. Note that `substr_range` is an experimental nightly-only feature. ```rust #![feature(substr_range)] use core::range::Range; let data = "a, b, b, a"; let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 1 })); assert_eq!(iter.next(), Some(Range { start: 3, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 6, end: 7 })); assert_eq!(iter.next(), Some(Range { start: 9, end: 10 })); ``` -------------------------------- ### Create a Router with Redirect Routes Source: https://docs.rs/axum/latest/axum/response/struct.Redirect.html Example of setting up routes that return a permanent redirect. Ensure axum is imported. ```rust use axum:: routing::get, response::Redirect, Router, ; let app = Router::new() .route("/old", get(|| async { Redirect::permanent("/new") })) .route("/new", get(|| async { "Hello!" })); ``` -------------------------------- ### Axum Query Extractor Source: https://docs.rs/axum/latest/axum/index.html Example of using the `Query` extractor to get query parameters and deserialize them. ```rust use axum::extract::Query; use std::collections::HashMap; // `Query` gives you the query parameters and deserializes them. async fn query(Query(params): Query>) {} ``` -------------------------------- ### Axum Router Setup Source: https://docs.rs/axum/latest/axum/index.html Demonstrates setting up a basic Axum Router with multiple routes and associated handlers. ```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() {} ``` -------------------------------- ### Axum Path Extractor Source: https://docs.rs/axum/latest/axum/index.html Example of using the `Path` extractor to get path parameters and deserialize them. ```rust use axum::extract::Path; // `Path` gives you the path parameters and deserializes them. async fn path(Path(user_id): Path) {} ``` -------------------------------- ### match_indices: Iterate over matches and their start indices Source: https://docs.rs/axum/latest/axum/extract/ws/struct.Utf8Bytes.html Use `match_indices` to get an iterator over tuples containing the start index and the matched string slice for each non-overlapping occurrence of a pattern. Overlapping matches are not included. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); ``` ```rust let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); ``` ```rust let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Router Creation and Configuration Source: https://docs.rs/axum/latest/axum/struct.Router.html Demonstrates how to create a new router and configure it to disable compatibility checks with older versions. ```APIDOC ## Router Creation and Configuration ### Description This section covers the creation of a new `Router` instance and how to optionally disable compatibility checks for route matching syntax from version 0.7. ### Methods #### `new()` Creates a new `Router`. #### `without_v07_checks()` Turns off checks for compatibility with route matching syntax from 0.7. This allows usage of paths starting with a colon `:` or an asterisk `*` which are otherwise prohibited. Adding such routes without calling this method first will panic. ### Request Example ```rust use axum::Router; let app = Router::<()>::new().without_v07_checks(); ``` ### Response Returns a `Router` instance. ``` -------------------------------- ### Route HEAD requests Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.head.html Use this function to route HEAD requests to a handler. See `get` for an example. ```rust pub fn head(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Serve with Client Address using `into_make_service_with_connect_info` Source: https://docs.rs/axum/latest/axum/struct.Router.html Employ `into_make_service_with_connect_info` to enable extracting connection information, such as the client's remote address, into request extensions. Requires the `tokio` feature. ```rust use axum::{ extract::ConnectInfo, routing::get, Router, }; use std::net::SocketAddr; let app = Router::new().route("/", get(handler)); async fn handler(ConnectInfo(addr): ConnectInfo) -> String { format!("Hello {{addr}}") } let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); ``` ```rust use axum::{ extract::connect_info::{ConnectInfo, Connected}, routing::get, serve::IncomingStream, Router, }; use tokio::net::TcpListener; let app = Router::new().route("/", get(handler)); async fn handler( ConnectInfo(my_connect_info): ConnectInfo, ) -> String { format!("Hello {{my_connect_info:?}}") } #[derive(Clone, Debug)] struct MyConnectInfo { // ... } impl Connected> for MyConnectInfo { fn connect_info(target: IncomingStream<'_, TcpListener>) -> Self { MyConnectInfo { // ... } } } let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); ``` -------------------------------- ### Get Query String from Absolute URI Source: https://docs.rs/axum/latest/axum/extract/struct.OriginalUri.html Extracts the query string component from an absolute URI, which starts after the '?' and ends before the '#'. ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` -------------------------------- ### MethodFilter Constants Source: https://docs.rs/axum/latest/axum/routing/struct.MethodFilter.html Use these constants to match specific HTTP methods. For example, to match only GET requests, use `MethodFilter::GET`. ```rust pub const CONNECT: Self ``` ```rust pub const DELETE: Self ``` ```rust pub const GET: Self ``` ```rust pub const HEAD: Self ``` ```rust pub const OPTIONS: Self ``` ```rust pub const PATCH: Self ``` ```rust pub const POST: Self ``` ```rust pub const PUT: Self ``` ```rust pub const TRACE: Self ``` -------------------------------- ### Serve a MethodRouter with Axum Source: https://docs.rs/axum/latest/axum/fn.serve.html Example of serving a single Axum MethodRouter using the `serve` function. Useful 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(); ``` -------------------------------- ### Route OPTIONS requests to a handler Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.options.html Use this function to route HTTP OPTIONS requests to a specific handler. See `get` for an example of usage. ```rust pub fn options(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Result expect() Example - Environment Variable Source: https://docs.rs/axum/latest/axum/response/type.Result.html Shows a practical use case for `expect()` in retrieving environment variables, providing a descriptive message if the variable is not set. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Merge routers with fallbacks (panic) Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Merging two routers that both have fallback services will result in a panic. This example demonstrates the setup that leads to this panic. ```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 { /* ... */ } ``` -------------------------------- ### Route PUT requests with axum::routing::method_routing::put Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.put.html Use this function to route `PUT` requests to a specified handler. See `get` for an example. ```rust pub fn put(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Provided Methods: `with_state` Source: https://docs.rs/axum/latest/axum/handler/trait.Handler.html Shows how to convert a handler into a `Service` by providing state using the `with_state` method. ```APIDOC #### fn with_state(self, state: S) -> HandlerService Convert the handler into a `Service` by providing the state ``` -------------------------------- ### Route PATCH requests with axum::routing::method_routing::patch Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.patch.html Use this function to route PATCH requests to a specific handler. See `get` for an example. ```rust pub fn patch(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Create OPTIONS Request Source: https://docs.rs/axum/latest/axum/extract/type.Request.html Use `Request::options()` to quickly create a `Builder` initialized with the OPTIONS method and a specified URI. ```rust let request = Request::options("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Route CONNECT requests with connect Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.connect.html Use this function to route CONNECT requests to a handler. See MethodFilter::CONNECT for usage scenarios and get for an example. ```rust pub fn connect(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Result iter() Example Source: https://docs.rs/axum/latest/axum/response/type.Result.html Shows how to use the `iter()` method to get an iterator over the `Ok` value of a Result. The iterator yields one item if `Ok`, and is empty if `Err`. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); ``` ```rust let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Axum Required Dependencies Source: https://docs.rs/axum/latest/axum/index.html Lists the essential dependencies for using the Axum web framework. The 'full' feature for Tokio is recommended for ease of setup, and Tower is helpful for testing. ```toml [dependencies] axum = "" tokio = { version = "", features = ["full"] } tower = "" ``` -------------------------------- ### Route DELETE requests with axum::routing::method_routing::delete Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.delete.html Use this function to route HTTP DELETE requests to a specific handler. See `get` for an example of usage. ```rust pub fn delete(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Serve a Router with Axum Source: https://docs.rs/axum/latest/axum/fn.serve.html Example of serving an Axum Router using the `serve` function. This is suitable for applications with defined routes. ```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(); ``` -------------------------------- ### FromFn Service with 7 Arguments Source: https://docs.rs/axum/latest/axum/middleware/struct.FromFn.html Documentation for the `Service` implementation of `FromFn` when it takes seven arguments, including its operational methods and types. ```APIDOC ## impl Service> for FromFn ### Description This `Service` implementation is designed for `FromFn` closures that accept seven arguments. It manages request processing and response generation. ### Method `call` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Request object is processed" } ``` ### Response #### Success Response (200) - **Response** (type) - The response from the service. #### Response Example ```json { "example": "Response object" } ``` ### Error Handling - **Error Type**: `Infallible` ### Readiness Check - **Method**: `poll_ready` - **Description**: Checks if the service is ready to accept requests. ``` -------------------------------- ### Define Custom Extractor with RequestPartsExt Source: https://docs.rs/axum/latest/axum/trait.RequestPartsExt.html Implement a custom extractor that uses `extract` to get path and query parameters from request parts. This example shows how to combine multiple extractors within a single custom struct. ```rust use axum::{ extract::{Query, Path, FromRequestParts}, response::{Response, IntoResponse}, http::request::Parts, RequestPartsExt, }; use std::collections::HashMap; struct MyExtractor { path_params: HashMap, query_params: HashMap, } impl FromRequestParts where S: Send + Sync, { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { let path_params = parts .extract::>>() .await .map(|Path(path_params)| path_params) .map_err(|err| err.into_response())?; let query_params = parts .extract::>>() .await .map(|Query(params)| params) .map_err(|err| err.into_response())?; Ok(MyExtractor { path_params, query_params }) } } ``` -------------------------------- ### Route POST requests with axum::routing::method_routing::post Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.post.html Use this function to define a route that specifically handles POST requests. It requires a handler that conforms to the Handler trait. See `get` for an example of usage. ```rust pub fn post(handler: H) -> MethodRouter where H: Handler, T: 'static, S: Clone + Send + Sync + 'static, ``` -------------------------------- ### Capture All Path Parameters into HashMap Source: https://docs.rs/axum/latest/axum/extract/path/struct.Path.html Example of capturing all available path parameters into a HashMap, where keys are parameter names and values are their string representations. ```rust use axum::{ extract::Path, routing::get, Router, }; use std::collections::HashMap; async fn params_map( Path(params): Path>, ) { // ... } ``` -------------------------------- ### Chain a service for GET requests Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Chains a service that will only accept `GET` requests. ```rust let router = MethodRouter::new().get_service(service); ``` -------------------------------- ### Get Type ID of a Value Source: https://docs.rs/axum/latest/axum/middleware/future/struct.FromExtractorResponseFuture.html Gets the `TypeId` of a value. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### FromFn Service with 5 Arguments Source: https://docs.rs/axum/latest/axum/middleware/struct.FromFn.html This section details the `Service` implementation for `FromFn` when it accepts five arguments. It outlines the response and error types, future response, and the methods for checking readiness and calling the service. ```APIDOC ## impl Service> for FromFn ### Description This `Service` implementation handles requests using a closure `F` that accepts five arguments, along with an inner service `I` and a state `S`. ### Method `call` ### Endpoint N/A (This is a service implementation, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (The `Request` object itself is processed) ### Request Example ```json { "example": "Request object is processed by the service" } ``` ### Response #### Success Response (200) - **Response** (type) - The response generated by the service. #### Response Example ```json { "example": "Response object" } ``` ### Error Handling - **Error Type**: `Infallible` - Indicates that this service will not produce errors. ### Readiness Check - **Method**: `poll_ready` - **Description**: Returns `Poll::Ready(Ok(()))` when the service is ready to process requests. ``` -------------------------------- ### Serve Axum App with ConnectInfo using Router::into_make_service_with_connect_info Source: https://docs.rs/axum/latest/axum/routing/struct.Router.html Use `into_make_service_with_connect_info` to enable extracting connection information, such as the client's remote address, into request extensions. This requires specifying the type that will hold the connection info. ```rust use axum::extract::ConnectInfo; use axum::routing::get; use axum::Router; use std::net::SocketAddr; let app = Router::new().route("/", get(handler)); async fn handler(ConnectInfo(addr): ConnectInfo) -> String { format!("Hello {{addr}}") } let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); ``` ```rust use axum::extract::connect_info::{ConnectInfo, Connected}; use axum::routing::get; use axum::serve::IncomingStream; use axum::Router; use tokio::net::TcpListener; let app = Router::new().route("/", get(handler)); async fn handler( ConnectInfo(my_connect_info): ConnectInfo, ) -> String { format!("Hello {{my_connect_info:?}}") } #[derive(Clone, Debug)] struct MyConnectInfo { // ... } impl Connected> for MyConnectInfo { fn connect_info(target: IncomingStream<'_, TcpListener>) -> Self { MyConnectInfo { // ... } } } let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); ``` -------------------------------- ### GET Service Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Chains an additional service that will only accept `GET` requests. Note that `GET` routes will also be called for `HEAD` requests but will have the response body removed. Explicit `HEAD` routes should be added afterwards if needed. ```APIDOC ## GET /api/resource ### Description Retrieves a specific resource. ### Method GET ### Endpoint /api/resource ### Response #### Success Response (200) - **data** (object) - The requested resource data #### Response Example { "data": { "id": 1, "name": "Example Resource" } } ``` -------------------------------- ### Serve MethodRouter with Connection Info using MakeService Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Converts a MethodRouter into a MakeService that captures connection information. Requires `tokio` feature. ```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(); ``` -------------------------------- ### GET Request Routing Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.get.html Routes `GET` requests to the specified handler. Note that `HEAD` requests are also handled by `GET` routes, but the response body will be removed. Explicit `HEAD` routes should be added afterwards if needed. ```APIDOC ## GET / ### Description Routes `GET` requests to the given handler. ### Method GET ### Endpoint / ### Parameters This endpoint does not have explicit path or query parameters. ### Request Body This endpoint does not have a request body. ### Request Example ```rust use axum::routing::get; async fn handler() {} // Requests to `GET /` will go to `handler`. let app = Router::new().route("/", get(handler)); ``` ### Response #### Success Response (200) - The response depends on the handler function. #### Response Example (Depends on the handler implementation) ``` -------------------------------- ### Get Request Method Source: https://docs.rs/axum/latest/axum/extract/type.Request.html Retrieves the HTTP method of a request. Defaults to GET if not explicitly set. ```rust let request: Request<()> = Request::default(); assert_eq!(*request.method(), Method::GET); ``` -------------------------------- ### POST / - Route requests to a service Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.on_service.html This example demonstrates how to use `on_service` to route POST requests to a specific service. The `service_fn` creates a simple service that always returns an empty response. ```APIDOC ## POST / - Route requests to a service ### Description Routes requests with the specified HTTP method (POST in this case) to a given service. The service is a `tower::Service` that handles the request and returns a response. ### Method POST ### Endpoint / ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **body** (string) - The response body from the service. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Clone Box using Box::clone_from_ref_in Source: https://docs.rs/axum/latest/axum/type.BoxError.html Demonstrates cloning a Box using the experimental `clone_from_ref_in` function. Requires nightly Rust and the `allocator_api` feature. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::clone_from_ref_in("hello", System); ``` -------------------------------- ### Get string slice from Utf8Bytes Source: https://docs.rs/axum/latest/axum/extract/ws/struct.Utf8Bytes.html Use `as_str` to get a string slice view of the Utf8Bytes content. ```rust pub fn as_str(&self) -> &str ``` -------------------------------- ### Chain additional methods with axum::routing::any Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.any.html This example shows how to use `any` for a default handler and then specify a different handler for a specific method like POST. Ensure axum is imported. ```rust use axum::{ routing::any, Router, }; async fn handler() {} 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)); ``` -------------------------------- ### Serve a Handler with Axum Source: https://docs.rs/axum/latest/axum/fn.serve.html Example of serving a standalone Axum Handler using the `serve` function. This is for cases where you have a single async function acting as the service. ```rust use axum::handler::HandlerWithoutStateExt; async fn handler() -> &'static str { "Hello, World!" } let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, handler.into_make_service()).await.unwrap(); ``` -------------------------------- ### Constructing Query Extractor from URI Source: https://docs.rs/axum/latest/axum/extract/struct.Query.html This example demonstrates how to manually construct a `Query` extractor from an existing `http::Uri`. This can be useful for testing or when dealing with URIs directly. The target type must implement `serde::Deserialize`. ```rust use axum::extract::Query; use http::Uri; use serde::Deserialize; #[derive(Deserialize)] struct ExampleParams { foo: String, bar: u32, } 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); ``` -------------------------------- ### Serve HTTP with Graceful Shutdown Source: https://docs.rs/axum/latest/axum/serve/struct.Serve.html Use this to start an axum server that can be gracefully shut down. Ensure the `tokio` and (`http1` or `http2`) features are enabled. The `shutdown_signal` future must be `Send` and `'static`. ```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() { // ... } ``` -------------------------------- ### axum::serve Source: https://docs.rs/axum/latest/axum/serve/struct.Serve.html The `serve` function is used to start an Axum server. It returns a `Serve` future that can be further configured for graceful shutdown. ```APIDOC ## Serve axum::serve ### Description Future returned by `serve`. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters This section is not applicable as `serve` is a function call, not an HTTP endpoint. ### Request Example ```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() { // ... } ``` ### Response #### Success Response (200) Not applicable (function call returns a future) #### Response Example Not applicable (function call returns a future) ``` -------------------------------- ### MethodRouter::get Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Chains a handler that only accepts GET requests. Note that HEAD requests are also handled by GET routes but with the response body removed. ```APIDOC ## GET / ### Description Chains an additional handler that will only accept `GET` requests. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ### Example Usage ```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)); ``` ``` -------------------------------- ### Get subslice of Utf8Bytes Source: https://docs.rs/axum/latest/axum/extract/ws/struct.Utf8Bytes.html Use `get` for a non-panicking way to retrieve a subslice of Utf8Bytes. It returns `None` if the indices are invalid or not on UTF-8 sequence boundaries. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### Create CONNECT Request Source: https://docs.rs/axum/latest/axum/extract/type.Request.html Use `Request::connect()` to quickly create a `Builder` initialized with the CONNECT method and a specified URI. ```rust let request = Request::connect("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Adding Routes to Router Source: https://docs.rs/axum/latest/axum/routing/struct.Router.html Demonstrates how to add routes to a router, including static paths, captures, and wildcards. ```APIDOC ## Router::route ### Description Adds a new route to the router. A route consists of a `path` and a `method_router` which handles requests matching that path. ### Method `Router::route(path: &str, method_router: MethodRouter) -> Self` ### Endpoint N/A (Method on Router instance) ### Parameters - **path** (string) - Required - The path string for the route. - **method_router** (MethodRouter) - Required - The handler for the route. ### Request Body None ### Response - **Self** (Router) - The router instance with the new route added. ### Path Types: #### Static Paths Exact path matches. - Examples: `/`, `/foo`, `/users/123` #### Captures Segments like `/{key}` match any single segment and capture its value. - Examples: `/{key}`, `/users/{id}`, `/users/{id}/tweets` - Captured values can be extracted using `axum::extract::Path`. #### Wildcards Paths ending in `/{*key}` match all remaining segments. - Examples: `/{*key}`, `/assets/{*path}`, `/{id}/{repo}/{*tree}` - Note: `/{*key}` does not match empty segments. - Captured values can be extracted using `axum::extract::Path`. ### Request Example (Adding Routes) ```rust use axum::{Router, routing::get, 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) {} ``` ### Response Example (Router instance with routes) ``` -------------------------------- ### Route GET requests to a service Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.get_service.html Use `get_service` to route incoming GET requests to a custom service. Ensure the service implements `tower::Service` and is `Clone`, `Send`, and `Sync`. Note that `HEAD` requests are also handled by `GET` routes but with an empty body; explicit `HEAD` routes may be needed. ```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)); ``` -------------------------------- ### Implement PolicyExt::and Source: https://docs.rs/axum/latest/axum/extract/multipart/struct.InvalidBoundary.html Creates a new policy that requires both `self` and `other` policies to return `Action::Follow`. ```rust fn and(self, other: P) -> And where T: Policy, P: Policy ``` -------------------------------- ### Implement PolicyExt::or Source: https://docs.rs/axum/latest/axum/extract/multipart/struct.InvalidBoundary.html Creates a new policy that returns `Action::Follow` if either `self` or `other` policy returns `Action::Follow`. ```rust fn or(self, other: P) -> Or where T: Policy, P: Policy ``` -------------------------------- ### Router Creation and Configuration Source: https://docs.rs/axum/latest/axum/routing/struct.Router.html This snippet covers the creation of a new Router and disabling compatibility checks for older route matching syntax. ```APIDOC ## Router Creation and Configuration ### Description Creates a new `Router` instance. By default, it responds with `404 Not Found` to all requests until routes are added. The `without_v07_checks` method can be used to disable checks for compatibility with route matching syntax from 0.7, allowing the use of paths starting with a colon `:` or an asterisk `*`. ### Method `Router::new()` ### Endpoint N/A (Constructor) ### Parameters None ### Request Body None ### Response - **Self** (Router) - A new `Router` instance. ### Request Example ```rust use axum::Router; let app = Router::<()>::new(); ``` ### Response Example (Router instance) ## Router::without_v07_checks ### Description Turns off checks for compatibility with route matching syntax from 0.7. This allows usage of paths starting with a colon `:` or an asterisk `*` which are otherwise prohibited and would cause a panic. ### Method `Router::without_v07_checks()` ### Endpoint N/A (Method on Router instance) ### Parameters None ### Request Body None ### Response - **Self** (Router) - The router instance with v0.7 checks disabled. ### Request Example ```rust use axum::Router; let app = Router::<()>::new().without_v07_checks(); ``` ### Response Example (Router instance with checks disabled) ``` -------------------------------- ### Routing GET and POST Requests Source: https://docs.rs/axum/latest/axum/routing/method_routing/struct.MethodRouter.html Illustrates how to chain handlers for different HTTP methods using `MethodRouter`. `POST /` requests are handled by `handler`, and `GET /` requests are handled by `other_handler`. ```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)); ``` -------------------------------- ### Create POST Request Source: https://docs.rs/axum/latest/axum/extract/type.Request.html Use `Request::post()` to quickly create a `Builder` initialized with the POST method and a specified URI. ```rust let request = Request::post("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### GET / Route Source: https://docs.rs/axum/latest/axum/routing/method_routing/fn.get_service.html Routes GET requests to the specified service. Note that HEAD requests are also handled, but the response body is removed. Explicit HEAD routes should be added afterwards. ```APIDOC ## GET / ### Description Routes `GET` requests to the given service. ### Method GET ### Endpoint / ### Parameters ### Request Body ### 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) - **body** (Body) - The response body from the service. #### Response Example ```json { "example": "response body" } ``` ```