### Option::take example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Takes the value out of the option, leaving None in its place. The example shows taking from Some(2) and from None. ```rust let mut x = Some(2); let y = x.take(); assert_eq!(x, None); assert_eq!(y, Some(2)); let mut x: Option = None; let y = x.take(); assert_eq!(x, None); assert_eq!(y, None); ``` -------------------------------- ### into_range_response example Source: https://docs.rs/axum-extra/latest/axum_extra/response/file_stream/struct.FileStream.html Builds a range response by seeking to byte 10 and calling into_range_response with start, end, and total size. The handler returns a 404 with a custom message on file open, metadata, or seek errors. ```rust use axum::{ http::StatusCode, response::IntoResponse, routing::get, Router, }; use axum_extra::response::file_stream::FileStream; use tokio::fs::File; use tokio::io::AsyncSeekExt; use tokio_util::io::ReaderStream; async fn range_response() -> Result { let mut file = File::open("test.txt") .await .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}")))?; let mut file_size = file .metadata() .await .map_err(|e| (StatusCode::NOT_FOUND, format!("Get file size: {e}")))? .len(); file.seek(std::io::SeekFrom::Start(10)) .await .map_err(|e| (StatusCode::NOT_FOUND, format!("File seek error: {e}")))?; let stream = ReaderStream::new(file); Ok(FileStream::new(stream).into_range_response(10, file_size - 1, file_size)) } let app = Router::new().route("/file-stream", get(range_response)); ``` -------------------------------- ### Option::as_slice example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::as_slice, showing how to get a slice of the contained value. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` -------------------------------- ### Option::as_mut example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::as_mut, showing how to convert &mut Option to Option<&mut T>. ```rust let mut x = Some(2); match x.as_mut() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### Valid path example Source: https://docs.rs/axum-extra/latest/axum_extra/macro.vpath.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example will compile without problems. The path uses the valid syntax with curly braces for parameters. ```rust use axum::routing::{Router, get}; use axum_extra::vpath; let router = axum::Router::<()>::new() .route(vpath!("/valid_path/{id}"), get(root)) .to_owned(); async fn root() {} ``` -------------------------------- ### try_range_response example Source: https://docs.rs/axum-extra/latest/axum_extra/response/file_stream/struct.FileStream.html Attempts a range request directly from a file path with start and end positions. If end is 0 it is treated as file_size - 1, and if start exceeds file_size or end, a Range Not Satisfiable response is returned. ```rust use axum::{ http::StatusCode, response::IntoResponse, Router, routing::get }; use std::path::Path; use axum_extra::response::file_stream::FileStream; use tokio::fs::File; use tokio_util::io::ReaderStream; use tokio::io::AsyncSeekExt; async fn range_stream() -> impl IntoResponse { let range_start = 0; let range_end = 1024; FileStream::>::try_range_response("CHANGELOG.md", range_start, range_end).await .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}"))) } let app = Router::new().route("/file-stream", get(range_stream)); ``` -------------------------------- ### Option::as_ref example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::as_ref, showing how to convert &Option to Option<&T> without moving the value. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {text:?}"); ``` -------------------------------- ### Option::is_none example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::is_none, showing how to check if an Option is None. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### CookieJar extractor example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.CookieJar.html?search=std%3A%3Avec Example usage of CookieJar as an extractor. It shows how to add a cookie to the jar and return it from the handler so the changes are propagated. It also demonstrates reading a cookie with `jar.get`. The example requires the `cookie` feature. ```rust use axum::{ Router, routing::{post, get}, response::{IntoResponse, Redirect}, http::StatusCode, }; use axum_extra::{ TypedHeader, headers::authorization::{Authorization, Bearer}, extract::cookie::{CookieJar, Cookie}, }; async fn create_session( TypedHeader(auth): TypedHeader>, jar: CookieJar, ) -> Result<(CookieJar, Redirect), StatusCode> { if let Some(session_id) = authorize_and_create_session(auth.token()).await { Ok(( // the updated jar must be returned for the changes // to be included in the response jar.add(Cookie::new("session_id", session_id)), Redirect::to("/me"), )) } else { Err(StatusCode::UNAUTHORIZED) } } async fn me(jar: CookieJar) -> Result<(), StatusCode> { if let Some(session_id) = jar.get("session_id") { // fetch and render user... } else { Err(StatusCode::UNAUTHORIZED) } } async fn authorize_and_create_session(token: &str) -> Option { // authorize the user and create a session... } let app = Router::new() .route("/sessions", post(create_session)) .route("/me", get(me)); ``` -------------------------------- ### GET /list_things Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.Query.html?search=u32+-%3E+bool Example of using the Query extractor to parse query parameters into a struct. ```APIDOC ## [GET] /list_things ### Description This endpoint demonstrates how to use the `Query` extractor to parse query string parameters into a struct. It parses query strings like `?page=2&per_page=30` into a `Pagination` struct. ### Method GET ### Endpoint /list_things ### Parameters #### Query Parameters - **page** (usize) - Required - The page number. - **per_page** (usize) - Required - The number of items per page. ### Request Example ``` GET /list_things?page=2&per_page=30 ``` ### Response #### Success Response (200) No response body is documented. #### Error Response (400) If the query string cannot be parsed, the request is rejected with a `400 Bad Request` response. ``` -------------------------------- ### Option::is_some example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::is_some, showing how to check if an Option is Some. ```rust let x: Option = Some(2); assert_eq!(x.is_some(), true); let x: Option = None; assert_eq!(x.is_some(), false); ``` -------------------------------- ### Option::as_mut_slice example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example from the standard library documentation for Option::as_mut_slice, showing how to get a mutable slice of the contained value. ```rust assert_eq!( [Some(1234).as_mut_slice(), None.as_mut_slice()], [&mut [1234][..], &mut [][..]], ); ``` -------------------------------- ### GET /process_items Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.Query.html?search=u32+-%3E+bool Example of using the Query extractor with a Vec field and serde default. ```APIDOC ## [GET] /process_items ### Description This endpoint demonstrates how to use the `Query` extractor with a `Vec` field that has a `#[serde(default)]` attribute. It parses zero or more occurrences of the `items` query parameter into a `Vec`. ### Method GET ### Endpoint /process_items ### Parameters #### Query Parameters - **items** (Vec) - Optional - A list of items. If not provided, defaults to an empty vector. ### Request Example ``` GET /process_items?items=1&items=2 ``` ### Response #### Success Response (200) No response body is documented. ``` -------------------------------- ### Example: returning a file as an attachment Source: https://docs.rs/axum-extra/latest/axum_extra/response/struct.Attachment.html Example handler that reads `Cargo.toml` and returns it as an `Attachment` with a filename and content-type. Uses `tokio::fs::read_to_string` and maps errors to a 404 status. ```rust use axum::{http::StatusCode, routing::get, Router}; use axum_extra::response::Attachment; async fn cargo_toml() -> Result, (StatusCode, String)> { let file_contents = tokio::fs::read_to_string("Cargo.toml") .await .map_err(|err| (StatusCode::NOT_FOUND, format!("File not found: {err}")))?; Ok(Attachment::new(file_contents) .filename("Cargo.toml") .content_type("text/x-toml")) } let app = Router::new().route("/Cargo.toml", get(cargo_toml)); let _: Router = app; ``` -------------------------------- ### Option::as_slice inverse example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example showing the inverse of as_slice using [_]::first. ```rust for i in [Some(1234_u16), None] { assert_eq!(i.as_ref(), i.as_slice().first()); } ``` -------------------------------- ### make_removal example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Makes a cookie a removal cookie by clearing its value, setting max-age to 0, and setting an expiration far in the past. The example starts with a permanent cookie and then applies make_removal. ```rust use cookie::Cookie; use cookie::time::Duration; let mut c = Cookie::new("foo", "bar"); c.make_permanent(); assert_eq!(c.max_age(), Some(Duration::days(365 * 20))); assert_eq!(c.value(), "bar"); c.make_removal(); assert_eq!(c.value(), ""); assert_eq!(c.max_age(), Some(Duration::ZERO)); ``` -------------------------------- ### Option::as_mut_slice inverse example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example showing the inverse of as_mut_slice using [_]::first_mut. ```rust assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123)) ``` -------------------------------- ### Option::get_or_try_insert_with example (nightly) Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Nightly-only API. If the option is None, calls the closure and inserts its output if successful; otherwise returns the residual. The example parses a string into u32 and u8, showing success and failure. ```rust #![feature(option_get_or_try_insert_with)] let mut o1: Option = None; let mut o2: Option = None; let number = "12345"; assert_eq!(o1.get_or_try_insert_with(|| number.parse()).copied(), Ok(12345)); assert!(o2.get_or_try_insert_with(|| number.parse()).is_err()); assert_eq!(o1, Some(12345)); assert_eq!(o2, None); ``` -------------------------------- ### Using PrivateCookieJar with Key from state Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.PrivateCookieJar.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Complete example showing how to use PrivateCookieJar as an extractor. It sets and gets a private cookie, and requires returning the updated jar from the handler for changes to propagate. The example also shows how to provide the Key via application state and FromRef. ```rust use axum::{ Router, routing::{post, get}, extract::FromRef, response::{IntoResponse, Redirect}, http::StatusCode, }; use axum_extra::{ TypedHeader, headers::authorization::{Authorization, Bearer}, extract::cookie::{PrivateCookieJar, Cookie, Key}, }; async fn set_secret( jar: PrivateCookieJar, ) -> (PrivateCookieJar, Redirect) { let updated_jar = jar.add(Cookie::new("secret", "secret-data")); (updated_jar, Redirect::to("/get")) } async fn get_secret(jar: PrivateCookieJar) { if let Some(data) = jar.get("secret") { // ... } } // our application state #[derive(Clone)] struct AppState { // that holds the key used to encrypt cookies key: Key, } // this impl tells `PrivateCookieJar` how to access the key from our state impl FromRef for Key { fn from_ref(state: &AppState) -> Self { state.key.clone() } } let state = AppState { // Generate a secure key // // You probably don't wanna generate a new one each time the app starts though key: Key::generate(), }; let app = Router::new() .route("/set", post(set_secret)) .route("/get", get(get_secret)) .with_state(state); ``` -------------------------------- ### Option::as_mut_slice mutation example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Example showing how to mutate the value through the mutable slice returned by as_mut_slice. ```rust let mut x = Some(1234); x.as_mut_slice()[0] += 1; assert_eq!(x, Some(1235)); ``` -------------------------------- ### Example: chaining handlers with `or` Source: https://docs.rs/axum-extra/latest/axum_extra/handler/trait.HandlerCallWithExtractors.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `or` to chain handlers with different extractor requirements, falling back to the next handler if an extractor fails. The example defines `admin`, `user`, and `guest` handlers and routes to them with `admin.or(user).or(guest)`. ```rust use axum_extra::handler::HandlerCallWithExtractors; use axum::{ Router, routing::get, extract::FromRequestParts, }; // handlers for varying levels of access async fn admin(admin: AdminPermissions) { // request came from an admin } async fn user(user: User) { // we have a `User` } async fn guest() { // `AdminPermissions` and `User` failed, so we're just a guest } // extractors for checking permissions struct AdminPermissions {} impl FromRequestParts for AdminPermissions where S: Send + Sync, { // check for admin permissions... } struct User {} impl FromRequestParts for User where S: Send + Sync, { // check for a logged in user... } let app = Router::new().route( "/users/{id}", get( // first try `admin`, if that rejects run `user`, finally falling back // to `guest` admin.or(user).or(guest) ) ); ``` -------------------------------- ### Resource::new Source: https://docs.rs/axum-extra/latest/axum_extra/routing/struct.Resource.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Adds a handler at GET /{resource_name}/new. ```APIDOC ## Resource::new ### Description Adds a handler at `GET /{resource_name}/new`. ### Method GET ### Endpoint `GET /{resource_name}/new` ### Parameters - `handler` (`H`) - Required - The handler to be called for this route. ### Returns - `Self` - The `Resource` with the handler added. ``` -------------------------------- ### with_query_params example Source: https://docs.rs/axum-extra/latest/axum_extra/routing/trait.TypedPath.html?search=u32+-%3E+bool Shows how to add query parameters to a TypedPath using with_query_params. The parameter type must implement Serialize. The example creates a path for /users with pagination query parameters. ```rust use axum_extra::routing::TypedPath; use serde::Serialize; #[derive(TypedPath)] #[typed_path("/users")] struct Users; #[derive(Serialize)] struct Pagination { page: u32, per_page: u32, } let path = Users.with_query_params(Pagination { page: 1, per_page: 10, }); ``` -------------------------------- ### Invalid path example Source: https://docs.rs/axum-extra/latest/axum_extra/macro.vpath.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example will fail to compile because the path is invalid. The macro aborts compilation if the path is invalid. ```rust use axum::routing::{Router, get}; use axum_extra::vpath; let router = axum::Router::<()>::new() .route(vpath!("invalid_path"), get(root)) .to_owned(); async fn root() {} ``` -------------------------------- ### Multipart upload handler example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/multipart/struct.Multipart.html?search= Example handler that extracts a Multipart from a POST request, iterates over fields with next_field(), and prints the field name and byte length. The Multipart extractor must be last in the handler because it consumes the request body. ```rust use axum::{ routing::post, Router, }; use axum_extra::extract::Multipart; 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)); ``` -------------------------------- ### is_none example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/enum.SameSite.html?search= Shows how to use `SameSite::is_none()` to check if a `SameSite` value is `None`. ```rust use cookie::SameSite; let none = SameSite::None; assert!(none.is_none()); assert!(!none.is_lax()); assert!(!none.is_strict()); ``` -------------------------------- ### path_raw example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Returns the Path of the cookie as a string slice with the same lifetime as the originally parsed string. The example shows that the returned path outlives the cookie instance. ```rust use cookie::Cookie; let cookie_string = format!("{}={}; Path=/", "foo", "bar"); // `c` will be dropped at the end of the scope, but `path` will live on let path = { let c = Cookie::parse(cookie_string.as_str()).unwrap(); c.path_raw() }; assert_eq!(path, Some("/")); ``` -------------------------------- ### Example: Using Cached to avoid repeated session extraction Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.Cached.html Shows how to wrap a `Session` extractor with `Cached` so that the session is loaded only once per request, even when multiple extractors need it. The example includes the `Session` and `CurrentUser` extractors and a handler that uses `Cached`. ```rust use axum_extra::extract::Cached; use axum::{ extract::FromRequestParts, response::{IntoResponse, Response}, http::{StatusCode, request::Parts}, }; #[derive(Clone)] struct Session { /* ... */ } impl FromRequestParts for Session where S: Send + Sync, { type Rejection = (StatusCode, String); async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { // load session... } } struct CurrentUser { /* ... */ } impl FromRequestParts for CurrentUser where S: Send + Sync, { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { // loading a `CurrentUser` requires first loading the `Session` // // by using `Cached` we avoid extracting the session more than // once, in case other extractors for the same request also loads the session let session: Session = Cached::::from_request_parts(parts, state) .await .map_err(|err| err.into_response())? .0; // load user from session... } } // handler that extracts the current user and the session // // the session will only be loaded once, even though `CurrentUser` // also loads it async fn handler( current_user: CurrentUser, // we have to use `Cached` here otherwise the // cached session would not be used Cached(session): Cached, ) { // ... } ``` -------------------------------- ### is_lax example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/enum.SameSite.html?search= Shows how to use `SameSite::is_lax()` to check if a `SameSite` value is `Lax`. ```rust use cookie::SameSite; let lax = SameSite::Lax; assert!(lax.is_lax()); assert!(!lax.is_strict()); assert!(!lax.is_none()); ``` -------------------------------- ### is_strict example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/enum.SameSite.html?search= Shows how to use `SameSite::is_strict()` to check if a `SameSite` value is `Strict`. ```rust use cookie::SameSite; let strict = SameSite::Strict; assert!(strict.is_strict()); assert!(!strict.is_lax()); assert!(!strict.is_none()); ``` -------------------------------- ### Stream file contents with AsyncReadBody Source: https://docs.rs/axum-extra/latest/axum_extra/body/struct.AsyncReadBody.html Example of using AsyncReadBody to stream the contents of a file. It opens a file, creates an AsyncReadBody from it, and returns it as a response with a content-type header. The example also sets up a route for the handler. ```rust use axum::{ Router, routing::get, http::{StatusCode, header::CONTENT_TYPE}, response::{Response, IntoResponse}, }; use axum_extra::body::AsyncReadBody; use tokio::fs::File; async fn cargo_toml() -> Result { let file = File::open("Cargo.toml") .await .map_err(|err| { (StatusCode::NOT_FOUND, format!("File not found: {err}")) })?; let headers = [(CONTENT_TYPE, "text/x-toml")]; let body = AsyncReadBody::new(file); Ok((headers, body).into_response()) } let app = Router::new().route("/Cargo.toml", get(cargo_toml)); ``` -------------------------------- ### OptionalQuery::take_if example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html?search=std%3A%3Avec Shows how to use take_if to conditionally take the value out of an Option, replacing it with None if the predicate returns false. The example demonstrates two calls: first with a predicate that increments the value and returns false, then with a predicate that checks equality. ```rust let mut x = Some(42); let prev = x.take_if(|v| { *v += 1; false }); assert_eq!(x, Some(43)); assert_eq!(prev, None); let prev = x.take_if(|v| *v == 43); assert_eq!(x, None); assert_eq!(prev, Some(43)); ``` -------------------------------- ### Get a cookie from CookieJar Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.CookieJar.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a cookie by name from the jar. The example shows how to get the cookie value as an owned String using `get` and `map`. ```rust use axum_extra::extract::cookie::CookieJar; use axum::response::IntoResponse; async fn handle(jar: CookieJar) { let value: Option = jar .get("foo") .map(|cookie| cookie.value().to_owned()); } ``` -------------------------------- ### Cookie::named example (deprecated) Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Shows the deprecated `Cookie::named` method, which creates a cookie with an empty value. The example asserts the name and empty value, and shows the equivalent `Cookie::from` with a string. ```rust use cookie::Cookie; let cookie = Cookie::named("name"); assert_eq!(cookie.name(), "name"); assert!(cookie.value().is_empty()); // This is equivalent to `from` with `"name`: let cookie = Cookie::from("name"); assert_eq!(cookie.name(), "name"); assert!(cookie.value().is_empty()); ``` -------------------------------- ### Create a Resource with CRUD routes Source: https://docs.rs/axum-extra/latest/axum_extra/routing/struct.Resource.html?search= Shows how to create a Resource named "users" and define conventional CRUD routes for it. The resulting resource is merged into an axum Router. Each method adds a handler for a specific HTTP method and path, with path parameters extracted via Path. ```rust use axum::{Router, routing::get, extract::Path}; use axum_extra::routing::{RouterExt, Resource}; let users = Resource::named("users") // Define a route for `GET /users` .index(|| async {}) // `POST /users` .create(|| async {}) // `GET /users/new` .new(|| async {}) // `GET /users/{users_id}` .show(|Path(user_id): Path| async {}) // `GET /users/{users_id}/edit` .edit(|Path(user_id): Path| async {}) // `PUT or PATCH /users/{users_id}` .update(|Path(user_id): Path| async {}) // `DELETE /users/{users_id}` .destroy(|Path(user_id): Path| async {}); let app = Router::new().merge(users); ``` -------------------------------- ### Cookie::build example with different base types Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Demonstrates using `Cookie::build` with different base types: a tuple, a string, and a `CookieBuilder`. Shows how each base affects the resulting cookie's properties. ```rust use cookie::Cookie; // Use `(K, V)` as the base, setting a name and value. let b1 = Cookie::build(("name", "value")).path("/"); assert_eq!(b1.inner().name_value(), ("name", "value")); assert_eq!(b1.inner().path(), Some("/")); // Use `&str` as the base, setting a name and empty value. let b2 = Cookie::build(("name")); assert_eq!(b2.inner().name_value(), ("name", "")); // Use `CookieBuilder` as the base, inheriting all properties. let b3 = Cookie::build(b1); assert_eq!(b3.inner().name_value(), ("name", "value")); assert_eq!(b3.inner().path(), Some("/")); ``` -------------------------------- ### Resource::show Source: https://docs.rs/axum-extra/latest/axum_extra/routing/struct.Resource.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Adds a handler at GET //{_id}. ```APIDOC ## Resource::show ### Description Adds a handler at `GET //{_id}`. For example, when the resource is `posts`, the route is `GET /post/{post_id}`. ### Method GET ### Endpoint `GET //{_id}` ### Parameters - `handler` (`H`) - Required - The handler to be called for this route. ### Returns - `Self` - The `Resource` with the handler added. ``` -------------------------------- ### Construct Query from Uri with try_from_uri Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.Query.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to construct a `Query` from a `Uri` reference using `Query::try_from_uri`. The example parses a URI string and then asserts that the extracted fields match the expected values. ```rust use axum_extra::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); ``` -------------------------------- ### TryFrom<&[u8]> for Key example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Key.html Demonstrates the fallible conversion from a byte slice to a cookie::Key. A key of at least 64 bytes succeeds, while a short key like [1, 2, 3, 4] fails. ```rust use cookie::Key; let key = { /* a cryptographically random key >= 64 bytes */ }; assert!(Key::try_from(key).is_ok()); // A key that's far too short to use. let key = &[1, 2, 3, 4][..]; assert!(Key::try_from(key).is_err()); ``` -------------------------------- ### GET /users/{id} Source: https://docs.rs/axum-extra/latest/axum_extra/protobuf/struct.Protobuf.html?search=u32+-%3E+bool Example of using the Protobuf extractor in an Axum handler to return a Protobuf response. ```APIDOC ## [GET] /users/{id} ### Description Retrieves a user by ID and returns it as a Protobuf response. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The user ID. ### Request Example No request body required. ### Response #### Success Response (200) - **username** (string) - The user's username. #### Response Example Protobuf-encoded User message with username field. ``` -------------------------------- ### get Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.PrivateCookieJar.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a cookie from the jar. If the cookie exists and can be decrypted, it is returned in plaintext. ```APIDOC ## get ### Description Gets a cookie from the jar. If the cookie exists and can be decrypted, it is returned in plaintext. ### Method get ### Signature pub fn get(&self, name: &str) -> Option> ### Parameters - **name** (&str) - Required - The name of the cookie to get. ### Returns - **Option>** - The decrypted cookie if it exists and can be decrypted, otherwise `None`. ### Example ```rust use axum_extra::extract::cookie::PrivateCookieJar; use axum::response::IntoResponse; async fn handle(jar: PrivateCookieJar) { let value: Option = jar .get("foo") .map(|cookie| cookie.value().to_owned()); } ``` ``` -------------------------------- ### Example: Using OptionalQuery to parse query strings Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Shows how to use OptionalQuery to parse query strings like ?page=2&per_page=30 into Some(Pagination) and empty query strings into None. If parsing fails, the request is rejected with a 400 Bad Request response. ```rust use axum::{routing::get, Router}; use axum_extra::extract::OptionalQuery; use serde::Deserialize; #[derive(Deserialize)] struct Pagination { page: usize, per_page: usize, } // This will parse query strings like `?page=2&per_page=30` into `Some(Pagination)` and // empty query string into `None` async fn list_things(OptionalQuery(pagination): OptionalQuery) { match pagination { Some(Pagination{ page, per_page }) => { /* return specified page */ }, None => { /* return fist page */ } } // ... } let app = Router::new().route("/list_things", get(list_things)); ``` -------------------------------- ### Build a Cookie with Cookie::build and CookieBuilder Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Shows how to construct a cookie with additional attributes using `Cookie::build` and `CookieBuilder` methods. The example sets domain, path, secure, and http_only flags, then adds and removes cookies from a jar. ```rust use cookie::Cookie; let cookie = Cookie::build(("name", "value")) .domain("www.rust-lang.org") .path("/") .secure(true) .http_only(true); jar.add(cookie); jar.remove(Cookie::build("name").path("/")); ``` -------------------------------- ### replace example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Shows how to replace the value in an Option, returning the old value if present. Works for both Some and None cases. ```rust let mut x = Some(2); let old = x.replace(5); assert_eq!(x, Some(5)); assert_eq!(old, Some(2)); let mut x = None; let old = x.replace(3); assert_eq!(x, Some(3)); assert_eq!(old, None); ``` -------------------------------- ### Constructing Expiration with From Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/enum.Expiration.html?search= Shows how to construct Expiration from None, OffsetDateTime, and Some(OffsetDateTime). None maps to Session, while OffsetDateTime and Some(OffsetDateTime) map to DateTime. ```rust use cookie::Expiration; use time::OffsetDateTime; let expires = Expiration::from(None); assert_eq!(expires, Expiration::Session); let now = OffsetDateTime::now_utc(); let expires = Expiration::from(now); assert_eq!(expires, Expiration::DateTime(now)); let expires = Expiration::from(Some(now)); assert_eq!(expires, Expiration::DateTime(now)); ``` -------------------------------- ### partitioned() example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Shows how partitioned() behaves: Some(true) when explicitly set to true, Some(false) when explicitly set to false, and None otherwise. Note that the Partitioned attribute is an HTTP draft and subject to change. ```rust use cookie::Cookie; let c = Cookie::parse("name=value; Partitioned").unwrap(); assert_eq!(c.partitioned(), Some(true)); let mut c = Cookie::parse("name=value").unwrap(); assert_eq!(c.partitioned(), None); let mut c = Cookie::new("name", "value"); assert_eq!(c.partitioned(), None); // An explicitly set "false" value. c.set_partitioned(false); assert_eq!(c.partitioned(), Some(false)); // An explicitly set "true" value. c.set_partitioned(true); assert_eq!(c.partitioned(), Some(true)); ``` -------------------------------- ### unset_expires example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Unsets the expires field of a cookie. The example first sets an expiration to Session and then removes it, resulting in None. ```rust use cookie::{Cookie, Expiration}; let mut c = Cookie::new("name", "value"); assert_eq!(c.expires(), None); c.set_expires(None); assert_eq!(c.expires(), Some(Expiration::Session)); c.unset_expires(); assert_eq!(c.expires(), None); ``` -------------------------------- ### ErasedJson handler example Source: https://docs.rs/axum-extra/latest/axum_extra/response/struct.ErasedJson.html Example handler returning ErasedJson, using ErasedJson::new to serialize different types from different branches. ```rust async fn handler() -> ErasedJson { // ... if condition { ErasedJson::new(&foo) } else { ErasedJson::new(&bar) } } ``` -------------------------------- ### Create Key with Key::from Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Key.html Creates a Key from a 512-bit (64-byte) cryptographically random string. Panics if the key is less than 64 bytes; use Key::try_from() or Key::generate() for a non-panicking alternative. ```rust use cookie::Key; let key = { /* a cryptographically random key >= 64 bytes */ }; let key = Key::from(key); ``` -------------------------------- ### Option::iter_mut example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Returns a mutable iterator over the possibly contained value. The example mutates the contained value via the iterator. ```rust let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); let mut x: Option = None; assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### max_age() example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/cookie/struct.Cookie.html?search=std%3A%3Avec Parses cookies with and without a Max-Age attribute and checks the returned Duration. The example converts the duration to whole hours. ```rust use cookie::Cookie; let c = Cookie::parse("name=value").unwrap(); assert_eq!(c.max_age(), None); let c = Cookie::parse("name=value; Max-Age=3600").unwrap(); assert_eq!(c.max_age().map(|age| age.whole_hours()), Some(1)); ``` -------------------------------- ### TryStream and WithSubscriber Methods Source: https://docs.rs/axum-extra/latest/axum_extra/json_lines/struct.JsonLines.html?search=u32+-%3E+bool Documentation for the TryStream extension methods and subscriber attachment methods from the axum_extra crate. ```APIDOC ## try_filter ### Description Attempt to filter the values produced by this stream according to the provided asynchronous closure. ### Signature ```rust fn try_filter(self, f: F) -> TryFilter where Fut: Future, F: FnMut(&Self::Ok) -> Fut, Self: Sized, ``` ### Parameters - `f` (F) - Required - Asynchronous closure that returns a future resolving to a boolean indicating whether to keep the item. ### Returns - `TryFilter` - A stream that filters items based on the asynchronous predicate. ## try_filter_map ### Description Attempt to filter the values produced by this stream while simultaneously mapping them to a different type according to the provided asynchronous closure. ### Signature ```rust fn try_filter_map(self, f: F) -> TryFilterMap where Fut: TryFuture, Error = Self::Error>, F: FnMut(Self::Ok) -> Fut, Self: Sized, ``` ### Parameters - `f` (F) - Required - Asynchronous closure that returns a future resolving to `Option`; `None` filters out the item. ### Returns - `TryFilterMap` - A stream that filters and maps items. ## try_flatten_unordered ### Description Flattens a stream of streams into just one continuous stream. Produced streams will be polled concurrently and any errors will be passed through without looking at them. If the underlying base stream returns an error, it will be immediately propagated. ### Availability Available on **crate feature `alloc`** only. ### Signature ```rust fn try_flatten_unordered( self, limit: impl Into>, ) -> TryFlattenUnordered where Self::Ok: TryStream + Unpin, ::Error: From, Self: Sized, ``` ### Parameters - `limit` (impl Into>) - Required - Maximum number of concurrent streams; `None` for unlimited. ### Returns - `TryFlattenUnordered` - A stream that flattens and polls inner streams concurrently. ## try_flatten ### Description Flattens a stream of streams into just one continuous stream. ### Signature ```rust fn try_flatten(self) -> TryFlatten where Self::Ok: TryStream, ::Error: From, Self: Sized, ``` ### Returns - `TryFlatten` - A stream that flattens inner streams sequentially. ## try_fold ### Description Attempt to execute an accumulating asynchronous computation over a stream, collecting all the values into one final result. ### Signature ```rust fn try_fold(self, init: T, f: F) -> TryFold where F: FnMut(T, Self::Ok) -> Fut, Fut: TryFuture, Self: Sized, ``` ### Parameters - `init` (T) - Required - Initial accumulator value. - `f` (F) - Required - Asynchronous closure that takes the accumulator and an item, returning a future resolving to the new accumulator. ### Returns - `TryFold` - A future that resolves to the final accumulator value. ## try_concat ### Description Attempt to concatenate all items of a stream into a single extendable destination, returning a future representing the end result. ### Signature ```rust fn try_concat(self) -> TryConcat where Self: Sized, Self::Ok: Extend<::Item> + IntoIterator + Default, ``` ### Returns - `TryConcat` - A future that resolves to the concatenated result. ## try_buffer_unordered ### Description Attempt to execute several futures from a stream concurrently (unordered). ### Availability Available on **crate feature `alloc`** only. ### Signature ```rust fn try_buffer_unordered(self, n: usize) -> TryBufferUnordered where Self::Ok: TryFuture, Self: Sized, ``` ### Parameters - `n` (usize) - Required - Maximum number of concurrent futures. ### Returns - `TryBufferUnordered` - A stream that yields results from concurrently executed futures in completion order. ## try_buffered ### Description Attempt to execute several futures from a stream concurrently. ### Availability Available on **crate feature `alloc`** only. ### Signature ```rust fn try_buffered(self, n: usize) -> TryBuffered where Self::Ok: TryFuture, Self: Sized, ``` ### Parameters - `n` (usize) - Required - Maximum number of concurrent futures. ### Returns - `TryBuffered` - A stream that yields results from concurrently executed futures in order. ## try_poll_next_unpin ### Description A convenience method for calling `TryStream::try_poll_next` on `Unpin` stream types. ### Signature ```rust fn try_poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll>> where Self: Unpin, ``` ### Parameters - `cx` (&mut Context<'_>) - Required - The task context for polling. ### Returns - `Poll>>` - The result of polling the stream. ## try_all ### Description Attempt to execute a predicate over an asynchronous stream and evaluate if all items satisfy the predicate. Exits early if an `Err` is encountered or if an `Ok` item is found that does not satisfy the predicate. ### Signature ```rust fn try_all(self, f: F) -> TryAll where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future, ``` ### Parameters - `f` (F) - Required - Asynchronous predicate closure that returns a future resolving to a boolean. ### Returns - `TryAll` - A future that resolves to `true` if all items satisfy the predicate, `false` otherwise. ## try_any ### Description Attempt to execute a predicate over an asynchronous stream and evaluate if any items satisfy the predicate. Exits early if an `Err` is encountered or if an `Ok` item is found that satisfies the predicate. ### Signature ```rust fn try_any(self, f: F) -> TryAny where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future, ``` ### Parameters - `f` (F) - Required - Asynchronous predicate closure that returns a future resolving to a boolean. ### Returns - `TryAny` - A future that resolves to `true` if any item satisfies the predicate, `false` otherwise. ## with_subscriber ### Description Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. ### Signature ```rust fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into, ``` ### Parameters - `subscriber` (S) - Required - The subscriber to attach. ### Returns - `WithDispatch` - A wrapper with the subscriber attached. ## with_current_subscriber ### Description Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. ### Signature ```rust fn with_current_subscriber(self) -> WithDispatch ``` ### Returns - `WithDispatch` - A wrapper with the current default subscriber attached. ``` -------------------------------- ### Option::get_or_insert_with example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Inserts a value computed by a closure if the option is None, then returns a mutable reference. The example uses a closure returning 5. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert_with(|| 5); assert_eq!(y, &5); *y = 7; } assert_eq!(x, Some(7)); ``` -------------------------------- ### Option::get_or_insert_default example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Inserts the default value if the option is None, then returns a mutable reference. The example shows inserting 0 for u32 and then modifying it. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert_default(); assert_eq!(y, &0); *y = 7; } assert_eq!(x, Some(7)); ``` -------------------------------- ### take_if example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Shows how to conditionally take a value from an Option using a predicate that can mutate the value. The predicate returns false to keep the value, and true to take it. ```rust let mut x = Some(42); let prev = x.take_if(|v| if *v == 42 { *v += 1; false } else { false }); assert_eq!(x, Some(43)); assert_eq!(prev, None); let prev = x.take_if(|v| *v == 43); assert_eq!(x, None); assert_eq!(prev, Some(43)); ``` -------------------------------- ### Option::iter example Source: https://docs.rs/axum-extra/latest/axum_extra/extract/struct.OptionalQuery.html Returns an iterator over the possibly contained value. The example shows that Some(4) yields a reference to 4, and None yields no items. ```rust let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); let x: Option = None; assert_eq!(x.iter().next(), None); ```