repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/oauth/src/main.rs | examples/oauth/src/main.rs | //! Example OAuth (Discord) implementation.
//!
//! 1) Create a new application at <https://discord.com/developers/applications>
//! 2) Visit the OAuth2 tab to get your CLIENT_ID and CLIENT_SECRET
//! 3) Add a new redirect URI (for this example: `http://127.0.0.1:3000/auth/authorized`)
//! 4) Run with the following (replacing values appropriately):
//! ```not_rust
//! CLIENT_ID=REPLACE_ME CLIENT_SECRET=REPLACE_ME cargo run -p example-oauth
//! ```
use anyhow::{anyhow, Context, Result};
use async_session::{MemoryStore, Session, SessionStore};
use axum::{
extract::{FromRef, FromRequestParts, OptionalFromRequestParts, Query, State},
http::{header::SET_COOKIE, HeaderMap},
response::{IntoResponse, Redirect, Response},
routing::get,
RequestPartsExt, Router,
};
use axum_extra::{headers, typed_header::TypedHeaderRejectionReason, TypedHeader};
use http::{header, request::Parts, StatusCode};
use oauth2::{
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointNotSet, EndpointSet,
RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use serde::{Deserialize, Serialize};
use std::{convert::Infallible, env};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
static COOKIE_NAME: &str = "SESSION";
static CSRF_TOKEN: &str = "csrf_token";
type BasicClient = oauth2::basic::BasicClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointSet,
>;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// `MemoryStore` is just used as an example. Don't use this in production.
let store = MemoryStore::new();
let oauth_client = oauth_client().unwrap();
let app_state = AppState {
store,
oauth_client,
};
let app = Router::new()
.route("/", get(index))
.route("/auth/discord", get(discord_auth))
.route("/auth/authorized", get(login_authorized))
.route("/protected", get(protected))
.route("/logout", get(logout))
.with_state(app_state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.context("failed to bind TcpListener")
.unwrap();
tracing::debug!(
"listening on {}",
listener
.local_addr()
.context("failed to return local address")
.unwrap()
);
axum::serve(listener, app).await;
}
#[derive(Clone)]
struct AppState {
store: MemoryStore,
oauth_client: BasicClient,
}
impl FromRef<AppState> for MemoryStore {
fn from_ref(state: &AppState) -> Self {
state.store.clone()
}
}
impl FromRef<AppState> for BasicClient {
fn from_ref(state: &AppState) -> Self {
state.oauth_client.clone()
}
}
fn oauth_client() -> Result<BasicClient, AppError> {
// Environment variables (* = required):
// *"CLIENT_ID" "REPLACE_ME";
// *"CLIENT_SECRET" "REPLACE_ME";
// "REDIRECT_URL" "http://127.0.0.1:3000/auth/authorized";
// "AUTH_URL" "https://discord.com/api/oauth2/authorize?response_type=code";
// "TOKEN_URL" "https://discord.com/api/oauth2/token";
let client_id = env::var("CLIENT_ID").context("Missing CLIENT_ID!")?;
let client_secret = env::var("CLIENT_SECRET").context("Missing CLIENT_SECRET!")?;
let redirect_url = env::var("REDIRECT_URL")
.unwrap_or_else(|_| "http://127.0.0.1:3000/auth/authorized".to_string());
let auth_url = env::var("AUTH_URL").unwrap_or_else(|_| {
"https://discord.com/api/oauth2/authorize?response_type=code".to_string()
});
let token_url = env::var("TOKEN_URL")
.unwrap_or_else(|_| "https://discord.com/api/oauth2/token".to_string());
Ok(oauth2::basic::BasicClient::new(ClientId::new(client_id))
.set_client_secret(ClientSecret::new(client_secret))
.set_auth_uri(
AuthUrl::new(auth_url).context("failed to create new authorization server URL")?,
)
.set_token_uri(TokenUrl::new(token_url).context("failed to create new token endpoint URL")?)
.set_redirect_uri(
RedirectUrl::new(redirect_url).context("failed to create new redirection URL")?,
))
}
// The user data we'll get back from Discord.
// https://discord.com/developers/docs/resources/user#user-object-user-structure
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: String,
avatar: Option<String>,
username: String,
discriminator: String,
}
// Session is optional
async fn index(user: Option<User>) -> impl IntoResponse {
match user {
Some(u) => format!(
"Hey {}! You're logged in!\nYou may now access `/protected`.\nLog out with `/logout`.",
u.username
),
None => "You're not logged in.\nVisit `/auth/discord` to do so.".to_string(),
}
}
async fn discord_auth(
State(client): State<BasicClient>,
State(store): State<MemoryStore>,
) -> Result<impl IntoResponse, AppError> {
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("identify".to_string()))
.url();
// Create session to store csrf_token
let mut session = Session::new();
session
.insert(CSRF_TOKEN, &csrf_token)
.context("failed in inserting CSRF token into session")?;
// Store the session in MemoryStore and retrieve the session cookie
let cookie = store
.store_session(session)
.await
.context("failed to store CSRF token session")?
.context("unexpected error retrieving CSRF cookie value")?;
// Attach the session cookie to the response header
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; HttpOnly; Secure; Path=/");
let mut headers = HeaderMap::new();
headers.insert(
SET_COOKIE,
cookie.parse().context("failed to parse cookie")?,
);
Ok((headers, Redirect::to(auth_url.as_ref())))
}
// Valid user session required. If there is none, redirect to the auth page
async fn protected(user: User) -> impl IntoResponse {
format!("Welcome to the protected area :)\nHere's your info:\n{user:?}")
}
async fn logout(
State(store): State<MemoryStore>,
TypedHeader(cookies): TypedHeader<headers::Cookie>,
) -> Result<impl IntoResponse, AppError> {
let cookie = cookies
.get(COOKIE_NAME)
.context("unexpected error getting cookie name")?;
let session = match store
.load_session(cookie.to_string())
.await
.context("failed to load session")?
{
Some(s) => s,
// No session active, just redirect
None => return Ok(Redirect::to("/")),
};
store
.destroy_session(session)
.await
.context("failed to destroy session")?;
Ok(Redirect::to("/"))
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct AuthRequest {
code: String,
state: String,
}
async fn csrf_token_validation_workflow(
auth_request: &AuthRequest,
cookies: &headers::Cookie,
store: &MemoryStore,
) -> Result<(), AppError> {
// Extract the cookie from the request
let cookie = cookies
.get(COOKIE_NAME)
.context("unexpected error getting cookie name")?
.to_string();
// Load the session
let session = match store
.load_session(cookie)
.await
.context("failed to load session")?
{
Some(session) => session,
None => return Err(anyhow!("Session not found").into()),
};
// Extract the CSRF token from the session
let stored_csrf_token = session
.get::<CsrfToken>(CSRF_TOKEN)
.context("CSRF token not found in session")?
.to_owned();
// Cleanup the CSRF token session
store
.destroy_session(session)
.await
.context("Failed to destroy old session")?;
// Validate CSRF token is the same as the one in the auth request
if *stored_csrf_token.secret() != auth_request.state {
return Err(anyhow!("CSRF token mismatch").into());
}
Ok(())
}
async fn login_authorized(
Query(query): Query<AuthRequest>,
State(store): State<MemoryStore>,
State(oauth_client): State<BasicClient>,
TypedHeader(cookies): TypedHeader<headers::Cookie>,
) -> Result<impl IntoResponse, AppError> {
csrf_token_validation_workflow(&query, &cookies, &store).await?;
let client = reqwest::Client::new();
// Get an auth token
let token = oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(&client)
.await
.context("failed in sending request request to authorization server")?;
// Fetch user data from discord
let user_data: User = client
// https://discord.com/developers/docs/resources/user#get-current-user
.get("https://discordapp.com/api/users/@me")
.bearer_auth(token.access_token().secret())
.send()
.await
.context("failed in sending request to target Url")?
.json::<User>()
.await
.context("failed to deserialize response as JSON")?;
// Create a new session filled with user data
let mut session = Session::new();
session
.insert("user", &user_data)
.context("failed in inserting serialized value into session")?;
// Store session and get corresponding cookie
let cookie = store
.store_session(session)
.await
.context("failed to store session")?
.context("unexpected error retrieving cookie value")?;
// Build the cookie
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; HttpOnly; Secure; Path=/");
// Set cookie
let mut headers = HeaderMap::new();
headers.insert(
SET_COOKIE,
cookie.parse().context("failed to parse cookie")?,
);
Ok((headers, Redirect::to("/")))
}
struct AuthRedirect;
impl IntoResponse for AuthRedirect {
fn into_response(self) -> Response {
Redirect::temporary("/auth/discord").into_response()
}
}
impl<S> FromRequestParts<S> for User
where
MemoryStore: FromRef<S>,
S: Send + Sync,
{
// If anything goes wrong or no session is found, redirect to the auth page
type Rejection = AuthRedirect;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let store = MemoryStore::from_ref(state);
let cookies = parts
.extract::<TypedHeader<headers::Cookie>>()
.await
.map_err(|e| match *e.name() {
header::COOKIE => match e.reason() {
TypedHeaderRejectionReason::Missing => AuthRedirect,
_ => panic!("unexpected error getting Cookie header(s): {e}"),
},
_ => panic!("unexpected error getting cookies: {e}"),
})?;
let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;
let session = store
.load_session(session_cookie.to_string())
.await
.unwrap()
.ok_or(AuthRedirect)?;
let user = session.get::<User>("user").ok_or(AuthRedirect)?;
Ok(user)
}
}
impl<S> OptionalFromRequestParts<S> for User
where
MemoryStore: FromRef<S>,
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(
parts: &mut Parts,
state: &S,
) -> Result<Option<Self>, Self::Rejection> {
match <User as FromRequestParts<S>>::from_request_parts(parts, state).await {
Ok(res) => Ok(Some(res)),
Err(AuthRedirect) => Ok(None),
}
}
}
// Use anyhow, define error and enable '?'
// For a simplified example of using anyhow in axum check /examples/anyhow-error-response
#[derive(Debug)]
struct AppError(anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
tracing::error!("Application error: {:#}", self.0);
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
}
}
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/dependency-injection/src/main.rs | examples/dependency-injection/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-dependency-injection
//! ```
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use axum::{
extract::{Path, State},
http::StatusCode,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
let user_repo = InMemoryUserRepo::default();
// We generally have two ways to inject dependencies:
//
// 1. Using trait objects (`dyn SomeTrait`)
// - Pros
// - Likely leads to simpler code due to fewer type parameters.
// - Cons
// - Less flexible because we can only use object safe traits
// - Small amount of additional runtime overhead due to dynamic dispatch.
// This is likely to be negligible.
// 2. Using generics (`T where T: SomeTrait`)
// - Pros
// - More flexible since all traits can be used.
// - No runtime overhead.
// - Cons:
// - Additional type parameters and trait bounds can lead to more complex code and
// boilerplate.
//
// Using trait objects is recommended unless you really need generics.
let using_dyn = Router::new()
.route("/users/{id}", get(get_user_dyn))
.route("/users", post(create_user_dyn))
.with_state(AppStateDyn {
user_repo: Arc::new(user_repo.clone()),
});
let using_generic = Router::new()
.route("/users/{id}", get(get_user_generic::<InMemoryUserRepo>))
.route("/users", post(create_user_generic::<InMemoryUserRepo>))
.with_state(AppStateGeneric { user_repo });
let app = Router::new()
.nest("/dyn", using_dyn)
.nest("/generic", using_generic);
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
#[derive(Clone)]
struct AppStateDyn {
user_repo: Arc<dyn UserRepo>,
}
#[derive(Clone)]
struct AppStateGeneric<T> {
user_repo: T,
}
#[derive(Debug, Serialize, Clone)]
struct User {
id: Uuid,
name: String,
}
#[derive(Deserialize)]
struct UserParams {
name: String,
}
async fn create_user_dyn(
State(state): State<AppStateDyn>,
Json(params): Json<UserParams>,
) -> Json<User> {
let user = User {
id: Uuid::new_v4(),
name: params.name,
};
state.user_repo.save_user(&user);
Json(user)
}
async fn get_user_dyn(
State(state): State<AppStateDyn>,
Path(id): Path<Uuid>,
) -> Result<Json<User>, StatusCode> {
match state.user_repo.get_user(id) {
Some(user) => Ok(Json(user)),
None => Err(StatusCode::NOT_FOUND),
}
}
async fn create_user_generic<T>(
State(state): State<AppStateGeneric<T>>,
Json(params): Json<UserParams>,
) -> Json<User>
where
T: UserRepo,
{
let user = User {
id: Uuid::new_v4(),
name: params.name,
};
state.user_repo.save_user(&user);
Json(user)
}
async fn get_user_generic<T>(
State(state): State<AppStateGeneric<T>>,
Path(id): Path<Uuid>,
) -> Result<Json<User>, StatusCode>
where
T: UserRepo,
{
match state.user_repo.get_user(id) {
Some(user) => Ok(Json(user)),
None => Err(StatusCode::NOT_FOUND),
}
}
trait UserRepo: Send + Sync {
fn get_user(&self, id: Uuid) -> Option<User>;
fn save_user(&self, user: &User);
}
#[derive(Debug, Clone, Default)]
struct InMemoryUserRepo {
map: Arc<Mutex<HashMap<Uuid, User>>>,
}
impl UserRepo for InMemoryUserRepo {
fn get_user(&self, id: Uuid) -> Option<User> {
self.map.lock().unwrap().get(&id).cloned()
}
fn save_user(&self, user: &User) {
self.map.lock().unwrap().insert(user.id, user.clone());
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/stream-to-file/src/main.rs | examples/stream-to-file/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-stream-to-file
//! ```
use axum::{
body::Bytes,
extract::{Multipart, Path, Request},
http::StatusCode,
response::{Html, Redirect},
routing::{get, post},
BoxError, Router,
};
use futures_util::{Stream, TryStreamExt};
use std::{io, pin::pin};
use tokio::{fs::File, io::BufWriter};
use tokio_util::io::StreamReader;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
const UPLOADS_DIRECTORY: &str = "uploads";
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// save files to a separate directory to not override files in the current directory
tokio::fs::create_dir(UPLOADS_DIRECTORY)
.await
.expect("failed to create `uploads` directory");
let app = Router::new()
.route("/", get(show_form).post(accept_form))
.route("/file/{file_name}", post(save_request_body));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
// Handler that streams the request body to a file.
//
// POST'ing to `/file/foo.txt` will create a file called `foo.txt`.
async fn save_request_body(
Path(file_name): Path<String>,
request: Request,
) -> Result<(), (StatusCode, String)> {
stream_to_file(&file_name, request.into_body().into_data_stream()).await
}
// Handler that returns HTML for a multipart form.
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
<head>
<title>Upload something!</title>
</head>
<body>
<form action="/" method="post" enctype="multipart/form-data">
<div>
<label>
Upload file:
<input type="file" name="file" multiple>
</label>
</div>
<div>
<input type="submit" value="Upload files">
</div>
</form>
</body>
</html>
"#,
)
}
// Handler that accepts a multipart form upload and streams each field to a file.
async fn accept_form(mut multipart: Multipart) -> Result<Redirect, (StatusCode, String)> {
while let Ok(Some(field)) = multipart.next_field().await {
let file_name = if let Some(file_name) = field.file_name() {
file_name.to_owned()
} else {
continue;
};
stream_to_file(&file_name, field).await?;
}
Ok(Redirect::to("/"))
}
// Save a `Stream` to a file
async fn stream_to_file<S, E>(path: &str, stream: S) -> Result<(), (StatusCode, String)>
where
S: Stream<Item = Result<Bytes, E>>,
E: Into<BoxError>,
{
if !path_is_valid(path) {
return Err((StatusCode::BAD_REQUEST, "Invalid path".to_owned()));
}
async {
// Convert the stream into an `AsyncRead`.
let body_with_io_error = stream.map_err(io::Error::other);
let mut body_reader = pin!(StreamReader::new(body_with_io_error));
// Create the file. `File` implements `AsyncWrite`.
let path = std::path::Path::new(UPLOADS_DIRECTORY).join(path);
let mut file = BufWriter::new(File::create(path).await?);
// Copy the body into the file.
tokio::io::copy(&mut body_reader, &mut file).await?;
Ok::<_, io::Error>(())
}
.await
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
}
// to prevent directory traversal attacks we ensure the path consists of exactly one normal
// component
fn path_is_valid(path: &str) -> bool {
let path = std::path::Path::new(path);
let mut components = path.components().peekable();
if let Some(first) = components.peek() {
if !matches!(first, std::path::Component::Normal(_)) {
return false;
}
}
components.count() == 1
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/tokio-postgres/src/main.rs | examples/tokio-postgres/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-tokio-postgres
//! ```
use axum::{
extract::{FromRef, FromRequestParts, State},
http::{request::Parts, StatusCode},
routing::get,
Router,
};
use bb8::{Pool, PooledConnection};
use bb8_postgres::PostgresConnectionManager;
use tokio_postgres::NoTls;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// set up connection pool
let manager =
PostgresConnectionManager::new_from_stringlike("host=localhost user=postgres", NoTls)
.unwrap();
let pool = Pool::builder().build(manager).await.unwrap();
// build our application with some routes
let app = Router::new()
.route(
"/",
get(using_connection_pool_extractor).post(using_connection_extractor),
)
.with_state(pool);
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;
async fn using_connection_pool_extractor(
State(pool): State<ConnectionPool>,
) -> Result<String, (StatusCode, String)> {
let conn = pool.get().await.map_err(internal_error)?;
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager<NoTls>>);
impl<S> FromRequestParts<S> for DatabaseConnection
where
ConnectionPool: FromRef<S>,
S: Send + Sync,
{
type Rejection = (StatusCode, String);
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let pool = ConnectionPool::from_ref(state);
let conn = pool.get_owned().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/templates/src/main.rs | examples/templates/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-templates
//! ```
use askama::Template;
use axum::{
extract,
http::StatusCode,
response::{Html, IntoResponse, Response},
routing::get,
Router,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// build our application with some routes
let app = app();
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
fn app() -> Router {
Router::new().route("/greet/{name}", get(greet))
}
async fn greet(extract::Path(name): extract::Path<String>) -> impl IntoResponse {
let template = HelloTemplate { name };
HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate {
name: String,
}
struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T>
where
T: Template,
{
fn into_response(self) -> Response {
match self.0.render() {
Ok(html) => Html(html).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to render template. Error: {err}"),
)
.into_response(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn test_main() {
let response = app()
.oneshot(
Request::builder()
.uri("/greet/Foo")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body();
let bytes = body.collect().await.unwrap().to_bytes();
let html = String::from_utf8(bytes.to_vec()).unwrap();
assert_eq!(html, "<h1>Hello, Foo!</h1>");
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/testing/src/main.rs | examples/testing/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo test -p example-testing
//! ```
use std::net::SocketAddr;
use axum::{
extract::ConnectInfo,
routing::{get, post},
Json, Router,
};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app()).await;
}
/// Having a function that produces our app makes it easy to call it from tests
/// without having to create an HTTP server.
fn app() -> Router {
Router::new()
.route("/", get(|| async { "Hello, World!" }))
.route(
"/json",
post(|payload: Json<serde_json::Value>| async move {
Json(serde_json::json!({ "data": payload.0 }))
}),
)
.route(
"/requires-connect-info",
get(|ConnectInfo(addr): ConnectInfo<SocketAddr>| async move { format!("Hi {addr}") }),
)
// We can still add middleware
.layer(TraceLayer::new_for_http())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
extract::connect_info::MockConnectInfo,
http::{self, Request, StatusCode},
};
use http_body_util::BodyExt; // for `collect`
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tower::{Service, ServiceExt}; // for `call`, `oneshot`, and `ready`
#[tokio::test]
async fn hello_world() {
let app = app();
// `Router` implements `tower::Service<Request<Body>>` so we can
// call it like any tower service, no need to run an HTTP server.
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"Hello, World!");
}
#[tokio::test]
async fn json() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method(http::Method::POST)
.uri("/json")
.header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
.body(Body::from(
serde_json::to_vec(&json!([1, 2, 3, 4])).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(body, json!({ "data": [1, 2, 3, 4] }));
}
#[tokio::test]
async fn not_found() {
let app = app();
let response = app
.oneshot(
Request::builder()
.uri("/does-not-exist")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert!(body.is_empty());
}
// You can also spawn a server and talk to it like any other HTTP server:
#[tokio::test]
async fn the_real_deal() {
let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app()).await;
});
let client =
hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
.build_http();
let response = client
.request(
Request::builder()
.uri(format!("http://{addr}"))
.header("Host", "localhost")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"Hello, World!");
}
// You can use `ready()` and `call()` to avoid using `clone()`
// in multiple request
#[tokio::test]
async fn multiple_request() {
let mut app = app().into_service();
let request = Request::builder().uri("/").body(Body::empty()).unwrap();
let response = ServiceExt::<Request<Body>>::ready(&mut app)
.await
.unwrap()
.call(request)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let request = Request::builder().uri("/").body(Body::empty()).unwrap();
let response = ServiceExt::<Request<Body>>::ready(&mut app)
.await
.unwrap()
.call(request)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
// Here we're calling `/requires-connect-info` which requires `ConnectInfo`
//
// That is normally set with `Router::into_make_service_with_connect_info` but we can't easily
// use that during tests. The solution is instead to set the `MockConnectInfo` layer during
// tests.
#[tokio::test]
async fn with_into_make_service_with_connect_info() {
let mut app = app()
.layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000))))
.into_service();
let request = Request::builder()
.uri("/requires-connect-info")
.body(Body::empty())
.unwrap();
let response = app.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/simple-router-wasm/src/main.rs | examples/simple-router-wasm/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-simple-router-wasm
//! ```
//!
//! This example shows what using axum in a wasm context might look like. This example should
//! always compile with `--target wasm32-unknown-unknown`.
//!
//! [`mio`](https://docs.rs/mio/latest/mio/index.html), tokio's IO layer, does not support the
//! `wasm32-unknown-unknown` target which is why this crate requires `default-features = false`
//! for axum.
//!
//! Most serverless runtimes expect an exported function that takes in a single request and returns
//! a single response, much like axum's `Handler` trait. In this example, the handler function is
//! `app` with `main` acting as the serverless runtime which originally receives the request and
//! calls the app function.
//!
//! We can use axum's routing, extractors, tower services, and everything else to implement
//! our serverless function, even though we are running axum in a wasm context.
use axum::{
response::{Html, Response},
routing::get,
Router,
};
use futures_executor::block_on;
use http::Request;
use tower_service::Service;
fn main() {
let request: Request<String> = Request::builder()
.uri("https://serverless.example/api/")
.body("Some Body Data".into())
.unwrap();
let response: Response = block_on(app(request));
assert_eq!(200, response.status());
}
#[allow(clippy::let_and_return)]
async fn app(request: Request<String>) -> Response {
let mut router = Router::new().route("/api/", get(index));
let response = router.call(request).await.unwrap();
response
}
async fn index() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/parse-body-based-on-content-type/src/main.rs | examples/parse-body-based-on-content-type/src/main.rs | //! Provides a RESTful web server managing some Todos.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-parse-body-based-on-content-type
//! ```
use axum::{
extract::{FromRequest, Request},
http::{header::CONTENT_TYPE, StatusCode},
response::{IntoResponse, Response},
routing::post,
Form, Json, RequestExt, Router,
};
use serde::{Deserialize, Serialize};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let app = Router::new().route("/", post(handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
#[derive(Debug, Serialize, Deserialize)]
struct Payload {
foo: String,
}
async fn handler(JsonOrForm(payload): JsonOrForm<Payload>) {
dbg!(payload);
}
struct JsonOrForm<T>(T);
impl<S, T> FromRequest<S> for JsonOrForm<T>
where
S: Send + Sync,
Json<T>: FromRequest<()>,
Form<T>: FromRequest<()>,
T: 'static,
{
type Rejection = Response;
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let content_type_header = req.headers().get(CONTENT_TYPE);
let content_type = content_type_header.and_then(|value| value.to_str().ok());
if let Some(content_type) = content_type {
if content_type.starts_with("application/json") {
let Json(payload) = req.extract().await.map_err(IntoResponse::into_response)?;
return Ok(Self(payload));
}
if content_type.starts_with("application/x-www-form-urlencoded") {
let Form(payload) = req.extract().await.map_err(IntoResponse::into_response)?;
return Ok(Self(payload));
}
}
Err(StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response())
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/reqwest-response/src/main.rs | examples/reqwest-response/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-reqwest-response
//! ```
use axum::{
body::{Body, Bytes},
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Router,
};
use reqwest::Client;
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt;
use tower_http::trace::TraceLayer;
use tracing::Span;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let client = Client::new();
let app = Router::new()
.route("/", get(stream_reqwest_response))
.route("/stream", get(stream_some_data))
// Add some logging so we can see the streams going through
.layer(TraceLayer::new_for_http().on_body_chunk(
|chunk: &Bytes, _latency: Duration, _span: &Span| {
tracing::debug!("streaming {} bytes", chunk.len());
},
))
.with_state(client);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
async fn stream_reqwest_response(State(client): State<Client>) -> Response {
let reqwest_response = match client.get("http://127.0.0.1:3000/stream").send().await {
Ok(res) => res,
Err(err) => {
tracing::error!(%err, "request failed");
return (StatusCode::BAD_REQUEST, Body::empty()).into_response();
}
};
let mut response_builder = Response::builder().status(reqwest_response.status());
*response_builder.headers_mut().unwrap() = reqwest_response.headers().clone();
response_builder
.body(Body::from_stream(reqwest_response.bytes_stream()))
// This unwrap is fine because the body is empty here
.unwrap()
}
async fn stream_some_data() -> Body {
let stream = tokio_stream::iter(0..5)
.throttle(Duration::from_secs(1))
.map(|n| n.to_string())
.map(Ok::<_, Infallible>);
Body::from_stream(stream)
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/diesel-async-postgres/src/main.rs | examples/diesel-async-postgres/src/main.rs | //! Run with
//!
//! ```sh
//! export DATABASE_URL=postgres://localhost/your_db
//! cargo run -p example-diesel-async-postgres
//! ```
//!
//! Checkout the [diesel webpage](https://diesel.rs) for
//! longer guides about diesel
//!
//! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/)
//! for a real world application using axum and diesel
use axum::{
extract::{FromRef, FromRequestParts, State},
http::{request::Parts, StatusCode},
response::Json,
routing::{get, post},
Router,
};
use diesel::prelude::*;
use diesel_async::{
pooled_connection::{bb8, AsyncDieselConnectionManager},
AsyncMigrationHarness, AsyncPgConnection, RunQueryDsl,
};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use std::net::SocketAddr;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
// normally part of your generated schema.rs file
table! {
users (id) {
id -> Integer,
name -> Text,
hair_color -> Nullable<Text>,
}
}
#[derive(serde::Serialize, HasQuery)]
struct User {
id: i32,
name: String,
hair_color: Option<String>,
}
#[derive(serde::Deserialize, Insertable)]
#[diesel(table_name = users)]
struct NewUser {
name: String,
hair_color: Option<String>,
}
type Pool = bb8::Pool<AsyncPgConnection>;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
let db_url = std::env::var("DATABASE_URL").unwrap();
// set up connection pool
let config = AsyncDieselConnectionManager::<diesel_async::AsyncPgConnection>::new(db_url);
let pool = bb8::Pool::builder().build(config).await.unwrap();
let mut harness = AsyncMigrationHarness::new(pool.get_owned().await.unwrap());
harness.run_pending_migrations(MIGRATIONS).unwrap();
// build our application with some routes
let app = Router::new()
.route("/user/list", get(list_users))
.route("/user/create", post(create_user))
.with_state(pool);
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await;
}
async fn create_user(
State(pool): State<Pool>,
Json(new_user): Json<NewUser>,
) -> Result<Json<User>, (StatusCode, String)> {
let mut conn = pool.get().await.map_err(internal_error)?;
let res = diesel::insert_into(users::table)
.values(new_user)
.returning(User::as_returning())
.get_result(&mut conn)
.await
.map_err(internal_error)?;
Ok(Json(res))
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(bb8::PooledConnection<'static, AsyncPgConnection>);
impl<S> FromRequestParts<S> for DatabaseConnection
where
S: Send + Sync,
Pool: FromRef<S>,
{
type Rejection = (StatusCode, String);
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let pool = Pool::from_ref(state);
let conn = pool.get_owned().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
async fn list_users(
DatabaseConnection(mut conn): DatabaseConnection,
) -> Result<Json<Vec<User>>, (StatusCode, String)> {
let res = User::query()
.load(&mut conn)
.await
.map_err(internal_error)?;
Ok(Json(res))
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/websockets/src/client.rs | examples/websockets/src/client.rs | //! Based on tokio-tungstenite example websocket client, but with multiple
//! concurrent websocket clients in one package
//!
//! This will connect to a server specified in the SERVER with N_CLIENTS
//! concurrent connections, and then flood some test messages over websocket.
//! This will also print whatever it gets into stdout.
//!
//! Note that this is not currently optimized for performance, especially around
//! stdout mutex management. Rather it's intended to show an example of working with axum's
//! websocket server and how the client-side and server-side code can be quite similar.
//!
use futures_util::{SinkExt, StreamExt};
use std::ops::ControlFlow;
use std::time::Instant;
use tokio::task::JoinSet;
use tokio_tungstenite::tungstenite::Utf8Bytes;
// we will use tungstenite for websocket client impl (same library as what axum is using)
use tokio_tungstenite::{
connect_async,
tungstenite::protocol::{frame::coding::CloseCode, CloseFrame, Message},
};
const N_CLIENTS: usize = 2; //set to desired number
const SERVER: &str = "ws://127.0.0.1:3000/ws";
#[tokio::main]
async fn main() {
let start_time = Instant::now();
//spawn several clients that will concurrently talk to the server
let mut clients = (0..N_CLIENTS).map(spawn_client).collect::<JoinSet<_>>();
//wait for all our clients to exit
while clients.join_next().await.is_some() {}
let end_time = Instant::now();
//total time should be the same no matter how many clients we spawn
println!(
"Total time taken {:#?} with {N_CLIENTS} concurrent clients, should be about 6.45 seconds.",
end_time - start_time
);
}
//creates a client. quietly exits on failure.
async fn spawn_client(who: usize) {
let ws_stream = match connect_async(SERVER).await {
Ok((stream, response)) => {
println!("Handshake for client {who} has been completed");
// This will be the HTTP response, same as with server this is the last moment we
// can still access HTTP stuff.
println!("Server response was {response:?}");
stream
}
Err(e) => {
println!("WebSocket handshake for client {who} failed with {e}!");
return;
}
};
let (mut sender, mut receiver) = ws_stream.split();
//we can ping the server for start
sender
.send(Message::Ping(axum::body::Bytes::from_static(
b"Hello, Server!",
)))
.await
.expect("Can not send!");
//spawn an async sender to push some more messages into the server
let mut send_task = tokio::spawn(async move {
for i in 1..30 {
// In any websocket error, break loop.
if sender
.send(Message::Text(format!("Message number {i}...").into()))
.await
.is_err()
{
//just as with server, if send fails there is nothing we can do but exit.
return;
}
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
}
// When we are done we may want our client to close connection cleanly.
println!("Sending close to {who}...");
if let Err(e) = sender
.send(Message::Close(Some(CloseFrame {
code: CloseCode::Normal,
reason: Utf8Bytes::from_static("Goodbye"),
})))
.await
{
println!("Could not send Close due to {e:?}, probably it is ok?");
};
});
//receiver just prints whatever it gets
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(msg)) = receiver.next().await {
// print message and break if instructed to do so
if process_message(msg, who).is_break() {
break;
}
}
});
//wait for either task to finish and kill the other task
tokio::select! {
_ = (&mut send_task) => {
recv_task.abort();
},
_ = (&mut recv_task) => {
send_task.abort();
}
}
}
/// Function to handle messages we get (with a slight twist that Frame variant is visible
/// since we are working with the underlying tungstenite library directly without axum here).
fn process_message(msg: Message, who: usize) -> ControlFlow<(), ()> {
match msg {
Message::Text(t) => {
println!(">>> {who} got str: {t:?}");
}
Message::Binary(d) => {
println!(">>> {who} got {} bytes: {d:?}", d.len());
}
Message::Close(c) => {
if let Some(cf) = c {
println!(
">>> {who} got close with code {} and reason `{}`",
cf.code, cf.reason
);
} else {
println!(">>> {who} somehow got close message without CloseFrame");
}
return ControlFlow::Break(());
}
Message::Pong(v) => {
println!(">>> {who} got pong with {v:?}");
}
// Just as with axum server, the underlying tungstenite websocket library
// will handle Ping for you automagically by replying with Pong and copying the
// v according to spec. But if you need the contents of the pings you can see them here.
Message::Ping(v) => {
println!(">>> {who} got ping with {v:?}");
}
Message::Frame(_) => {
unreachable!("This is never supposed to happen")
}
}
ControlFlow::Continue(())
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/websockets/src/main.rs | examples/websockets/src/main.rs | //! Example websocket server.
//!
//! Run the server with
//! ```not_rust
//! cargo run -p example-websockets --bin example-websockets
//! ```
//!
//! Run a browser client with
//! ```not_rust
//! firefox http://localhost:3000
//! ```
//!
//! Alternatively you can run the rust client (showing two
//! concurrent websocket connections being established) with
//! ```not_rust
//! cargo run -p example-websockets --bin example-client
//! ```
use axum::{
body::Bytes,
extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},
response::IntoResponse,
routing::any,
Router,
};
use axum_extra::TypedHeader;
use std::ops::ControlFlow;
use std::{net::SocketAddr, path::PathBuf};
use tower_http::{
services::ServeDir,
trace::{DefaultMakeSpan, TraceLayer},
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
//allows to extract the IP of connecting user
use axum::extract::connect_info::ConnectInfo;
use axum::extract::ws::CloseFrame;
//allows to split the websocket stream into separate TX and RX branches
use futures_util::{sink::SinkExt, stream::StreamExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");
// build our application with some routes
let app = Router::new()
.fallback_service(ServeDir::new(assets_dir).append_index_html_on_directories(true))
.route("/ws", any(ws_handler))
// logging so we can see what's going on
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::default().include_headers(true)),
);
// run it with hyper
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.await;
}
/// The handler for the HTTP request (this gets called when the HTTP request lands at the start
/// of websocket negotiation). After this completes, the actual switching from HTTP to
/// websocket protocol will occur.
/// This is the last point where we can extract TCP/IP metadata such as IP address of the client
/// as well as things from HTTP headers such as user-agent of the browser etc.
async fn ws_handler(
ws: WebSocketUpgrade,
user_agent: Option<TypedHeader<headers::UserAgent>>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
) -> impl IntoResponse {
let user_agent = if let Some(TypedHeader(user_agent)) = user_agent {
user_agent.to_string()
} else {
String::from("Unknown browser")
};
println!("`{user_agent}` at {addr} connected.");
// finalize the upgrade process by returning upgrade callback.
// we can customize the callback by sending additional info such as address.
ws.on_upgrade(move |socket| handle_socket(socket, addr))
}
/// Actual websocket statemachine (one will be spawned per connection)
async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
// send a ping (unsupported by some browsers) just to kick things off and get a response
if socket
.send(Message::Ping(Bytes::from_static(&[1, 2, 3])))
.await
.is_ok()
{
println!("Pinged {who}...");
} else {
println!("Could not send ping {who}!");
// no Error here since the only thing we can do is to close the connection.
// If we can not send messages, there is no way to salvage the statemachine anyway.
return;
}
// receive single message from a client (we can either receive or send with socket).
// this will likely be the Pong for our Ping or a hello message from client.
// waiting for message from a client will block this task, but will not block other client's
// connections.
if let Some(msg) = socket.recv().await {
if let Ok(msg) = msg {
if process_message(msg, who).is_break() {
return;
}
} else {
println!("client {who} abruptly disconnected");
return;
}
}
// Since each client gets individual statemachine, we can pause handling
// when necessary to wait for some external event (in this case illustrated by sleeping).
// Waiting for this client to finish getting its greetings does not prevent other clients from
// connecting to server and receiving their greetings.
for i in 1..5 {
if socket
.send(Message::Text(format!("Hi {i} times!").into()))
.await
.is_err()
{
println!("client {who} abruptly disconnected");
return;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
// By splitting socket we can send and receive at the same time. In this example we will send
// unsolicited messages to client based on some sort of server's internal event (i.e .timer).
let (mut sender, mut receiver) = socket.split();
// Spawn a task that will push several messages to the client (does not matter what client does)
let mut send_task = tokio::spawn(async move {
let n_msg = 20;
for i in 0..n_msg {
// In case of any websocket error, we exit.
if sender
.send(Message::Text(format!("Server message {i} ...").into()))
.await
.is_err()
{
return i;
}
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
}
println!("Sending close to {who}...");
if let Err(e) = sender
.send(Message::Close(Some(CloseFrame {
code: axum::extract::ws::close_code::NORMAL,
reason: Utf8Bytes::from_static("Goodbye"),
})))
.await
{
println!("Could not send Close due to {e}, probably it is ok?");
}
n_msg
});
// This second task will receive messages from client and print them on server console
let mut recv_task = tokio::spawn(async move {
let mut cnt = 0;
while let Some(Ok(msg)) = receiver.next().await {
cnt += 1;
// print message and break if instructed to do so
if process_message(msg, who).is_break() {
break;
}
}
cnt
});
// If any one of the tasks exit, abort the other.
tokio::select! {
rv_a = (&mut send_task) => {
match rv_a {
Ok(a) => println!("{a} messages sent to {who}"),
Err(a) => println!("Error sending messages {a:?}")
}
recv_task.abort();
},
rv_b = (&mut recv_task) => {
match rv_b {
Ok(b) => println!("Received {b} messages"),
Err(b) => println!("Error receiving messages {b:?}")
}
send_task.abort();
}
}
// returning from the handler closes the websocket connection
println!("Websocket context {who} destroyed");
}
/// helper to print contents of messages to stdout. Has special treatment for Close.
fn process_message(msg: Message, who: SocketAddr) -> ControlFlow<(), ()> {
match msg {
Message::Text(t) => {
println!(">>> {who} sent str: {t:?}");
}
Message::Binary(d) => {
println!(">>> {who} sent {} bytes: {d:?}", d.len());
}
Message::Close(c) => {
if let Some(cf) = c {
println!(
">>> {who} sent close with code {} and reason `{}`",
cf.code, cf.reason
);
} else {
println!(">>> {who} somehow sent close message without CloseFrame");
}
return ControlFlow::Break(());
}
Message::Pong(v) => {
println!(">>> {who} sent pong with {v:?}");
}
// You should never need to manually handle Message::Ping, as axum's websocket library
// will do so for you automagically by replying with Pong and copying the v according to
// spec. But if you need the contents of the pings you can see them here.
Message::Ping(v) => {
println!(">>> {who} sent ping with {v:?}");
}
}
ControlFlow::Continue(())
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/websockets-http2/src/main.rs | examples/websockets-http2/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-websockets-http2
//! ```
use axum::{
extract::{
ws::{self, WebSocketUpgrade},
State,
},
http::Version,
routing::any,
Router,
};
use axum_server::tls_rustls::RustlsConfig;
use std::{net::SocketAddr, path::PathBuf};
use tokio::sync::broadcast;
use tower_http::services::ServeDir;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");
// configure certificate and private key used by https
let config = RustlsConfig::from_pem_file(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("self_signed_certs")
.join("cert.pem"),
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("self_signed_certs")
.join("key.pem"),
)
.await
.unwrap();
// build our application with some routes and a broadcast channel
let app = Router::new()
.fallback_service(ServeDir::new(assets_dir).append_index_html_on_directories(true))
.route("/ws", any(ws_handler))
.with_state(broadcast::channel::<String>(16).0);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
let mut server = axum_server::bind_rustls(addr, config);
// IMPORTANT: This is required to advertise our support for HTTP/2 websockets to the client.
// If you use axum::serve, it is enabled by default.
server.http_builder().http2().enable_connect_protocol();
server.serve(app.into_make_service()).await.unwrap();
}
async fn ws_handler(
ws: WebSocketUpgrade,
version: Version,
State(sender): State<broadcast::Sender<String>>,
) -> axum::response::Response {
tracing::debug!("accepted a WebSocket using {version:?}");
let mut receiver = sender.subscribe();
ws.on_upgrade(|mut ws| async move {
loop {
tokio::select! {
// Since `ws` is a `Stream`, it is by nature cancel-safe.
res = ws.recv() => {
match res {
Some(Ok(ws::Message::Text(s))) => {
let _ = sender.send(s.to_string());
}
Some(Ok(_)) => {}
Some(Err(e)) => tracing::debug!("client disconnected abruptly: {e}"),
None => break,
}
}
// Tokio guarantees that `broadcast::Receiver::recv` is cancel-safe.
res = receiver.recv() => {
match res {
Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg.into())).await {
tracing::debug!("client disconnected abruptly: {e}");
}
Err(_) => continue,
}
}
}
}
})
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/form/src/main.rs | examples/form/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-form
//! ```
use axum::{extract::Form, response::Html, routing::get, Router};
use serde::Deserialize;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// build our application with some routes
let app = app();
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
fn app() -> Router {
Router::new().route("/", get(show_form).post(accept_form))
}
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post">
<label for="name">
Enter your name:
<input type="text" name="name">
</label>
<label>
Enter your email:
<input type="text" name="email">
</label>
<input type="submit" value="Subscribe!">
</form>
</body>
</html>
"#,
)
}
#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct Input {
name: String,
email: String,
}
async fn accept_form(Form(input): Form<Input>) -> Html<String> {
dbg!(&input);
Html(format!(
"email='{}'\nname='{}'\n",
&input.email, &input.name
))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{self, Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt; // for `call`, `oneshot`, and `ready` // for `collect`
#[tokio::test]
async fn test_get() {
let app = app();
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body = std::str::from_utf8(&body).unwrap();
assert!(body.contains(r#"<input type="submit" value="Subscribe!">"#));
}
#[tokio::test]
async fn test_post() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method(http::Method::POST)
.uri("/")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::from("name=foo&email=bar@axum"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body = std::str::from_utf8(&body).unwrap();
assert_eq!(body, "email='bar@axum'\nname='foo'\n");
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/validator/src/main.rs | examples/validator/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-validator
//!
//! curl '127.0.0.1:3000?name='
//! -> Input validation error: [name: Can not be empty]
//!
//! curl '127.0.0.1:3000?name=LT'
//! -> <h1>Hello, LT!</h1>
//! ```
use axum::{
extract::{rejection::FormRejection, Form, FromRequest, Request},
http::StatusCode,
response::{Html, IntoResponse, Response},
routing::get,
Router,
};
use serde::{de::DeserializeOwned, Deserialize};
use thiserror::Error;
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use validator::Validate;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// build our application with a route
let app = app();
// run it
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
fn app() -> Router {
Router::new().route("/", get(handler))
}
#[derive(Debug, Deserialize, Validate)]
pub struct NameInput {
#[validate(length(min = 2, message = "Can not be empty"))]
pub name: String,
}
async fn handler(ValidatedForm(input): ValidatedForm<NameInput>) -> Html<String> {
Html(format!("<h1>Hello, {}!</h1>", input.name))
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedForm<T>(pub T);
impl<T, S> FromRequest<S> for ValidatedForm<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
Form<T>: FromRequest<S, Rejection = FormRejection>,
{
type Rejection = ServerError;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Form(value) = Form::<T>::from_request(req, state).await?;
value.validate()?;
Ok(ValidatedForm(value))
}
}
#[derive(Debug, Error)]
pub enum ServerError {
#[error(transparent)]
ValidationError(#[from] validator::ValidationErrors),
#[error(transparent)]
AxumFormRejection(#[from] FormRejection),
}
impl IntoResponse for ServerError {
fn into_response(self) -> Response {
match self {
ServerError::ValidationError(_) => {
let message = format!("Input validation error: [{self}]").replace('\n', ", ");
(StatusCode::BAD_REQUEST, message)
}
ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),
}
.into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
async fn get_html(response: Response<Body>) -> String {
let body = response.into_body();
let bytes = body.collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn test_no_param() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(html, "Failed to deserialize form: missing field `name`");
}
#[tokio::test]
async fn test_with_param_without_value() {
let response = app()
.oneshot(
Request::builder()
.uri("/?name=")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(html, "Input validation error: [name: Can not be empty]");
}
#[tokio::test]
async fn test_with_param_with_short_value() {
let response = app()
.oneshot(
Request::builder()
.uri("/?name=X")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(html, "Input validation error: [name: Can not be empty]");
}
#[tokio::test]
async fn test_with_param_and_value() {
let response = app()
.oneshot(
Request::builder()
.uri("/?name=LT")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let html = get_html(response).await;
assert_eq!(html, "<h1>Hello, LT!</h1>");
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/routes-and-handlers-close-together/src/main.rs | examples/routes-and-handlers-close-together/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-routes-and-handlers-close-together
//! ```
use axum::{
routing::{get, post, MethodRouter},
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.merge(root())
.merge(get_foo())
.merge(post_foo());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
fn root() -> Router {
async fn handler() -> &'static str {
"Hello, World!"
}
route("/", get(handler))
}
fn get_foo() -> Router {
async fn handler() -> &'static str {
"Hi from `GET /foo`"
}
route("/foo", get(handler))
}
fn post_foo() -> Router {
async fn handler() -> &'static str {
"Hi from `POST /foo`"
}
route("/foo", post(handler))
}
fn route(path: &str, method_router: MethodRouter<()>) -> Router {
Router::new().route(path, method_router)
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/prometheus-metrics/src/main.rs | examples/prometheus-metrics/src/main.rs | //! Someday tower-http will hopefully have a metrics middleware, until then you can track
//! metrics like this.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-prometheus-metrics
//! ```
use axum::{
extract::{MatchedPath, Request},
middleware::{self, Next},
response::IntoResponse,
routing::get,
Router,
};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
use std::{
future::ready,
time::{Duration, Instant},
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
fn metrics_app() -> Router {
let recorder_handle = setup_metrics_recorder();
Router::new().route("/metrics", get(move || ready(recorder_handle.render())))
}
fn main_app() -> Router {
Router::new()
.route("/fast", get(|| async {}))
.route(
"/slow",
get(|| async {
tokio::time::sleep(Duration::from_secs(1)).await;
}),
)
.route_layer(middleware::from_fn(track_metrics))
}
async fn start_main_server() {
let app = main_app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
async fn start_metrics_server() {
let app = metrics_app();
// NOTE: expose metrics endpoint on a different port
let listener = tokio::net::TcpListener::bind("127.0.0.1:3001")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
// The `/metrics` endpoint should not be publicly available. If behind a reverse proxy, this
// can be achieved by rejecting requests to `/metrics`. In this example, a second server is
// started on another port to expose `/metrics`.
let (_main_server, _metrics_server) = tokio::join!(start_main_server(), start_metrics_server());
}
fn setup_metrics_recorder() -> PrometheusHandle {
const EXPONENTIAL_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
let recorder_handle = PrometheusBuilder::new()
.set_buckets_for_metric(
Matcher::Full("http_requests_duration_seconds".to_string()),
EXPONENTIAL_SECONDS,
)
.unwrap()
.install_recorder()
.unwrap();
let upkeep_handle = recorder_handle.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(5)).await;
upkeep_handle.run_upkeep();
}
});
recorder_handle
}
async fn track_metrics(req: Request, next: Next) -> impl IntoResponse {
let start = Instant::now();
let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
matched_path.as_str().to_owned()
} else {
req.uri().path().to_owned()
};
let method = req.method().clone();
let response = next.run(req).await;
let latency = start.elapsed().as_secs_f64();
let status = response.status().as_u16().to_string();
let labels = [
("method", method.to_string()),
("path", path),
("status", status),
];
metrics::counter!("http_requests_total", &labels).increment(1);
metrics::histogram!("http_requests_duration_seconds", &labels).record(latency);
response
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/print-request-response/src/main.rs | examples/print-request-response/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-print-request-response
//! ```
use axum::{
body::{Body, Bytes},
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::post,
Router,
};
use http_body_util::BodyExt;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let app = Router::new()
.route("/", post(|| async move { "Hello from `POST /`" }))
.layer(middleware::from_fn(print_request_response));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
async fn print_request_response(
req: Request,
next: Next,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let (parts, body) = req.into_parts();
let bytes = buffer_and_print("request", body).await?;
let req = Request::from_parts(parts, Body::from(bytes));
let res = next.run(req).await;
let (parts, body) = res.into_parts();
let bytes = buffer_and_print("response", body).await?;
let res = Response::from_parts(parts, Body::from(bytes));
Ok(res)
}
async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, (StatusCode, String)>
where
B: axum::body::HttpBody<Data = Bytes>,
B::Error: std::fmt::Display,
{
let bytes = match body.collect().await {
Ok(collected) => collected.to_bytes(),
Err(err) => {
return Err((
StatusCode::BAD_REQUEST,
format!("failed to read {direction} body: {err}"),
));
}
};
if let Ok(body) = std::str::from_utf8(&bytes) {
tracing::debug!("{direction} body = {body:?}");
}
Ok(bytes)
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/testing-websockets/src/main.rs | examples/testing-websockets/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo test -p example-testing-websockets
//! ```
use axum::{
extract::{
ws::{Message, WebSocket},
WebSocketUpgrade,
},
response::Response,
routing::get,
Router,
};
use futures_util::{Sink, SinkExt, Stream, StreamExt};
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app()).await;
}
fn app() -> Router {
// WebSocket routes can generally be tested in two ways:
//
// - Integration tests where you run the server and connect with a real WebSocket client.
// - Unit tests where you mock the socket as some generic send/receive type
//
// Which version you pick is up to you. Generally we recommend the integration test version
// unless your app has a lot of setup that makes it hard to run in a test.
Router::new()
.route("/integration-testable", get(integration_testable_handler))
.route("/unit-testable", get(unit_testable_handler))
}
// A WebSocket handler that echos any message it receives.
//
// This one we'll be integration testing so it can be written in the regular way.
async fn integration_testable_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(integration_testable_handle_socket)
}
async fn integration_testable_handle_socket(mut socket: WebSocket) {
while let Some(Ok(msg)) = socket.recv().await {
if let Message::Text(msg) = msg {
if socket
.send(Message::Text(format!("You said: {msg}").into()))
.await
.is_err()
{
break;
}
}
}
}
// The unit testable version requires some changes.
//
// By splitting the socket into an `impl Sink` and `impl Stream` we can test without providing a
// real socket and instead using channels, which also implement `Sink` and `Stream`.
async fn unit_testable_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(|socket| {
let (write, read) = socket.split();
unit_testable_handle_socket(write, read)
})
}
// The implementation is largely the same as `integration_testable_handle_socket` expect we call
// methods from `SinkExt` and `StreamExt`.
async fn unit_testable_handle_socket<W, R>(mut write: W, mut read: R)
where
W: Sink<Message> + Unpin,
R: Stream<Item = Result<Message, axum::Error>> + Unpin,
{
while let Some(Ok(msg)) = read.next().await {
if let Message::Text(msg) = msg {
if write
.send(Message::Text(format!("You said: {msg}").into()))
.await
.is_err()
{
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
future::IntoFuture,
net::{Ipv4Addr, SocketAddr},
};
use tokio_tungstenite::tungstenite;
// We can integration test one handler by running the server in a background task and
// connecting to it like any other client would.
#[tokio::test]
async fn integration_test() {
let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))
.await
.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(axum::serve(listener, app()).into_future());
let (mut socket, _response) =
tokio_tungstenite::connect_async(format!("ws://{addr}/integration-testable"))
.await
.unwrap();
socket
.send(tungstenite::Message::text("foo"))
.await
.unwrap();
let msg = match socket.next().await.unwrap().unwrap() {
tungstenite::Message::Text(msg) => msg,
other => panic!("expected a text message but got {other:?}"),
};
assert_eq!(msg.as_str(), "You said: foo");
}
// We can unit test the other handler by creating channels to read and write from.
#[tokio::test]
async fn unit_test() {
// Need to use "futures" channels rather than "tokio" channels as they implement `Sink` and
// `Stream`
let (socket_write, mut test_rx) = futures_channel::mpsc::channel(1024);
let (mut test_tx, socket_read) = futures_channel::mpsc::channel(1024);
tokio::spawn(unit_testable_handle_socket(socket_write, socket_read));
test_tx.send(Ok(Message::Text("foo".into()))).await.unwrap();
let msg = match test_rx.next().await.unwrap() {
Message::Text(msg) => msg,
other => panic!("expected a text message but got {other:?}"),
};
assert_eq!(msg.as_str(), "You said: foo");
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/error-handling/src/main.rs | examples/error-handling/src/main.rs | //! Example showing how to convert errors into responses.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-error-handling
//! ```
//!
//! For successful requests the log output will be
//!
//! ```ignore
//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_request: started processing request
//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
//! ```
//!
//! For failed requests the log output will be
//!
//! ```ignore
//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_request: started processing request
//! ERROR request{method=POST uri=/users matched_path="/users"}: example_error_handling: error from time_library err=failed to get time
//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_response: finished processing request latency=0 ms status=500
//! ```
use std::{
collections::HashMap,
sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex,
},
};
use axum::{
extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request, State},
http::StatusCode,
middleware::{from_fn, Next},
response::{IntoResponse, Response},
routing::post,
Router,
};
use serde::{Deserialize, Serialize};
use time_library::Timestamp;
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let state = AppState::default();
let app = Router::new()
// A dummy route that accepts some JSON but sometimes fails
.route("/users", post(users_create))
.layer(
TraceLayer::new_for_http()
// Create our own span for the request and include the matched path. The matched
// path is useful for figuring out which handler the request was routed to.
.make_span_with(|req: &Request| {
let method = req.method();
let uri = req.uri();
// axum automatically adds this extension.
let matched_path = req
.extensions()
.get::<MatchedPath>()
.map(|matched_path| matched_path.as_str());
tracing::debug_span!("request", %method, %uri, matched_path)
})
// By default `TraceLayer` will log 5xx responses but we're doing our specific
// logging of errors so disable that
.on_failure(()),
)
.layer(from_fn(log_app_errors))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
#[derive(Default, Clone)]
struct AppState {
next_id: Arc<AtomicU64>,
users: Arc<Mutex<HashMap<u64, User>>>,
}
#[derive(Deserialize)]
struct UserParams {
name: String,
}
#[derive(Serialize, Clone)]
struct User {
id: u64,
name: String,
created_at: Timestamp,
}
async fn users_create(
State(state): State<AppState>,
// Make sure to use our own JSON extractor so we get input errors formatted in a way that
// matches our application
AppJson(params): AppJson<UserParams>,
) -> Result<AppJson<User>, AppError> {
let id = state.next_id.fetch_add(1, Ordering::SeqCst);
// We have implemented `From<time_library::Error> for AppError` which allows us to use `?` to
// automatically convert the error
let created_at = Timestamp::now()?;
let user = User {
id,
name: params.name,
created_at,
};
state.users.lock().unwrap().insert(id, user.clone());
Ok(AppJson(user))
}
// Create our own JSON extractor by wrapping `axum::Json`. This makes it easy to override the
// rejection and provide our own which formats errors to match our application.
//
// `axum::Json` responds with plain text if the input is invalid.
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(AppError))]
struct AppJson<T>(T);
impl<T> IntoResponse for AppJson<T>
where
axum::Json<T>: IntoResponse,
{
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}
// The kinds of errors we can hit in our application.
#[derive(Debug)]
enum AppError {
// The request body contained invalid JSON
JsonRejection(JsonRejection),
// Some error from a third party library we're using
TimeError(time_library::Error),
}
// Tell axum how `AppError` should be converted into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
// How we want errors responses to be serialized
#[derive(Serialize)]
struct ErrorResponse {
message: String,
}
let (status, message, err) = match &self {
AppError::JsonRejection(rejection) => {
// This error is caused by bad user input so don't log it
(rejection.status(), rejection.body_text(), None)
}
AppError::TimeError(_err) => {
// While we could simply log the error here we would introduce
// a side-effect to our conversion, instead add the AppError to
// the Response as an Extension
// Don't expose any details about the error to the client
(
StatusCode::INTERNAL_SERVER_ERROR,
"Something went wrong".to_owned(),
Some(self),
)
}
};
let mut response = (status, AppJson(ErrorResponse { message })).into_response();
if let Some(err) = err {
// Insert our error into the response, our logging middleware will use this.
// By wrapping the error in an Arc we can use it as an Extension regardless of any inner types not deriving Clone.
response.extensions_mut().insert(Arc::new(err));
}
response
}
}
impl From<JsonRejection> for AppError {
fn from(rejection: JsonRejection) -> Self {
Self::JsonRejection(rejection)
}
}
impl From<time_library::Error> for AppError {
fn from(error: time_library::Error) -> Self {
Self::TimeError(error)
}
}
// Our middleware is responsible for logging error details internally
async fn log_app_errors(request: Request, next: Next) -> Response {
let response = next.run(request).await;
// If the response contains an AppError Extension, log it.
if let Some(err) = response.extensions().get::<Arc<AppError>>() {
tracing::error!(?err, "an unexpected error occurred inside a handler");
}
response
}
// Imagine this is some third party library that we're using. It sometimes returns errors which we
// want to log.
mod time_library {
use std::sync::atomic::{AtomicU64, Ordering};
use serde::Serialize;
#[derive(Serialize, Clone)]
pub struct Timestamp(u64);
impl Timestamp {
pub fn now() -> Result<Self, Error> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
// Fail on every third call just to simulate errors
if COUNTER.fetch_add(1, Ordering::SeqCst).is_multiple_of(3) {
Err(Error::FailedToGetTime)
} else {
Ok(Self(1337))
}
}
}
#[derive(Debug, Clone)]
pub enum Error {
FailedToGetTime,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "failed to get time")
}
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/todos/src/main.rs | examples/todos/src/main.rs | //! Provides a RESTful web server managing some Todos.
//!
//! API will be:
//!
//! - `GET /todos`: return a JSON list of Todos.
//! - `POST /todos`: create a new Todo.
//! - `PATCH /todos/{id}`: update a specific Todo.
//! - `DELETE /todos/{id}`: delete a specific Todo.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-todos
//! ```
use axum::{
error_handling::HandleErrorLayer,
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
routing::{get, patch},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
sync::{Arc, RwLock},
time::Duration,
};
use tower::{BoxError, ServiceBuilder};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let db = Db::default();
// Compose the routes
let app = Router::new()
.route("/todos", get(todos_index).post(todos_create))
.route("/todos/{id}", patch(todos_update).delete(todos_delete))
// Add middleware to all routes
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
if error.is::<tower::timeout::error::Elapsed>() {
Ok(StatusCode::REQUEST_TIMEOUT)
} else {
Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {error}"),
))
}
}))
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.into_inner(),
)
.with_state(db);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
// The query parameters for todos index
#[derive(Debug, Deserialize, Default)]
pub struct Pagination {
pub offset: Option<usize>,
pub limit: Option<usize>,
}
async fn todos_index(pagination: Query<Pagination>, State(db): State<Db>) -> impl IntoResponse {
let todos = db.read().unwrap();
let todos = todos
.values()
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(usize::MAX))
.cloned()
.collect::<Vec<_>>();
Json(todos)
}
#[derive(Debug, Deserialize)]
struct CreateTodo {
text: String,
}
async fn todos_create(State(db): State<Db>, Json(input): Json<CreateTodo>) -> impl IntoResponse {
let todo = Todo {
id: Uuid::new_v4(),
text: input.text,
completed: false,
};
db.write().unwrap().insert(todo.id, todo.clone());
(StatusCode::CREATED, Json(todo))
}
#[derive(Debug, Deserialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
}
async fn todos_update(
Path(id): Path<Uuid>,
State(db): State<Db>,
Json(input): Json<UpdateTodo>,
) -> Result<impl IntoResponse, StatusCode> {
let mut todo = db
.read()
.unwrap()
.get(&id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(text) = input.text {
todo.text = text;
}
if let Some(completed) = input.completed {
todo.completed = completed;
}
db.write().unwrap().insert(todo.id, todo.clone());
Ok(Json(todo))
}
async fn todos_delete(Path(id): Path<Uuid>, State(db): State<Db>) -> impl IntoResponse {
if db.write().unwrap().remove(&id).is_some() {
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND
}
}
type Db = Arc<RwLock<HashMap<Uuid, Todo>>>;
#[derive(Debug, Serialize, Clone)]
struct Todo {
id: Uuid,
text: String,
completed: bool,
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/unix-domain-socket/src/main.rs | examples/unix-domain-socket/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-unix-domain-socket
//! ```
#[cfg(unix)]
#[tokio::main]
async fn main() {
unix::server().await;
}
#[cfg(not(unix))]
fn main() {
println!("This example requires unix")
}
#[cfg(unix)]
mod unix {
use axum::{
body::Body,
extract::connect_info::{self, ConnectInfo},
http::{Method, Request, StatusCode},
routing::get,
serve::IncomingStream,
Router,
};
use http_body_util::BodyExt;
use hyper_util::rt::TokioIo;
use std::{path::PathBuf, sync::Arc};
use tokio::net::{unix::UCred, UnixListener, UnixStream};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
pub async fn server() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
let path = PathBuf::from("/tmp/axum/helloworld");
let _ = tokio::fs::remove_file(&path).await;
tokio::fs::create_dir_all(path.parent().unwrap())
.await
.unwrap();
let uds = UnixListener::bind(path.clone()).unwrap();
tokio::spawn(async move {
let app = Router::new()
.route("/", get(handler))
.into_make_service_with_connect_info::<UdsConnectInfo>();
axum::serve(uds, app).await;
});
let stream = TokioIo::new(UnixStream::connect(path).await.unwrap());
let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
tokio::task::spawn(async move {
if let Err(err) = conn.await {
println!("Connection failed: {err:?}");
}
});
let request = Request::builder()
.method(Method::GET)
.uri("http://uri-doesnt-matter.com")
.body(Body::empty())
.unwrap();
let response = sender.send_request(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.collect().await.unwrap().to_bytes();
let body = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body, "Hello, World!");
}
async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
println!("new connection from `{info:?}`");
"Hello, World!"
}
#[derive(Clone, Debug)]
#[allow(dead_code)]
struct UdsConnectInfo {
peer_addr: Arc<tokio::net::unix::SocketAddr>,
peer_cred: UCred,
}
impl connect_info::Connected<IncomingStream<'_, UnixListener>> for UdsConnectInfo {
fn connect_info(stream: IncomingStream<'_, UnixListener>) -> Self {
let peer_addr = stream.io().peer_addr().unwrap();
let peer_cred = stream.io().peer_cred().unwrap();
Self {
peer_addr: Arc::new(peer_addr),
peer_cred,
}
}
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/tls-rustls/src/main.rs | examples/tls-rustls/src/main.rs | //! Run with
//!
//! ```not_rust
//! cargo run -p example-tls-rustls
//! ```
#![allow(unused_imports)]
use axum::{
handler::HandlerWithoutStateExt,
http::{uri::Authority, StatusCode, Uri},
response::Redirect,
routing::get,
BoxError, Router,
};
use axum_server::tls_rustls::RustlsConfig;
use std::{net::SocketAddr, path::PathBuf};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct Ports {
http: u16,
https: u16,
}
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
let ports = Ports {
http: 7878,
https: 3000,
};
// optional: spawn a second server to redirect http requests to this server
tokio::spawn(redirect_http_to_https(ports));
// configure certificate and private key used by https
let config = RustlsConfig::from_pem_file(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("self_signed_certs")
.join("cert.pem"),
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("self_signed_certs")
.join("key.pem"),
)
.await
.unwrap();
let app = Router::new().route("/", get(handler));
// run https server
let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
tracing::debug!("listening on {}", addr);
axum_server::bind_rustls(addr, config)
.serve(app.into_make_service())
.await
.unwrap();
}
#[allow(dead_code)]
async fn handler() -> &'static str {
"Hello, World!"
}
#[allow(dead_code)]
async fn redirect_http_to_https(ports: Ports) {
fn make_https(uri: Uri, https_port: u16) -> Result<Uri, BoxError> {
let mut parts = uri.into_parts();
parts.scheme = Some(axum::http::uri::Scheme::HTTPS);
parts.authority = Some(format!("localhost:{https_port}").parse()?);
if parts.path_and_query.is_none() {
parts.path_and_query = Some("/".parse().unwrap());
}
Ok(Uri::from_parts(parts)?)
}
let redirect = move |uri: Uri| async move {
match make_https(uri, ports.https) {
Ok(uri) => Ok(Redirect::permanent(&uri.to_string())),
Err(error) => {
tracing::warn!(%error, "failed to convert URI to HTTPS");
Err(StatusCode::BAD_REQUEST)
}
}
};
let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, redirect.into_make_service()).await;
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/typed_path.rs | axum-macros/src/typed_path.rs | use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{parse::Parse, ItemStruct, LitStr, Token};
use crate::attr_parsing::{combine_attribute, parse_parenthesized_attribute, second, Combine};
pub(crate) fn expand(item_struct: &ItemStruct) -> syn::Result<TokenStream> {
let ItemStruct {
attrs,
ident,
generics,
fields,
..
} = item_struct;
if !generics.params.is_empty() || generics.where_clause.is_some() {
return Err(syn::Error::new_spanned(
generics,
"`#[derive(TypedPath)]` doesn't support generics",
));
}
let Attrs { path, rejection } = crate::attr_parsing::parse_attrs("typed_path", attrs)?;
let path = path.ok_or_else(|| {
syn::Error::new(
Span::call_site(),
"Missing path: `#[typed_path(\"/foo/bar\")]`",
)
})?;
let rejection = rejection.map(second);
match fields {
syn::Fields::Named(_) => {
let segments = parse_path(&path)?;
Ok(expand_named_fields(
ident,
&path,
&segments,
rejection.as_ref(),
))
}
syn::Fields::Unnamed(fields) => {
let segments = parse_path(&path)?;
expand_unnamed_fields(fields, ident, &path, &segments, rejection.as_ref())
}
syn::Fields::Unit => expand_unit_fields(ident, &path, rejection.as_ref()),
}
}
mod kw {
syn::custom_keyword!(rejection);
}
#[derive(Default)]
struct Attrs {
path: Option<LitStr>,
rejection: Option<(kw::rejection, syn::Path)>,
}
impl Parse for Attrs {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let mut path = None;
let mut rejection = None;
while !input.is_empty() {
let lh = input.lookahead1();
if lh.peek(LitStr) {
path = Some(input.parse()?);
} else if lh.peek(kw::rejection) {
parse_parenthesized_attribute(input, &mut rejection)?;
} else {
return Err(lh.error());
}
let _ = input.parse::<Token![,]>();
}
Ok(Self { path, rejection })
}
}
impl Combine for Attrs {
fn combine(mut self, other: Self) -> syn::Result<Self> {
let Self { path, rejection } = other;
if let Some(path) = path {
if self.path.is_some() {
return Err(syn::Error::new_spanned(
path,
"path specified more than once",
));
}
self.path = Some(path);
}
combine_attribute(&mut self.rejection, rejection)?;
Ok(self)
}
}
fn expand_named_fields(
ident: &syn::Ident,
path: &LitStr,
segments: &[Segment],
rejection: Option<&syn::Path>,
) -> TokenStream {
let format_str = format_str_from_path(segments);
let captures = captures_from_path(segments);
let typed_path_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::axum_extra::routing::TypedPath for #ident {
const PATH: &'static str = #path;
}
};
let display_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::std::fmt::Display for #ident {
#[allow(clippy::unnecessary_to_owned)]
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
let Self { #(#captures,)* } = self;
write!(
f,
#format_str,
#(
#captures = ::axum_extra::__private::utf8_percent_encode(
&#captures.to_string(),
::axum_extra::__private::PATH_SEGMENT,
)
),*
)
}
}
};
let rejection_assoc_type = rejection_assoc_type(rejection);
let map_err_rejection = map_err_rejection(rejection);
let from_request_impl = quote! {
#[automatically_derived]
impl<S> ::axum::extract::FromRequestParts<S> for #ident
where
S: Send + Sync,
{
type Rejection = #rejection_assoc_type;
async fn from_request_parts(
parts: &mut ::axum::http::request::Parts,
state: &S,
) -> ::std::result::Result<Self, Self::Rejection> {
::axum::extract::Path::from_request_parts(parts, state)
.await
.map(|path| path.0)
#map_err_rejection
}
}
};
quote! {
#typed_path_impl
#display_impl
#from_request_impl
}
}
fn expand_unnamed_fields(
fields: &syn::FieldsUnnamed,
ident: &syn::Ident,
path: &LitStr,
segments: &[Segment],
rejection: Option<&syn::Path>,
) -> syn::Result<TokenStream> {
let num_captures = segments
.iter()
.filter(|segment| match segment {
Segment::Capture(_, _) => true,
Segment::Static(_) => false,
})
.count();
let num_fields = fields.unnamed.len();
if num_fields != num_captures {
return Err(syn::Error::new_spanned(
fields,
format!(
"Mismatch in number of captures and fields. Path has {} but struct has {}",
simple_pluralize(num_captures, "capture"),
simple_pluralize(num_fields, "field"),
),
));
}
let destructure_self = segments
.iter()
.filter_map(|segment| match segment {
Segment::Capture(capture, _) => Some(capture),
Segment::Static(_) => None,
})
.enumerate()
.map(|(idx, capture)| {
let idx = syn::Index {
index: idx as _,
span: Span::call_site(),
};
let capture = format_ident!("{}", capture, span = path.span());
quote_spanned! {path.span()=>
#idx: #capture,
}
});
let format_str = format_str_from_path(segments);
let captures = captures_from_path(segments);
let typed_path_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::axum_extra::routing::TypedPath for #ident {
const PATH: &'static str = #path;
}
};
let display_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::std::fmt::Display for #ident {
#[allow(clippy::unnecessary_to_owned)]
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
let Self { #(#destructure_self)* } = self;
write!(
f,
#format_str,
#(
#captures = ::axum_extra::__private::utf8_percent_encode(
&#captures.to_string(),
::axum_extra::__private::PATH_SEGMENT,
)
),*
)
}
}
};
let rejection_assoc_type = rejection_assoc_type(rejection);
let map_err_rejection = map_err_rejection(rejection);
let from_request_impl = quote! {
#[automatically_derived]
impl<S> ::axum::extract::FromRequestParts<S> for #ident
where
S: Send + Sync,
{
type Rejection = #rejection_assoc_type;
async fn from_request_parts(
parts: &mut ::axum::http::request::Parts,
state: &S,
) -> ::std::result::Result<Self, Self::Rejection> {
::axum::extract::Path::from_request_parts(parts, state)
.await
.map(|path| path.0)
#map_err_rejection
}
}
};
Ok(quote! {
#typed_path_impl
#display_impl
#from_request_impl
})
}
fn simple_pluralize(count: usize, word: &str) -> String {
if count == 1 {
format!("{count} {word}")
} else {
format!("{count} {word}s")
}
}
fn expand_unit_fields(
ident: &syn::Ident,
path: &LitStr,
rejection: Option<&syn::Path>,
) -> syn::Result<TokenStream> {
for segment in parse_path(path)? {
match segment {
Segment::Capture(_, span) => {
return Err(syn::Error::new(
span,
"Typed paths for unit structs cannot contain captures",
));
}
Segment::Static(_) => {}
}
}
let typed_path_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::axum_extra::routing::TypedPath for #ident {
const PATH: &'static str = #path;
}
};
let display_impl = quote_spanned! {path.span()=>
#[automatically_derived]
impl ::std::fmt::Display for #ident {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, #path)
}
}
};
let rejection_assoc_type = if let Some(rejection) = &rejection {
quote! { #rejection }
} else {
quote! { ::axum::http::StatusCode }
};
let create_rejection = if let Some(rejection) = &rejection {
quote! {
Err(<#rejection as ::std::default::Default>::default())
}
} else {
quote! {
Err(::axum::http::StatusCode::NOT_FOUND)
}
};
let from_request_impl = quote! {
#[automatically_derived]
impl<S> ::axum::extract::FromRequestParts<S> for #ident
where
S: Send + Sync,
{
type Rejection = #rejection_assoc_type;
async fn from_request_parts(
parts: &mut ::axum::http::request::Parts,
_state: &S,
) -> ::std::result::Result<Self, Self::Rejection> {
if parts.uri.path() == <Self as ::axum_extra::routing::TypedPath>::PATH {
Ok(Self)
} else {
#create_rejection
}
}
}
};
Ok(quote! {
#typed_path_impl
#display_impl
#from_request_impl
})
}
fn format_str_from_path(segments: &[Segment]) -> String {
segments
.iter()
.map(|segment| match segment {
Segment::Capture(capture, _) => format!("{{{capture}}}"),
Segment::Static(segment) => segment.to_owned(),
})
.collect::<Vec<_>>()
.join("/")
}
fn captures_from_path(segments: &[Segment]) -> Vec<syn::Ident> {
segments
.iter()
.filter_map(|segment| match segment {
Segment::Capture(capture, span) => Some(format_ident!("{}", capture, span = *span)),
Segment::Static(_) => None,
})
.collect::<Vec<_>>()
}
fn parse_path(path: &LitStr) -> syn::Result<Vec<Segment>> {
let value = path.value();
if value.is_empty() {
return Err(syn::Error::new_spanned(
path,
"paths must start with a `/`. Use \"/\" for root routes",
));
} else if !path.value().starts_with('/') {
return Err(syn::Error::new_spanned(path, "paths must start with a `/`"));
}
path.value()
.split('/')
.map(|segment| {
if let Some(capture) = segment
.strip_prefix('{')
.and_then(|segment| segment.strip_suffix('}'))
.and_then(|segment| {
(!segment.starts_with('{') && !segment.ends_with('}')).then_some(segment)
})
.map(|capture| capture.strip_prefix('*').unwrap_or(capture))
{
Ok(Segment::Capture(capture.to_owned(), path.span()))
} else {
Ok(Segment::Static(segment.to_owned()))
}
})
.collect()
}
enum Segment {
Capture(String, Span),
Static(String),
}
fn path_rejection() -> TokenStream {
quote! {
<::axum::extract::Path<Self> as ::axum::extract::FromRequestParts<S>>::Rejection
}
}
fn rejection_assoc_type(rejection: Option<&syn::Path>) -> TokenStream {
match rejection {
Some(rejection) => quote! { #rejection },
None => path_rejection(),
}
}
fn map_err_rejection(rejection: Option<&syn::Path>) -> TokenStream {
rejection
.as_ref()
.map(|rejection| {
let path_rejection = path_rejection();
quote! {
.map_err(|rejection| {
<#rejection as ::std::convert::From<#path_rejection>>::from(rejection)
})
}
})
.unwrap_or_default()
}
#[test]
fn ui() {
crate::run_ui_tests("typed_path");
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/lib.rs | axum-macros/src/lib.rs | //! Macros for [`axum`].
//!
//! [`axum`]: https://crates.io/crates/axum
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(test, allow(clippy::float_cmp))]
#![cfg_attr(not(test), warn(clippy::print_stdout, clippy::dbg_macro))]
use debug_handler::FunctionKind;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Parse, Type};
mod attr_parsing;
#[cfg(feature = "__private")]
mod axum_test;
mod debug_handler;
mod from_ref;
mod from_request;
mod typed_path;
mod with_position;
use from_request::Trait::{FromRequest, FromRequestParts};
/// Derive an implementation of [`FromRequest`].
///
/// Supports generating two kinds of implementations:
/// 1. One that extracts each field individually.
/// 2. Another that extracts the whole type at once via another extractor.
///
/// # Each field individually
///
/// By default `#[derive(FromRequest)]` will call `FromRequest::from_request` for each field:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum::{
/// extract::Extension,
/// body::Bytes,
/// };
/// use axum_extra::{
/// TypedHeader,
/// headers::ContentType,
/// };
///
/// #[derive(FromRequest)]
/// struct MyExtractor {
/// state: Extension<State>,
/// content_type: TypedHeader<ContentType>,
/// request_body: Bytes,
/// }
///
/// #[derive(Clone)]
/// struct State {
/// // ...
/// }
///
/// async fn handler(extractor: MyExtractor) {}
/// ```
///
/// This requires that each field is an extractor (i.e. implements [`FromRequest`]).
///
/// Note that only the last field can consume the request body. Therefore this doesn't compile:
///
/// ```compile_fail
/// use axum_macros::FromRequest;
/// use axum::body::Bytes;
///
/// #[derive(FromRequest)]
/// struct MyExtractor {
/// // only the last field can implement `FromRequest`
/// // other fields must only implement `FromRequestParts`
/// bytes: Bytes,
/// string: String,
/// }
/// ```
///
/// ## Extracting via another extractor
///
/// You can use `#[from_request(via(...))]` to extract a field via another extractor, meaning the
/// field itself doesn't need to implement `FromRequest`:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum::{
/// extract::Extension,
/// body::Bytes,
/// };
/// use axum_extra::{
/// TypedHeader,
/// headers::ContentType,
/// };
///
/// #[derive(FromRequest)]
/// struct MyExtractor {
/// // This will extracted via `Extension::<State>::from_request`
/// #[from_request(via(Extension))]
/// state: State,
/// // and this via `TypedHeader::<ContentType>::from_request`
/// #[from_request(via(TypedHeader))]
/// content_type: ContentType,
/// // Can still be combined with other extractors
/// request_body: Bytes,
/// }
///
/// #[derive(Clone)]
/// struct State {
/// // ...
/// }
///
/// async fn handler(extractor: MyExtractor) {}
/// ```
///
/// Note this requires the via extractor to be a generic newtype struct (a tuple struct with
/// exactly one public field) that implements `FromRequest`:
///
/// ```
/// pub struct ViaExtractor<T>(pub T);
///
/// // impl<T, S> FromRequest<S> for ViaExtractor<T> { ... }
/// ```
///
/// More complex via extractors are not supported and require writing a manual implementation.
///
/// ## Optional fields
///
/// `#[from_request(via(...))]` supports `Option<_>` and `Result<_, _>` to make fields optional:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum_extra::{
/// TypedHeader,
/// headers::{ContentType, UserAgent},
/// typed_header::TypedHeaderRejection,
/// };
///
/// #[derive(FromRequest)]
/// struct MyExtractor {
/// // This will extracted via `Option::<TypedHeader<ContentType>>::from_request`
/// #[from_request(via(TypedHeader))]
/// content_type: Option<ContentType>,
/// // This will extracted via
/// // `Result::<TypedHeader<UserAgent>, TypedHeaderRejection>::from_request`
/// #[from_request(via(TypedHeader))]
/// user_agent: Result<UserAgent, TypedHeaderRejection>,
/// }
///
/// async fn handler(extractor: MyExtractor) {}
/// ```
///
/// ## The rejection
///
/// By default [`axum::response::Response`] will be used as the rejection. You can also use your own
/// rejection type with `#[from_request(rejection(YourType))]`:
///
/// ```
/// use axum::{
/// extract::{
/// rejection::{ExtensionRejection, StringRejection},
/// FromRequest,
/// },
/// Extension,
/// response::{Response, IntoResponse},
/// };
///
/// #[derive(FromRequest)]
/// #[from_request(rejection(MyRejection))]
/// struct MyExtractor {
/// state: Extension<String>,
/// body: String,
/// }
///
/// struct MyRejection(Response);
///
/// // This tells axum how to convert `Extension`'s rejections into `MyRejection`
/// impl From<ExtensionRejection> for MyRejection {
/// fn from(rejection: ExtensionRejection) -> Self {
/// // ...
/// # todo!()
/// }
/// }
///
/// // This tells axum how to convert `String`'s rejections into `MyRejection`
/// impl From<StringRejection> for MyRejection {
/// fn from(rejection: StringRejection) -> Self {
/// // ...
/// # todo!()
/// }
/// }
///
/// // All rejections must implement `IntoResponse`
/// impl IntoResponse for MyRejection {
/// fn into_response(self) -> Response {
/// self.0
/// }
/// }
/// ```
///
/// ## Concrete state
///
/// If the extraction can be done only for a concrete state, that type can be specified with
/// `#[from_request(state(YourState))]`:
///
/// ```
/// use axum::extract::{FromRequest, FromRequestParts};
///
/// #[derive(Clone)]
/// struct CustomState;
///
/// struct MyInnerType;
///
/// impl FromRequestParts<CustomState> for MyInnerType {
/// // ...
/// # type Rejection = ();
///
/// # async fn from_request_parts(
/// # _parts: &mut axum::http::request::Parts,
/// # _state: &CustomState
/// # ) -> Result<Self, Self::Rejection> {
/// # todo!()
/// # }
/// }
///
/// #[derive(FromRequest)]
/// #[from_request(state(CustomState))]
/// struct MyExtractor {
/// custom: MyInnerType,
/// body: String,
/// }
/// ```
///
/// This is not needed for a `State<T>` as the type is inferred in that case.
///
/// ```
/// use axum::extract::{FromRequest, FromRequestParts, State};
///
/// #[derive(Clone)]
/// struct CustomState;
///
/// #[derive(FromRequest)]
/// struct MyExtractor {
/// custom: State<CustomState>,
/// body: String,
/// }
/// ```
///
/// # The whole type at once
///
/// By using `#[from_request(via(...))]` on the container you can extract the whole type at once,
/// instead of each field individually:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum::extract::Extension;
///
/// // This will extracted via `Extension::<State>::from_request`
/// #[derive(Clone, FromRequest)]
/// #[from_request(via(Extension))]
/// struct State {
/// // ...
/// }
///
/// async fn handler(state: State) {}
/// ```
///
/// The rejection will be the "via extractors"'s rejection. For the previous example that would be
/// [`axum::extract::rejection::ExtensionRejection`].
///
/// You can use a different rejection type with `#[from_request(rejection(YourType))]`:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum::{
/// extract::{Extension, rejection::ExtensionRejection},
/// response::{IntoResponse, Response},
/// Json,
/// http::StatusCode,
/// };
/// use serde_json::json;
///
/// // This will extracted via `Extension::<State>::from_request`
/// #[derive(Clone, FromRequest)]
/// #[from_request(
/// via(Extension),
/// // Use your own rejection type
/// rejection(MyRejection),
/// )]
/// struct State {
/// // ...
/// }
///
/// struct MyRejection(Response);
///
/// // This tells axum how to convert `Extension`'s rejections into `MyRejection`
/// impl From<ExtensionRejection> for MyRejection {
/// fn from(rejection: ExtensionRejection) -> Self {
/// let response = (
/// StatusCode::INTERNAL_SERVER_ERROR,
/// Json(json!({ "error": "Something went wrong..." })),
/// ).into_response();
///
/// MyRejection(response)
/// }
/// }
///
/// // All rejections must implement `IntoResponse`
/// impl IntoResponse for MyRejection {
/// fn into_response(self) -> Response {
/// self.0
/// }
/// }
///
/// async fn handler(state: State) {}
/// ```
///
/// This allows you to wrap other extractors and easily customize the rejection:
///
/// ```
/// use axum_macros::FromRequest;
/// use axum::{
/// extract::{Extension, rejection::JsonRejection},
/// response::{IntoResponse, Response},
/// http::StatusCode,
/// };
/// use serde_json::json;
/// use serde::Deserialize;
///
/// // create an extractor that internally uses `axum::Json` but has a custom rejection
/// #[derive(FromRequest)]
/// #[from_request(via(axum::Json), rejection(MyRejection))]
/// struct MyJson<T>(T);
///
/// struct MyRejection(Response);
///
/// impl From<JsonRejection> for MyRejection {
/// fn from(rejection: JsonRejection) -> Self {
/// let response = (
/// StatusCode::INTERNAL_SERVER_ERROR,
/// axum::Json(json!({ "error": rejection.to_string() })),
/// ).into_response();
///
/// MyRejection(response)
/// }
/// }
///
/// impl IntoResponse for MyRejection {
/// fn into_response(self) -> Response {
/// self.0
/// }
/// }
///
/// #[derive(Deserialize)]
/// struct Payload {}
///
/// async fn handler(
/// // make sure to use `MyJson` and not `axum::Json`
/// MyJson(payload): MyJson<Payload>,
/// ) {}
/// ```
///
/// # Known limitations
///
/// Generics are only supported on tuple structs with exactly one field. Thus this doesn't work
///
/// ```compile_fail
/// #[derive(axum_macros::FromRequest)]
/// struct MyExtractor<T> {
/// thing: Option<T>,
/// }
/// ```
///
/// [`FromRequest`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRequest.html
/// [`axum::response::Response`]: https://docs.rs/axum/0.8/axum/response/type.Response.html
/// [`axum::extract::rejection::ExtensionRejection`]: https://docs.rs/axum/0.8/axum/extract/rejection/enum.ExtensionRejection.html
#[proc_macro_derive(FromRequest, attributes(from_request))]
pub fn derive_from_request(item: TokenStream) -> TokenStream {
expand_with(item, |item| from_request::expand(item, FromRequest))
}
/// Derive an implementation of [`FromRequestParts`].
///
/// This works similarly to `#[derive(FromRequest)]` except it uses [`FromRequestParts`]. All the
/// same options are supported.
///
/// # Example
///
/// ```
/// 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<String, String>,
/// content_type: TypedHeader<ContentType>,
/// }
///
/// async fn handler(extractor: MyExtractor) {}
/// ```
///
/// # Cannot extract the body
///
/// [`FromRequestParts`] cannot extract the request body:
///
/// ```compile_fail
/// use axum_macros::FromRequestParts;
///
/// #[derive(FromRequestParts)]
/// struct MyExtractor {
/// body: String,
/// }
/// ```
///
/// Use `#[derive(FromRequest)]` for that.
///
/// [`FromRequestParts`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRequestParts.html
#[proc_macro_derive(FromRequestParts, attributes(from_request))]
pub fn derive_from_request_parts(item: TokenStream) -> TokenStream {
expand_with(item, |item| from_request::expand(item, FromRequestParts))
}
/// Generates better error messages when applied to handler functions.
///
/// While using [`axum`], you can get long error messages for simple mistakes. For example:
///
/// ```compile_fail
/// 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;
/// }
///
/// fn handler() -> &'static str {
/// "Hello, world"
/// }
/// ```
///
/// You will get a long error message about function not implementing [`Handler`] trait. But why
/// does this function not implement it? To figure it out, the [`debug_handler`] macro can be used.
///
/// ```compile_fail
/// # use axum::{routing::get, Router};
/// # use axum_macros::debug_handler;
/// #
/// # #[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;
/// # }
/// #
/// #[debug_handler]
/// fn handler() -> &'static str {
/// "Hello, world"
/// }
/// ```
///
/// ```text
/// error: handlers must be async functions
/// --> main.rs:xx:1
/// |
/// xx | fn handler() -> &'static str {
/// | ^^
/// ```
///
/// As the error message says, handler function needs to be async.
///
/// ```no_run
/// use axum::{routing::get, Router, debug_handler};
///
/// #[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;
/// }
///
/// #[debug_handler]
/// async fn handler() -> &'static str {
/// "Hello, world"
/// }
/// ```
///
/// # Changing state type
///
/// By default `#[debug_handler]` assumes your state type is `()` unless your handler has a
/// [`axum::extract::State`] argument:
///
/// ```
/// use axum::{debug_handler, extract::State};
///
/// #[debug_handler]
/// async fn handler(
/// // this makes `#[debug_handler]` use `AppState`
/// State(state): State<AppState>,
/// ) {}
///
/// #[derive(Clone)]
/// struct AppState {}
/// ```
///
/// If your handler takes multiple [`axum::extract::State`] arguments or you need to otherwise
/// customize the state type you can set it with `#[debug_handler(state = ...)]`:
///
/// ```
/// use axum::{debug_handler, extract::{State, FromRef}};
///
/// #[debug_handler(state = AppState)]
/// async fn handler(
/// State(app_state): State<AppState>,
/// State(inner_state): State<InnerState>,
/// ) {}
///
/// #[derive(Clone)]
/// struct AppState {
/// inner: InnerState,
/// }
///
/// #[derive(Clone)]
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
/// fn from_ref(state: &AppState) -> Self {
/// state.inner.clone()
/// }
/// }
/// ```
///
/// # Limitations
///
/// This macro does not work for functions in an `impl` block that don't have a `self` parameter:
///
/// ```compile_fail
/// use axum::{debug_handler, extract::Path};
///
/// struct App {}
///
/// impl App {
/// #[debug_handler]
/// async fn handler(Path(_): Path<String>) {}
/// }
/// ```
///
/// This will yield an error similar to this:
///
/// ```text
/// error[E0425]: cannot find function `__axum_macros_check_handler_0_from_request_check` in this scope
// --> src/main.rs:xx:xx
// |
// xx | pub async fn handler(Path(_): Path<String>) {}
// | ^^^^ not found in this scope
/// ```
///
/// # Performance
///
/// This macro has no effect when compiled with the release profile. (eg. `cargo build --release`)
///
/// [`axum`]: https://docs.rs/axum/0.8
/// [`Handler`]: https://docs.rs/axum/0.8/axum/handler/trait.Handler.html
/// [`axum::extract::State`]: https://docs.rs/axum/0.8/axum/extract/struct.State.html
/// [`debug_handler`]: macro@debug_handler
#[proc_macro_attribute]
pub fn debug_handler(_attr: TokenStream, input: TokenStream) -> TokenStream {
#[cfg(not(debug_assertions))]
return input;
#[cfg(debug_assertions)]
return expand_attr_with(_attr, input, |attrs, item_fn| {
debug_handler::expand(attrs, &item_fn, FunctionKind::Handler)
});
}
/// Generates better error messages when applied to middleware functions.
///
/// This works similarly to [`#[debug_handler]`](macro@debug_handler) except for middleware using
/// [`axum::middleware::from_fn`].
///
/// # Example
///
/// ```no_run
/// use axum::{
/// routing::get,
/// extract::Request,
/// response::Response,
/// Router,
/// middleware::{self, Next},
/// debug_middleware,
/// };
///
/// #[tokio::main]
/// async fn main() {
/// let app = Router::new()
/// .route("/", get(|| async {}))
/// .layer(middleware::from_fn(my_middleware));
///
/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// axum::serve(listener, app).await;
/// }
///
/// // if this wasn't a valid middleware function #[debug_middleware] would
/// // improve compile error
/// #[debug_middleware]
/// async fn my_middleware(
/// request: Request,
/// next: Next,
/// ) -> Response {
/// next.run(request).await
/// }
/// ```
///
/// # Performance
///
/// This macro has no effect when compiled with the release profile. (eg. `cargo build --release`)
///
/// [`axum`]: https://docs.rs/axum/latest
/// [`axum::middleware::from_fn`]: https://docs.rs/axum/0.8/axum/middleware/fn.from_fn.html
/// [`debug_middleware`]: macro@debug_middleware
#[proc_macro_attribute]
pub fn debug_middleware(_attr: TokenStream, input: TokenStream) -> TokenStream {
#[cfg(not(debug_assertions))]
return input;
#[cfg(debug_assertions)]
return expand_attr_with(_attr, input, |attrs, item_fn| {
debug_handler::expand(attrs, &item_fn, FunctionKind::Middleware)
});
}
/// Private API: Do no use this!
///
/// Attribute macro to be placed on test functions that'll generate two functions:
///
/// 1. One identical to the function it was placed on.
/// 2. One where calls to `Router::nest` has been replaced with `Router::nest_service`
///
/// This makes it easy to that `nest` and `nest_service` behaves in the same way, without having to
/// manually write identical tests for both methods.
#[cfg(feature = "__private")]
#[proc_macro_attribute]
#[doc(hidden)]
pub fn __private_axum_test(_attr: TokenStream, input: TokenStream) -> TokenStream {
expand_attr_with(_attr, input, axum_test::expand)
}
/// Derive an implementation of [`axum_extra::routing::TypedPath`].
///
/// See that trait for more details.
///
/// [`axum_extra::routing::TypedPath`]: https://docs.rs/axum-extra/latest/axum_extra/routing/trait.TypedPath.html
#[proc_macro_derive(TypedPath, attributes(typed_path))]
pub fn derive_typed_path(input: TokenStream) -> TokenStream {
expand_with(input, |item_struct| typed_path::expand(&item_struct))
}
/// Derive an implementation of [`FromRef`] for each field in a struct.
///
/// # Example
///
/// ```
/// use axum::{
/// Router,
/// routing::get,
/// extract::{State, FromRef},
/// };
///
/// #
/// # type AuthToken = String;
/// # type DatabasePool = ();
/// #
/// // This will implement `FromRef` for each field in the struct.
/// #[derive(FromRef, Clone)]
/// struct AppState {
/// auth_token: AuthToken,
/// database_pool: DatabasePool,
/// // fields can also be skipped
/// #[from_ref(skip)]
/// api_token: String,
/// }
///
/// // So those types can be extracted via `State`
/// async fn handler(State(auth_token): State<AuthToken>) {}
///
/// async fn other_handler(State(database_pool): State<DatabasePool>) {}
///
/// # let auth_token = Default::default();
/// # let database_pool = Default::default();
/// let state = AppState {
/// auth_token,
/// database_pool,
/// api_token: "secret".to_owned(),
/// };
///
/// let app = Router::new()
/// .route("/", get(handler).post(other_handler))
/// .with_state(state);
/// # let _: axum::Router = app;
/// ```
///
/// [`FromRef`]: https://docs.rs/axum/0.8/axum/extract/trait.FromRef.html
#[proc_macro_derive(FromRef, attributes(from_ref))]
pub fn derive_from_ref(item: TokenStream) -> TokenStream {
expand_with(item, from_ref::expand)
}
fn expand_with<F, I, K>(input: TokenStream, f: F) -> TokenStream
where
F: FnOnce(I) -> syn::Result<K>,
I: Parse,
K: ToTokens,
{
expand(syn::parse(input).and_then(f))
}
fn expand_attr_with<F, A, I, K>(attr: TokenStream, input: TokenStream, f: F) -> TokenStream
where
F: FnOnce(A, I) -> K,
A: Parse,
I: Parse,
K: ToTokens,
{
let expand_result = (|| {
let attr = syn::parse(attr)?;
let input = syn::parse(input)?;
Ok(f(attr, input))
})();
expand(expand_result)
}
fn expand<T>(result: syn::Result<T>) -> TokenStream
where
T: ToTokens,
{
match result {
Ok(tokens) => {
let tokens = (quote! { #tokens }).into();
if std::env::var_os("AXUM_MACROS_DEBUG").is_some() {
eprintln!("{tokens}");
}
tokens
}
Err(err) => err.into_compile_error().into(),
}
}
fn infer_state_types<'a, I>(types: I) -> impl Iterator<Item = Type> + 'a
where
I: Iterator<Item = &'a Type> + 'a,
{
types
.filter_map(|ty| {
if let Type::Path(path) = ty {
Some(&path.path)
} else {
None
}
})
.filter_map(|path| {
if let Some(last_segment) = path.segments.last() {
if last_segment.ident != "State" {
return None;
}
match &last_segment.arguments {
syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => {
Some(args.args.first().unwrap())
}
_ => None,
}
} else {
None
}
})
.filter_map(|generic_arg| {
if let syn::GenericArgument::Type(ty) = generic_arg {
Some(ty)
} else {
None
}
})
.cloned()
}
#[cfg(test)]
fn run_ui_tests(directory: &str) {
#[rustversion::nightly]
fn go(directory: &str) {
let t = trybuild::TestCases::new();
if let Ok(mut path) = std::env::var("AXUM_TEST_ONLY") {
if let Some(path_without_prefix) = path.strip_prefix("axum-macros/") {
path = path_without_prefix.to_owned();
}
if !path.contains(&format!("/{directory}/")) {
return;
}
if path.contains("/fail/") {
t.compile_fail(path);
} else if path.contains("/pass/") {
t.pass(path);
} else {
panic!()
}
} else {
t.compile_fail(format!("tests/{directory}/fail/*.rs"));
t.pass(format!("tests/{directory}/pass/*.rs"));
}
}
#[rustversion::not(nightly)]
fn go(_directory: &str) {}
go(directory);
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/debug_handler.rs | axum-macros/src/debug_handler.rs | use std::{collections::HashSet, fmt};
use crate::{
attr_parsing::{parse_assignment_attribute, second},
with_position::{Position, WithPosition},
};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{parse::Parse, spanned::Spanned, FnArg, ItemFn, ReturnType, Token, Type};
pub(crate) fn expand(attr: Attrs, item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {
let Attrs { state_ty } = attr;
let mut state_ty = state_ty.map(second);
let check_extractor_count = check_extractor_count(item_fn, kind);
let check_path_extractor = check_path_extractor(item_fn, kind);
let check_output_tuples = check_output_tuples(item_fn);
let check_output_impls_into_response = if check_output_tuples.is_empty() {
check_output_impls_into_response(item_fn)
} else {
check_output_tuples
};
// If the function is generic, we can't reliably check its inputs or whether the future it
// returns is `Send`. Skip those checks to avoid unhelpful additional compiler errors.
let check_inputs_and_future_send = if item_fn.sig.generics.params.is_empty() {
let mut err = None;
if state_ty.is_none() {
let state_types_from_args = state_types_from_args(item_fn);
#[allow(clippy::comparison_chain)]
if state_types_from_args.len() == 1 {
state_ty = state_types_from_args.into_iter().next();
} else if state_types_from_args.len() > 1 {
err = Some(
syn::Error::new(
Span::call_site(),
format!(
"can't infer state type, please add set it explicitly, as in \
`#[axum_macros::debug_{kind}(state = MyStateType)]`"
),
)
.into_compile_error(),
);
}
}
err.unwrap_or_else(|| {
let state_ty = state_ty.unwrap_or_else(|| syn::parse_quote!(()));
let check_future_send = check_future_send(item_fn, kind);
if let Some(check_input_order) = check_input_order(item_fn, kind) {
quote! {
#check_input_order
#check_future_send
}
} else {
let check_inputs_impls_from_request =
check_inputs_impls_from_request(item_fn, &state_ty, kind);
quote! {
#check_inputs_impls_from_request
#check_future_send
}
}
})
} else {
syn::Error::new_spanned(
&item_fn.sig.generics,
format!("`#[axum_macros::debug_{kind}]` doesn't support generic functions"),
)
.into_compile_error()
};
let middleware_takes_next_as_last_arg =
matches!(kind, FunctionKind::Middleware).then(|| next_is_last_input(item_fn));
quote! {
#item_fn
#check_extractor_count
#check_path_extractor
#check_output_impls_into_response
#check_inputs_and_future_send
#middleware_takes_next_as_last_arg
}
}
#[derive(Clone, Copy)]
pub(crate) enum FunctionKind {
Handler,
Middleware,
}
impl fmt::Display for FunctionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Handler => f.write_str("handler"),
Self::Middleware => f.write_str("middleware"),
}
}
}
impl FunctionKind {
fn name_uppercase_plural(self) -> &'static str {
match self {
Self::Handler => "Handlers",
Self::Middleware => "Middleware",
}
}
}
mod kw {
syn::custom_keyword!(body);
syn::custom_keyword!(state);
}
pub(crate) struct Attrs {
state_ty: Option<(kw::state, Type)>,
}
impl Parse for Attrs {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let mut state_ty = None;
while !input.is_empty() {
let lh = input.lookahead1();
if lh.peek(kw::state) {
parse_assignment_attribute(input, &mut state_ty)?;
} else {
return Err(lh.error());
}
let _ = input.parse::<Token![,]>();
}
Ok(Self { state_ty })
}
}
fn check_extractor_count(item_fn: &ItemFn, kind: FunctionKind) -> Option<TokenStream> {
let max_extractors = 16;
let inputs = item_fn
.sig
.inputs
.iter()
.filter(|arg| skip_next_arg(arg, kind))
.count();
if inputs <= max_extractors {
None
} else {
let error_message = format!(
"{} cannot take more than {max_extractors} arguments. \
Use `(a, b): (ExtractorA, ExtractorA)` to further nest extractors",
kind.name_uppercase_plural(),
);
let error = syn::Error::new_spanned(&item_fn.sig.inputs, error_message).to_compile_error();
Some(error)
}
}
fn extractor_idents(
item_fn: &ItemFn,
kind: FunctionKind,
) -> impl Iterator<Item = (usize, &syn::FnArg, &syn::Ident)> {
item_fn
.sig
.inputs
.iter()
.filter(move |arg| skip_next_arg(arg, kind))
.enumerate()
.filter_map(|(idx, fn_arg)| match fn_arg {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_type) => {
if let Type::Path(type_path) = &*pat_type.ty {
type_path
.path
.segments
.last()
.map(|segment| (idx, fn_arg, &segment.ident))
} else {
None
}
}
})
}
fn check_path_extractor(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {
let path_extractors = extractor_idents(item_fn, kind)
.filter(|(_, _, ident)| *ident == "Path")
.collect::<Vec<_>>();
if path_extractors.len() > 1 {
path_extractors
.into_iter()
.map(|(_, arg, _)| {
syn::Error::new_spanned(
arg,
"Multiple parameters must be extracted with a tuple \
`Path<(_, _)>` or a struct `Path<YourParams>`, not by applying \
multiple `Path<_>` extractors",
)
.to_compile_error()
})
.collect()
} else {
quote! {}
}
}
fn is_self_pat_type(typed: &syn::PatType) -> bool {
let ident = if let syn::Pat::Ident(ident) = &*typed.pat {
&ident.ident
} else {
return false;
};
ident == "self"
}
fn check_inputs_impls_from_request(
item_fn: &ItemFn,
state_ty: &Type,
kind: FunctionKind,
) -> TokenStream {
let takes_self = item_fn.sig.inputs.first().is_some_and(|arg| match arg {
FnArg::Receiver(_) => true,
FnArg::Typed(typed) => is_self_pat_type(typed),
});
WithPosition::new(
item_fn
.sig
.inputs
.iter()
.filter(|arg| skip_next_arg(arg, kind)),
)
.enumerate()
.map(|(idx, arg)| {
let must_impl_from_request_parts = match &arg {
Position::First(_) | Position::Middle(_) => true,
Position::Last(_) | Position::Only(_) => false,
};
let arg = arg.into_inner();
let (span, ty) = match arg {
FnArg::Receiver(receiver) => {
if receiver.reference.is_some() {
return syn::Error::new_spanned(
receiver,
"Handlers must only take owned values",
)
.into_compile_error();
}
let span = receiver.span();
(span, syn::parse_quote!(Self))
}
FnArg::Typed(typed) => {
let ty = &typed.ty;
let span = ty.span();
if is_self_pat_type(typed) {
(span, syn::parse_quote!(Self))
} else {
(span, ty.clone())
}
}
};
let consumes_request = request_consuming_type_name(&ty).is_some();
let check_fn = format_ident!(
"__axum_macros_check_{}_{}_from_request_check",
item_fn.sig.ident,
idx,
span = span,
);
let call_check_fn = format_ident!(
"__axum_macros_check_{}_{}_from_request_call_check",
item_fn.sig.ident,
idx,
span = span,
);
let call_check_fn_body = if takes_self {
quote_spanned! {span=>
Self::#check_fn();
}
} else {
quote_spanned! {span=>
#check_fn();
}
};
let check_fn_generics = if must_impl_from_request_parts || consumes_request {
quote! {}
} else {
quote! { <M> }
};
let from_request_bound = if must_impl_from_request_parts {
quote_spanned! {span=>
#ty: ::axum::extract::FromRequestParts<#state_ty> + Send
}
} else if consumes_request {
quote_spanned! {span=>
#ty: ::axum::extract::FromRequest<#state_ty> + Send
}
} else {
quote_spanned! {span=>
#ty: ::axum::extract::FromRequest<#state_ty, M> + Send
}
};
quote_spanned! {span=>
#[allow(warnings)]
#[doc(hidden)]
fn #check_fn #check_fn_generics()
where
#from_request_bound,
{}
// we have to call the function to actually trigger a compile error
// since the function is generic, just defining it is not enough
#[allow(warnings)]
#[doc(hidden)]
fn #call_check_fn()
{
#call_check_fn_body
}
}
})
.collect::<TokenStream>()
}
fn check_output_tuples(item_fn: &ItemFn) -> TokenStream {
let elems = match &item_fn.sig.output {
ReturnType::Type(_, ty) => match &**ty {
Type::Tuple(tuple) => &tuple.elems,
_ => return quote! {},
},
ReturnType::Default => return quote! {},
};
let handler_ident = &item_fn.sig.ident;
match elems.len() {
0 => quote! {},
n if n > 17 => syn::Error::new_spanned(
&item_fn.sig.output,
"Cannot return tuples with more than 17 elements",
)
.to_compile_error(),
_ => WithPosition::new(elems)
.enumerate()
.map(|(idx, arg)| match arg {
Position::First(ty) => match extract_clean_typename(ty).as_deref() {
Some("StatusCode" | "Response") => quote! {},
Some("Parts") => check_is_response_parts(ty, handler_ident, idx),
Some(_) | None => {
if let Some(tn) = well_known_last_response_type(ty) {
syn::Error::new_spanned(
ty,
format!(
"`{tn}` must be the last element \
in a response tuple"
),
)
.to_compile_error()
} else {
check_into_response_parts(ty, handler_ident, idx)
}
}
},
Position::Middle(ty) => {
if let Some(tn) = well_known_last_response_type(ty) {
syn::Error::new_spanned(
ty,
format!("`{tn}` must be the last element in a response tuple"),
)
.to_compile_error()
} else {
check_into_response_parts(ty, handler_ident, idx)
}
}
Position::Last(ty) | Position::Only(ty) => check_into_response(handler_ident, ty),
})
.collect::<TokenStream>(),
}
}
fn check_into_response(handler: &Ident, ty: &Type) -> TokenStream {
let (span, ty) = (ty.span(), ty.clone());
let check_fn = format_ident!(
"__axum_macros_check_{handler}_into_response_check",
span = span,
);
let call_check_fn = format_ident!(
"__axum_macros_check_{handler}_into_response_call_check",
span = span,
);
let call_check_fn_body = quote_spanned! {span=>
#check_fn();
};
let from_request_bound = quote_spanned! {span=>
#ty: ::axum::response::IntoResponse
};
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #check_fn()
where
#from_request_bound,
{}
// we have to call the function to actually trigger a compile error
// since the function is generic, just defining it is not enough
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #call_check_fn() {
#call_check_fn_body
}
}
}
fn check_is_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {
let (span, ty) = (ty.span(), ty.clone());
let check_fn = format_ident!(
"__axum_macros_check_{}_is_response_parts_{index}_check",
ident,
span = span,
);
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #check_fn(parts: #ty) -> ::axum::http::response::Parts {
parts
}
}
}
fn check_into_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {
let (span, ty) = (ty.span(), ty.clone());
let check_fn = format_ident!(
"__axum_macros_check_{}_into_response_parts_{index}_check",
ident,
span = span,
);
let call_check_fn = format_ident!(
"__axum_macros_check_{}_into_response_parts_{index}_call_check",
ident,
span = span,
);
let call_check_fn_body = quote_spanned! {span=>
#check_fn();
};
let from_request_bound = quote_spanned! {span=>
#ty: ::axum::response::IntoResponseParts
};
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #check_fn()
where
#from_request_bound,
{}
// we have to call the function to actually trigger a compile error
// since the function is generic, just defining it is not enough
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #call_check_fn() {
#call_check_fn_body
}
}
}
fn check_input_order(item_fn: &ItemFn, kind: FunctionKind) -> Option<TokenStream> {
let number_of_inputs = item_fn
.sig
.inputs
.iter()
.filter(|arg| skip_next_arg(arg, kind))
.count();
let types_that_consume_the_request = item_fn
.sig
.inputs
.iter()
.filter(|arg| skip_next_arg(arg, kind))
.enumerate()
.filter_map(|(idx, arg)| {
let ty = match arg {
FnArg::Typed(pat_type) => &*pat_type.ty,
FnArg::Receiver(_) => return None,
};
let type_name = request_consuming_type_name(ty)?;
Some((idx, type_name, ty.span()))
})
.collect::<Vec<_>>();
if types_that_consume_the_request.is_empty() {
return None;
};
// exactly one type that consumes the request
if types_that_consume_the_request.len() == 1 {
// and that is not the last
if types_that_consume_the_request[0].0 != number_of_inputs - 1 {
let (_idx, type_name, span) = &types_that_consume_the_request[0];
let error = format!(
"`{type_name}` consumes the request body and thus must be \
the last argument to the handler function"
);
return Some(quote_spanned! {*span=>
compile_error!(#error);
});
} else {
return None;
}
}
if types_that_consume_the_request.len() == 2 {
let (_, first, _) = &types_that_consume_the_request[0];
let (_, second, _) = &types_that_consume_the_request[1];
let error = format!(
"Can't have two extractors that consume the request body. \
`{first}` and `{second}` both do that.",
);
let span = item_fn.sig.inputs.span();
Some(quote_spanned! {span=>
compile_error!(#error);
})
} else {
let types = WithPosition::new(types_that_consume_the_request)
.map(|pos| match pos {
Position::First((_, type_name, _)) | Position::Middle((_, type_name, _)) => {
format!("`{type_name}`, ")
}
Position::Last((_, type_name, _)) => format!("and `{type_name}`"),
Position::Only(_) => unreachable!(),
})
.collect::<String>();
let error = format!(
"Can't have more than one extractor that consume the request body. \
{types} all do that.",
);
let span = item_fn.sig.inputs.span();
Some(quote_spanned! {span=>
compile_error!(#error);
})
}
}
fn extract_clean_typename(ty: &Type) -> Option<String> {
let path = match ty {
Type::Path(type_path) => &type_path.path,
_ => return None,
};
path.segments.last().map(|p| p.ident.to_string())
}
fn request_consuming_type_name(ty: &Type) -> Option<&'static str> {
let typename = extract_clean_typename(ty)?;
let type_name = match &*typename {
"Json" => "Json<_>",
"RawBody" => "RawBody<_>",
"RawForm" => "RawForm",
"Multipart" => "Multipart",
"Protobuf" => "Protobuf",
"JsonLines" => "JsonLines<_>",
"Form" => "Form<_>",
"Request" => "Request<_>",
"Bytes" => "Bytes",
"String" => "String",
"Parts" => "Parts",
_ => return None,
};
Some(type_name)
}
fn well_known_last_response_type(ty: &Type) -> Option<&'static str> {
let typename = extract_clean_typename(ty)?;
let type_name = match &*typename {
"Json" => "Json<_>",
"Protobuf" => "Protobuf",
"JsonLines" => "JsonLines<_>",
"Form" => "Form<_>",
"Bytes" => "Bytes",
"String" => "String",
_ => return None,
};
Some(type_name)
}
fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {
let ty = match &item_fn.sig.output {
syn::ReturnType::Default => return quote! {},
syn::ReturnType::Type(_, ty) => ty,
};
let span = ty.span();
let declare_inputs = item_fn
.sig
.inputs
.iter()
.filter_map(|arg| match arg {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_ty) => {
let pat = &pat_ty.pat;
let ty = &pat_ty.ty;
Some(quote! {
let #pat: #ty = panic!();
})
}
})
.collect::<TokenStream>();
let block = &item_fn.block;
let make_value_name = format_ident!(
"__axum_macros_check_{}_into_response_make_value",
item_fn.sig.ident
);
let make = if item_fn.sig.asyncness.is_some() {
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
async fn #make_value_name() -> #ty {
#declare_inputs
#block
}
}
} else {
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #make_value_name() -> #ty {
#declare_inputs
#block
}
}
};
let name = format_ident!("__axum_macros_check_{}_into_response", item_fn.sig.ident);
if let Some(receiver) = self_receiver(item_fn) {
quote_spanned! {span=>
#make
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
async fn #name() {
fn check<T>(_: T)
where T: ::axum::response::IntoResponse
{}
let value = #receiver #make_value_name().await;
check(value);
}
}
} else {
quote_spanned! {span=>
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
async fn #name() {
#make
fn check<T>(_: T)
where T: ::axum::response::IntoResponse
{}
let value = #make_value_name().await;
check(value);
}
}
}
}
fn check_future_send(item_fn: &ItemFn, kind: FunctionKind) -> TokenStream {
if item_fn.sig.asyncness.is_none() {
match &item_fn.sig.output {
syn::ReturnType::Default => {
return syn::Error::new_spanned(
item_fn.sig.fn_token,
format!("{} must be `async fn`s", kind.name_uppercase_plural()),
)
.into_compile_error();
}
syn::ReturnType::Type(_, ty) => ty,
};
}
let span = item_fn.sig.ident.span();
let handler_name = &item_fn.sig.ident;
let args = item_fn.sig.inputs.iter().map(|_| {
quote_spanned! {span=> panic!() }
});
let name = format_ident!("__axum_macros_check_{}_future", item_fn.sig.ident);
let define_check = quote! {
fn check<T>(_: T)
where T: ::std::future::Future + Send
{}
};
let do_check = quote! {
check(future);
};
if let Some(receiver) = self_receiver(item_fn) {
quote! {
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #name() {
#define_check
let future = #receiver #handler_name(#(#args),*);
#do_check
}
}
} else {
quote! {
#[allow(warnings)]
#[allow(unreachable_code)]
#[doc(hidden)]
fn #name() {
#item_fn
#define_check
let future = #handler_name(#(#args),*);
#do_check
}
}
}
}
fn self_receiver(item_fn: &ItemFn) -> Option<TokenStream> {
let takes_self = item_fn.sig.inputs.iter().any(|arg| match arg {
FnArg::Receiver(_) => true,
FnArg::Typed(typed) => is_self_pat_type(typed),
});
if takes_self {
return Some(quote! { Self:: });
}
if let syn::ReturnType::Type(_, ty) = &item_fn.sig.output {
if let syn::Type::Path(path) = &**ty {
let segments = &path.path.segments;
if segments.len() == 1 {
if let Some(last) = segments.last() {
match &last.arguments {
syn::PathArguments::None if last.ident == "Self" => {
return Some(quote! { Self:: });
}
_ => {}
}
}
}
}
}
None
}
/// Given a signature like
///
/// ```skip
/// #[debug_handler]
/// async fn handler(
/// _: axum::extract::State<AppState>,
/// _: State<AppState>,
/// ) {}
/// ```
///
/// This will extract `AppState`.
///
/// Returns `None` if there are no `State` args or multiple of different types.
fn state_types_from_args(item_fn: &ItemFn) -> HashSet<Type> {
let types = item_fn
.sig
.inputs
.iter()
.filter_map(|input| match input {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_type) => Some(pat_type),
})
.map(|pat_type| &*pat_type.ty);
crate::infer_state_types(types).collect()
}
fn next_is_last_input(item_fn: &ItemFn) -> TokenStream {
let next_args = item_fn
.sig
.inputs
.iter()
.enumerate()
.filter(|(_, arg)| !skip_next_arg(arg, FunctionKind::Middleware))
.collect::<Vec<_>>();
if next_args.is_empty() {
return quote! {
compile_error!(
"Middleware functions must take `axum::middleware::Next` as the last argument",
);
};
}
if next_args.len() == 1 {
let (idx, arg) = &next_args[0];
if *idx != item_fn.sig.inputs.len() - 1 {
return quote_spanned! {arg.span()=>
compile_error!("`axum::middleware::Next` must the last argument");
};
}
}
if next_args.len() >= 2 {
return quote! {
compile_error!(
"Middleware functions can only take one argument of type `axum::middleware::Next`",
);
};
}
quote! {}
}
fn skip_next_arg(arg: &FnArg, kind: FunctionKind) -> bool {
match kind {
FunctionKind::Handler => true,
FunctionKind::Middleware => match arg {
FnArg::Receiver(_) => true,
FnArg::Typed(pat_type) => {
if let Type::Path(type_path) = &*pat_type.ty {
type_path
.path
.segments
.last()
.map_or(true, |path_segment| path_segment.ident != "Next")
} else {
true
}
}
},
}
}
#[test]
fn ui_debug_handler() {
crate::run_ui_tests("debug_handler");
}
#[test]
fn ui_debug_middleware() {
crate::run_ui_tests("debug_middleware");
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/from_ref.rs | axum-macros/src/from_ref.rs | use proc_macro2::{Ident, TokenStream};
use quote::quote_spanned;
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
Field, ItemStruct, Token, Type,
};
use crate::attr_parsing::{combine_unary_attribute, parse_attrs, Combine};
pub(crate) fn expand(item: ItemStruct) -> syn::Result<TokenStream> {
if !item.generics.params.is_empty() {
return Err(syn::Error::new_spanned(
item.generics,
"`#[derive(FromRef)]` doesn't support generics",
));
}
let tokens = item
.fields
.iter()
.enumerate()
.map(|(idx, field)| expand_field(&item.ident, idx, field))
.collect();
Ok(tokens)
}
fn expand_field(state: &Ident, idx: usize, field: &Field) -> TokenStream {
let FieldAttrs { skip } = match parse_attrs("from_ref", &field.attrs) {
Ok(attrs) => attrs,
Err(err) => return err.into_compile_error(),
};
if skip.is_some() {
return TokenStream::default();
}
let field_ty = &field.ty;
let span = field.ty.span();
let body = if let Some(field_ident) = &field.ident {
if matches!(field_ty, Type::Reference(_)) {
quote_spanned! {span=> state.#field_ident }
} else {
quote_spanned! {span=> state.#field_ident.clone() }
}
} else {
let idx = syn::Index {
index: idx as _,
span: field.span(),
};
quote_spanned! {span=> state.#idx.clone() }
};
quote_spanned! {span=>
#[allow(clippy::clone_on_copy, clippy::clone_on_ref_ptr)]
impl ::axum::extract::FromRef<#state> for #field_ty {
fn from_ref(state: &#state) -> Self {
#body
}
}
}
}
mod kw {
syn::custom_keyword!(skip);
}
#[derive(Default)]
pub(super) struct FieldAttrs {
pub(super) skip: Option<kw::skip>,
}
impl Parse for FieldAttrs {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let mut skip = None;
while !input.is_empty() {
let lh = input.lookahead1();
if lh.peek(kw::skip) {
skip = Some(input.parse()?);
} else {
return Err(lh.error());
}
let _ = input.parse::<Token![,]>();
}
Ok(Self { skip })
}
}
impl Combine for FieldAttrs {
fn combine(mut self, other: Self) -> syn::Result<Self> {
let Self { skip } = other;
combine_unary_attribute(&mut self.skip, skip)?;
Ok(self)
}
}
#[test]
fn ui() {
crate::run_ui_tests("from_ref");
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/with_position.rs | axum-macros/src/with_position.rs | // this is copied from itertools under the following license
//
// Copyright (c) 2015
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use std::iter::{Fuse, FusedIterator, Peekable};
pub(crate) struct WithPosition<I>
where
I: Iterator,
{
handled_first: bool,
peekable: Peekable<Fuse<I>>,
}
impl<I> WithPosition<I>
where
I: Iterator,
{
pub(crate) fn new(iter: impl IntoIterator<IntoIter = I>) -> Self {
Self {
handled_first: false,
peekable: iter.into_iter().fuse().peekable(),
}
}
}
impl<I> Clone for WithPosition<I>
where
I: Clone + Iterator,
I::Item: Clone,
{
fn clone(&self) -> Self {
Self {
handled_first: self.handled_first,
peekable: self.peekable.clone(),
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum Position<T> {
First(T),
Middle(T),
Last(T),
Only(T),
}
impl<T> Position<T> {
pub(crate) fn into_inner(self) -> T {
match self {
Self::First(x) | Self::Middle(x) | Self::Last(x) | Self::Only(x) => x,
}
}
}
impl<I: Iterator> Iterator for WithPosition<I> {
type Item = Position<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
match self.peekable.next() {
Some(item) => {
if !self.handled_first {
// Haven't seen the first item yet, and there is one to give.
self.handled_first = true;
// Peek to see if this is also the last item,
// in which case tag it as `Only`.
match self.peekable.peek() {
Some(_) => Some(Position::First(item)),
None => Some(Position::Only(item)),
}
} else {
// Have seen the first item, and there's something left.
// Peek to see if this is the last item.
match self.peekable.peek() {
Some(_) => Some(Position::Middle(item)),
None => Some(Position::Last(item)),
}
}
}
// Iterator is finished.
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.peekable.size_hint()
}
}
impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator {}
impl<I: Iterator> FusedIterator for WithPosition<I> {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/axum_test.rs | axum-macros/src/axum_test.rs | use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{parse::Parse, parse_quote, visit_mut::VisitMut, ItemFn};
pub(crate) fn expand(_attr: Attrs, mut item_fn: ItemFn) -> TokenStream {
item_fn.attrs.push(parse_quote!(#[tokio::test]));
let nest_service_fn = replace_nest_with_nest_service(item_fn.clone());
quote! {
#item_fn
#nest_service_fn
}
}
pub(crate) struct Attrs;
impl Parse for Attrs {
fn parse(_input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
Ok(Self)
}
}
fn replace_nest_with_nest_service(mut item_fn: ItemFn) -> Option<ItemFn> {
item_fn.sig.ident = format_ident!("{}_with_nest_service", item_fn.sig.ident);
let mut visitor = NestToNestService::default();
syn::visit_mut::visit_item_fn_mut(&mut visitor, &mut item_fn);
(visitor.count > 0).then_some(item_fn)
}
#[derive(Default)]
struct NestToNestService {
count: usize,
}
impl VisitMut for NestToNestService {
fn visit_expr_method_call_mut(&mut self, i: &mut syn::ExprMethodCall) {
if i.method == "nest" && i.args.len() == 2 {
i.method = parse_quote!(nest_service);
self.count += 1;
}
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/attr_parsing.rs | axum-macros/src/attr_parsing.rs | use quote::ToTokens;
use syn::{
parse::{Parse, ParseStream},
Token,
};
pub(crate) fn parse_parenthesized_attribute<K, T>(
input: ParseStream<'_>,
out: &mut Option<(K, T)>,
) -> syn::Result<()>
where
K: Parse + ToTokens,
T: Parse,
{
let kw = input.parse()?;
let content;
syn::parenthesized!(content in input);
let inner = content.parse()?;
if out.is_some() {
let kw_name = std::any::type_name::<K>().split("::").last().unwrap();
let msg = format!("`{kw_name}` specified more than once");
return Err(syn::Error::new_spanned(kw, msg));
}
*out = Some((kw, inner));
Ok(())
}
pub(crate) fn parse_assignment_attribute<K, T>(
input: ParseStream<'_>,
out: &mut Option<(K, T)>,
) -> syn::Result<()>
where
K: Parse + ToTokens,
T: Parse,
{
let kw = input.parse()?;
input.parse::<Token![=]>()?;
let inner = input.parse()?;
if out.is_some() {
let kw_name = std::any::type_name::<K>().split("::").last().unwrap();
let msg = format!("`{kw_name}` specified more than once");
return Err(syn::Error::new_spanned(kw, msg));
}
*out = Some((kw, inner));
Ok(())
}
pub(crate) trait Combine: Sized {
fn combine(self, other: Self) -> syn::Result<Self>;
}
pub(crate) fn parse_attrs<T>(ident: &str, attrs: &[syn::Attribute]) -> syn::Result<T>
where
T: Combine + Default + Parse,
{
attrs
.iter()
.filter(|attr| attr.meta.path().is_ident(ident))
.map(|attr| attr.parse_args::<T>())
.try_fold(T::default(), |out, next| out.combine(next?))
}
pub(crate) fn combine_attribute<K, T>(a: &mut Option<(K, T)>, b: Option<(K, T)>) -> syn::Result<()>
where
K: ToTokens,
{
if let Some((kw, inner)) = b {
if a.is_some() {
let kw_name = std::any::type_name::<K>().split("::").last().unwrap();
let msg = format!("`{kw_name}` specified more than once");
return Err(syn::Error::new_spanned(kw, msg));
}
*a = Some((kw, inner));
}
Ok(())
}
pub(crate) fn combine_unary_attribute<K>(a: &mut Option<K>, b: Option<K>) -> syn::Result<()>
where
K: ToTokens,
{
if let Some(kw) = b {
if a.is_some() {
let kw_name = std::any::type_name::<K>().split("::").last().unwrap();
let msg = format!("`{kw_name}` specified more than once");
return Err(syn::Error::new_spanned(kw, msg));
}
*a = Some(kw);
}
Ok(())
}
pub(crate) fn second<T, K>(tuple: (T, K)) -> K {
tuple.1
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/from_request/attr.rs | axum-macros/src/from_request/attr.rs | use crate::attr_parsing::{combine_attribute, parse_parenthesized_attribute, Combine};
use syn::{
parse::{Parse, ParseStream},
Token,
};
pub(crate) mod kw {
syn::custom_keyword!(via);
syn::custom_keyword!(rejection);
syn::custom_keyword!(state);
}
#[derive(Default)]
pub(super) struct FromRequestContainerAttrs {
pub(super) via: Option<(kw::via, syn::Path)>,
pub(super) rejection: Option<(kw::rejection, syn::Path)>,
pub(super) state: Option<(kw::state, syn::Type)>,
}
impl Parse for FromRequestContainerAttrs {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let mut via = None;
let mut rejection = None;
let mut state = None;
while !input.is_empty() {
let lh = input.lookahead1();
if lh.peek(kw::via) {
parse_parenthesized_attribute(input, &mut via)?;
} else if lh.peek(kw::rejection) {
parse_parenthesized_attribute(input, &mut rejection)?;
} else if lh.peek(kw::state) {
parse_parenthesized_attribute(input, &mut state)?;
} else {
return Err(lh.error());
}
let _ = input.parse::<Token![,]>();
}
Ok(Self {
via,
rejection,
state,
})
}
}
impl Combine for FromRequestContainerAttrs {
fn combine(mut self, other: Self) -> syn::Result<Self> {
let Self {
via,
rejection,
state,
} = other;
combine_attribute(&mut self.via, via)?;
combine_attribute(&mut self.rejection, rejection)?;
combine_attribute(&mut self.state, state)?;
Ok(self)
}
}
#[derive(Default)]
pub(super) struct FromRequestFieldAttrs {
pub(super) via: Option<(kw::via, syn::Path)>,
}
impl Parse for FromRequestFieldAttrs {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let mut via = None;
while !input.is_empty() {
let lh = input.lookahead1();
if lh.peek(kw::via) {
parse_parenthesized_attribute(input, &mut via)?;
} else {
return Err(lh.error());
}
let _ = input.parse::<Token![,]>();
}
Ok(Self { via })
}
}
impl Combine for FromRequestFieldAttrs {
fn combine(mut self, other: Self) -> syn::Result<Self> {
let Self { via } = other;
combine_attribute(&mut self.via, via)?;
Ok(self)
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/src/from_request/mod.rs | axum-macros/src/from_request/mod.rs | use self::attr::FromRequestContainerAttrs;
use crate::{
attr_parsing::{parse_attrs, second},
from_request::attr::FromRequestFieldAttrs,
};
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use std::{collections::HashSet, fmt, iter};
use syn::{
parse_quote, punctuated::Punctuated, spanned::Spanned, Fields, Ident, Path, Token, Type,
};
mod attr;
#[derive(Clone, Copy)]
pub(crate) enum Trait {
FromRequest,
FromRequestParts,
}
impl Trait {
fn via_marker_type(self) -> Option<Type> {
match self {
Self::FromRequest => Some(parse_quote!(M)),
Self::FromRequestParts => None,
}
}
}
impl fmt::Display for Trait {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FromRequest => f.write_str("FromRequest"),
Self::FromRequestParts => f.write_str("FromRequestParts"),
}
}
}
#[derive(Debug)]
enum State {
Custom(syn::Type),
Default(syn::Type),
CannotInfer,
}
impl State {
/// ```not_rust
/// impl<T> A for B {}
/// ^ this type
/// ```
fn impl_generics(&self) -> impl Iterator<Item = Type> {
match self {
Self::Default(inner) => Some(inner.clone()),
Self::Custom(_) => None,
Self::CannotInfer => Some(parse_quote!(S)),
}
.into_iter()
}
/// ```not_rust
/// impl<T> A<T> for B {}
/// ^ this type
/// ```
fn trait_generics(&self) -> impl Iterator<Item = Type> {
match self {
Self::Default(inner) | Self::Custom(inner) => iter::once(inner.clone()),
Self::CannotInfer => iter::once(parse_quote!(S)),
}
}
fn bounds(&self) -> TokenStream {
match self {
Self::Custom(_) => quote! {},
Self::Default(inner) => quote! {
#inner: ::std::marker::Send + ::std::marker::Sync,
},
Self::CannotInfer => quote! {
S: ::std::marker::Send + ::std::marker::Sync,
},
}
}
}
impl ToTokens for State {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Custom(inner) | Self::Default(inner) => inner.to_tokens(tokens),
Self::CannotInfer => quote! { S }.to_tokens(tokens),
}
}
}
pub(crate) fn expand(item: syn::Item, tr: Trait) -> syn::Result<TokenStream> {
match item {
syn::Item::Struct(item) => {
let syn::ItemStruct {
attrs,
ident,
generics,
fields,
semi_token: _,
vis: _,
struct_token: _,
} = item;
let generic_ident = parse_single_generic_type_on_struct(generics, &fields, tr)?;
let FromRequestContainerAttrs {
via,
rejection,
state,
} = parse_attrs("from_request", &attrs)?;
let state = if let Some((_, state)) = state {
State::Custom(state)
} else {
let mut inferred_state_types: HashSet<_> =
infer_state_type_from_field_types(&fields)
.chain(infer_state_type_from_field_attributes(&fields))
.collect();
if let Some((_, via)) = &via {
inferred_state_types.extend(state_from_via(&ident, via));
}
match inferred_state_types.len() {
0 => State::Default(syn::parse_quote!(S)),
1 => State::Custom(inferred_state_types.iter().next().unwrap().to_owned()),
_ => State::CannotInfer,
}
};
let trait_impl = match (via.map(second), rejection.map(second)) {
(Some(via), rejection) => impl_struct_by_extracting_all_at_once(
&ident,
fields,
&via,
rejection.as_ref(),
generic_ident.as_ref(),
&state,
tr,
)?,
(None, rejection) => {
error_on_generic_ident(generic_ident, tr)?;
impl_struct_by_extracting_each_field(&ident, &fields, rejection, &state, tr)?
}
};
if matches!(state, State::CannotInfer) {
let attr_name = match tr {
Trait::FromRequest => "from_request",
Trait::FromRequestParts => "from_request_parts",
};
let compile_error = syn::Error::new(
Span::call_site(),
format_args!(
"can't infer state type, please add \
`#[{attr_name}(state = MyStateType)]` attribute",
),
)
.into_compile_error();
Ok(quote! {
#trait_impl
#compile_error
})
} else {
Ok(trait_impl)
}
}
syn::Item::Enum(item) => {
let syn::ItemEnum {
attrs,
vis: _,
enum_token: _,
ident,
generics,
brace_token: _,
variants,
} = item;
let generics_error = format!("`#[derive({tr})]` on enums don't support generics");
if !generics.params.is_empty() {
return Err(syn::Error::new_spanned(generics, generics_error));
}
if let Some(where_clause) = generics.where_clause {
return Err(syn::Error::new_spanned(where_clause, generics_error));
}
let FromRequestContainerAttrs {
via,
rejection,
state,
} = parse_attrs("from_request", &attrs)?;
let state = match state {
Some((_, state)) => State::Custom(state),
None => (|| {
let via = via.as_ref().map(|(_, via)| via)?;
state_from_via(&ident, via).map(State::Custom)
})()
.unwrap_or_else(|| State::Default(syn::parse_quote!(S))),
};
match (via.map(second), rejection) {
(Some(via), rejection) => impl_enum_by_extracting_all_at_once(
&ident,
variants,
&via,
rejection.map(second).as_ref(),
&state,
tr,
),
(None, Some((rejection_kw, _))) => Err(syn::Error::new_spanned(
rejection_kw,
"cannot use `rejection` without `via`",
)),
(None, _) => Err(syn::Error::new(
Span::call_site(),
"missing `#[from_request(via(...))]`",
)),
}
}
_ => Err(syn::Error::new_spanned(item, "expected `struct` or `enum`")),
}
}
fn parse_single_generic_type_on_struct(
generics: syn::Generics,
fields: &syn::Fields,
tr: Trait,
) -> syn::Result<Option<Ident>> {
if let Some(where_clause) = generics.where_clause {
return Err(syn::Error::new_spanned(
where_clause,
format_args!("#[derive({tr})] doesn't support structs with `where` clauses"),
));
}
match generics.params.len() {
0 => Ok(None),
1 => {
let param = generics.params.first().unwrap();
let ty_ident = match param {
syn::GenericParam::Type(ty) => &ty.ident,
syn::GenericParam::Lifetime(lifetime) => {
return Err(syn::Error::new_spanned(
lifetime,
format_args!(
"#[derive({tr})] doesn't support structs \
that are generic over lifetimes"
),
));
}
syn::GenericParam::Const(konst) => {
return Err(syn::Error::new_spanned(
konst,
format_args!(
"#[derive({tr})] doesn't support structs \
that have const generics"
),
));
}
};
match fields {
syn::Fields::Named(fields_named) => {
return Err(syn::Error::new_spanned(
fields_named,
format_args!(
"#[derive({tr})] doesn't support named fields \
for generic structs. Use a tuple struct instead"
),
));
}
syn::Fields::Unnamed(fields_unnamed) => {
if fields_unnamed.unnamed.len() != 1 {
return Err(syn::Error::new_spanned(
fields_unnamed,
format_args!(
"#[derive({tr})] only supports generics on \
tuple structs that have exactly one field"
),
));
}
let field = fields_unnamed.unnamed.first().unwrap();
if let syn::Type::Path(type_path) = &field.ty {
if type_path.path.get_ident() != Some(ty_ident) {
return Err(syn::Error::new_spanned(
type_path,
format_args!(
"#[derive({tr})] only supports generics on \
tuple structs that have exactly one field of the generic type"
),
));
}
} else {
return Err(syn::Error::new_spanned(&field.ty, "Expected type path"));
}
}
syn::Fields::Unit => return Ok(None),
}
Ok(Some(ty_ident.clone()))
}
_ => Err(syn::Error::new_spanned(
generics,
format_args!("#[derive({tr})] only supports 0 or 1 generic type parameters"),
)),
}
}
fn error_on_generic_ident(generic_ident: Option<Ident>, tr: Trait) -> syn::Result<()> {
if let Some(generic_ident) = generic_ident {
Err(syn::Error::new_spanned(
generic_ident,
format_args!(
"#[derive({tr})] only supports generics when used with #[from_request(via)]"
),
))
} else {
Ok(())
}
}
fn impl_struct_by_extracting_each_field(
ident: &syn::Ident,
fields: &syn::Fields,
rejection: Option<syn::Path>,
state: &State,
tr: Trait,
) -> syn::Result<TokenStream> {
let trait_fn_body = if matches!(state, State::CannotInfer) {
quote! {
::std::unimplemented!()
}
} else {
let extract_fields = extract_fields(fields, rejection.as_ref(), tr)?;
quote! {
::std::result::Result::Ok(Self {
#(#extract_fields)*
})
}
};
let rejection_ident = if let Some(rejection) = rejection {
quote!(#rejection)
} else if has_no_fields(fields) {
quote!(::std::convert::Infallible)
} else {
quote!(::axum::response::Response)
};
let impl_generics = state
.impl_generics()
.collect::<Punctuated<Type, Token![,]>>();
let trait_generics = state
.trait_generics()
.collect::<Punctuated<Type, Token![,]>>();
let state_bounds = state.bounds();
Ok(match tr {
Trait::FromRequest => quote! {
#[automatically_derived]
impl<#impl_generics> ::axum::extract::FromRequest<#trait_generics> for #ident
where
#state_bounds
{
type Rejection = #rejection_ident;
async fn from_request(
mut req: ::axum::http::Request<::axum::body::Body>,
state: &#state,
) -> ::std::result::Result<Self, Self::Rejection> {
#trait_fn_body
}
}
},
Trait::FromRequestParts => quote! {
#[automatically_derived]
impl<#impl_generics> ::axum::extract::FromRequestParts<#trait_generics> for #ident
where
#state_bounds
{
type Rejection = #rejection_ident;
async fn from_request_parts(
parts: &mut ::axum::http::request::Parts,
state: &#state,
) -> ::std::result::Result<Self, Self::Rejection> {
#trait_fn_body
}
}
},
})
}
fn has_no_fields(fields: &syn::Fields) -> bool {
match fields {
syn::Fields::Named(fields) => fields.named.is_empty(),
syn::Fields::Unnamed(fields) => fields.unnamed.is_empty(),
syn::Fields::Unit => true,
}
}
fn extract_fields(
fields: &syn::Fields,
rejection: Option<&syn::Path>,
tr: Trait,
) -> syn::Result<Vec<TokenStream>> {
fn member(field: &syn::Field, index: usize) -> TokenStream {
if let Some(ident) = &field.ident {
quote! { #ident }
} else {
let member = syn::Member::Unnamed(syn::Index {
index: index as u32,
span: field.span(),
});
quote! { #member }
}
}
fn into_inner(via: Option<&(attr::kw::via, syn::Path)>, ty_span: Span) -> TokenStream {
if let Some((_, path)) = via {
let span = path.span();
quote_spanned! {span=>
|#path(inner)| inner
}
} else {
quote_spanned! {ty_span=>
::std::convert::identity
}
}
}
fn into_outer(
via: Option<&(attr::kw::via, syn::Path)>,
ty_span: Span,
field_ty: &Type,
) -> TokenStream {
if let Some((_, path)) = via {
let span = path.span();
quote_spanned! {span=>
#path<#field_ty>
}
} else {
quote_spanned! {ty_span=>
#field_ty
}
}
}
let mut fields_iter = fields.iter();
let last = match tr {
// Use FromRequestParts for all elements except the last
Trait::FromRequest => fields_iter.next_back(),
// Use FromRequestParts for all elements
Trait::FromRequestParts => None,
};
let mut res: Vec<_> = fields_iter
.enumerate()
.map(|(index, field)| {
let FromRequestFieldAttrs { via } = parse_attrs("from_request", &field.attrs)?;
let member = member(field, index);
let ty_span = field.ty.span();
let into_inner = into_inner(via.as_ref(), ty_span);
if peel_option(&field.ty).is_some() {
let field_ty = into_outer(via.as_ref(), ty_span, peel_option(&field.ty).unwrap());
let tokens = match tr {
Trait::FromRequest => {
quote_spanned! {ty_span=>
#member: {
let (mut parts, body) = req.into_parts();
let value =
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
&mut parts,
state,
)
.await
.ok()
.map(#into_inner);
req = ::axum::http::Request::from_parts(parts, body);
value
},
}
}
Trait::FromRequestParts => {
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
parts,
state,
)
.await
.ok()
.map(#into_inner)
},
}
}
};
Ok(tokens)
} else if peel_result_ok(&field.ty).is_some() {
let field_ty = into_outer(via.as_ref(), ty_span, peel_result_ok(&field.ty).unwrap());
let tokens = match tr {
Trait::FromRequest => {
quote_spanned! {ty_span=>
#member: {
let (mut parts, body) = req.into_parts();
let value =
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
&mut parts,
state,
)
.await
.map(#into_inner);
req = ::axum::http::Request::from_parts(parts, body);
value
},
}
}
Trait::FromRequestParts => {
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
parts,
state,
)
.await
.map(#into_inner)
},
}
}
};
Ok(tokens)
} else {
let field_ty = into_outer(via.as_ref(), ty_span, &field.ty);
let map_err = if let Some(rejection) = rejection {
quote! { <#rejection as ::std::convert::From<_>>::from }
} else {
quote! { ::axum::response::IntoResponse::into_response }
};
let tokens = match tr {
Trait::FromRequest => {
quote_spanned! {ty_span=>
#member: {
let (mut parts, body) = req.into_parts();
let value =
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
&mut parts,
state,
)
.await
.map(#into_inner)
.map_err(#map_err)?;
req = ::axum::http::Request::from_parts(parts, body);
value
},
}
}
Trait::FromRequestParts => {
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequestParts<_>>::from_request_parts(
parts,
state,
)
.await
.map(#into_inner)
.map_err(#map_err)?
},
}
}
};
Ok(tokens)
}
})
.collect::<syn::Result<_>>()?;
// Handle the last element, if deriving FromRequest
if let Some(field) = last {
let FromRequestFieldAttrs { via } = parse_attrs("from_request", &field.attrs)?;
let member = member(field, fields.len() - 1);
let ty_span = field.ty.span();
let into_inner = into_inner(via.as_ref(), ty_span);
let item = if peel_option(&field.ty).is_some() {
let field_ty = into_outer(via.as_ref(), ty_span, peel_option(&field.ty).unwrap());
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequest<_, _>>::from_request(req, state)
.await
.ok()
.map(#into_inner)
},
}
} else if peel_result_ok(&field.ty).is_some() {
let field_ty = into_outer(via.as_ref(), ty_span, peel_result_ok(&field.ty).unwrap());
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequest<_, _>>::from_request(req, state)
.await
.map(#into_inner)
},
}
} else {
let field_ty = into_outer(via.as_ref(), ty_span, &field.ty);
let map_err = if let Some(rejection) = rejection {
quote! { <#rejection as ::std::convert::From<_>>::from }
} else {
quote! { ::axum::response::IntoResponse::into_response }
};
quote_spanned! {ty_span=>
#member: {
<#field_ty as ::axum::extract::FromRequest<_, _>>::from_request(req, state)
.await
.map(#into_inner)
.map_err(#map_err)?
},
}
};
res.push(item);
}
Ok(res)
}
fn peel_option(ty: &syn::Type) -> Option<&syn::Type> {
let syn::Type::Path(type_path) = ty else {
return None;
};
let segment = type_path.path.segments.last()?;
if segment.ident != "Option" {
return None;
}
let args = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args,
syn::PathArguments::Parenthesized(_) | syn::PathArguments::None => return None,
};
let ty = if args.args.len() == 1 {
args.args.last().unwrap()
} else {
return None;
};
if let syn::GenericArgument::Type(ty) = ty {
Some(ty)
} else {
None
}
}
fn peel_result_ok(ty: &syn::Type) -> Option<&syn::Type> {
let syn::Type::Path(type_path) = ty else {
return None;
};
let segment = type_path.path.segments.last()?;
if segment.ident != "Result" {
return None;
}
let args = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args,
syn::PathArguments::Parenthesized(_) | syn::PathArguments::None => return None,
};
let ty = if args.args.len() == 2 {
args.args.first().unwrap()
} else {
return None;
};
if let syn::GenericArgument::Type(ty) = ty {
Some(ty)
} else {
None
}
}
fn impl_struct_by_extracting_all_at_once(
ident: &syn::Ident,
fields: syn::Fields,
via_path: &syn::Path,
rejection: Option<&syn::Path>,
generic_ident: Option<&Ident>,
state: &State,
tr: Trait,
) -> syn::Result<TokenStream> {
let fields = match fields {
syn::Fields::Named(fields) => fields.named.into_iter(),
syn::Fields::Unnamed(fields) => fields.unnamed.into_iter(),
syn::Fields::Unit => Punctuated::<_, Token![,]>::new().into_iter(),
};
for field in fields {
let FromRequestFieldAttrs { via } = parse_attrs("from_request", &field.attrs)?;
if let Some((via, _)) = via {
return Err(syn::Error::new_spanned(
via,
"`#[from_request(via(...))]` on a field cannot be used \
together with `#[from_request(...)]` on the container",
));
}
}
let path_span = via_path.span();
// for something like
//
// ```
// #[derive(Clone, Default, FromRequest)]
// #[from_request(via(State))]
// struct AppState {}
// ```
//
// we need to implement `impl<M> FromRequest<AppState, M>` but only for
// - `#[derive(FromRequest)]`, not `#[derive(FromRequestParts)]`
// - `State`, not other extractors
//
// honestly not sure why but the tests all pass
let via_marker_type = if path_ident_is_state(via_path) {
tr.via_marker_type()
} else {
None
};
let impl_generics = via_marker_type
.iter()
.cloned()
.chain(state.impl_generics())
.chain(generic_ident.is_some().then(|| parse_quote!(T)))
.collect::<Punctuated<Type, Token![,]>>();
let trait_generics = state
.trait_generics()
.chain(via_marker_type)
.collect::<Punctuated<Type, Token![,]>>();
let ident_generics = if generic_ident.is_some() {
quote! { <T> }
} else {
TokenStream::new()
};
let rejection_bound = rejection.as_ref().map(|rejection| {
match (tr, generic_ident.is_some()) {
(Trait::FromRequest, true) => {
quote! {
#rejection: ::std::convert::From<<#via_path<T> as ::axum::extract::FromRequest<#trait_generics>>::Rejection>,
}
},
(Trait::FromRequest, false) => {
quote! {
#rejection: ::std::convert::From<<#via_path<Self> as ::axum::extract::FromRequest<#trait_generics>>::Rejection>,
}
},
(Trait::FromRequestParts, true) => {
quote! {
#rejection: ::std::convert::From<<#via_path<T> as ::axum::extract::FromRequestParts<#trait_generics>>::Rejection>,
}
},
(Trait::FromRequestParts, false) => {
quote! {
#rejection: ::std::convert::From<<#via_path<Self> as ::axum::extract::FromRequestParts<#trait_generics>>::Rejection>,
}
}
}
}).unwrap_or_default();
let via_type_generics = if generic_ident.is_some() {
quote! { T }
} else {
quote! { Self }
};
let associated_rejection_type = if let Some(rejection) = &rejection {
quote! { #rejection }
} else {
match tr {
Trait::FromRequest => quote! {
<#via_path<#via_type_generics> as ::axum::extract::FromRequest<#trait_generics>>::Rejection
},
Trait::FromRequestParts => quote! {
<#via_path<#via_type_generics> as ::axum::extract::FromRequestParts<#trait_generics>>::Rejection
},
}
};
let value_to_self = if generic_ident.is_some() {
quote! {
#ident(value)
}
} else {
quote! { value }
};
let state_bounds = state.bounds();
let tokens = match tr {
Trait::FromRequest => {
quote_spanned! {path_span=>
#[automatically_derived]
impl<#impl_generics> ::axum::extract::FromRequest<#trait_generics> for #ident #ident_generics
where
#via_path<#via_type_generics>: ::axum::extract::FromRequest<#trait_generics>,
#rejection_bound
#state_bounds
{
type Rejection = #associated_rejection_type;
async fn from_request(
req: ::axum::http::Request<::axum::body::Body>,
state: &#state,
) -> ::std::result::Result<Self, Self::Rejection> {
<#via_path<#via_type_generics> as ::axum::extract::FromRequest<_, _>>::from_request(req, state)
.await
.map(|#via_path(value)| #value_to_self)
.map_err(::std::convert::From::from)
}
}
}
}
Trait::FromRequestParts => {
quote_spanned! {path_span=>
#[automatically_derived]
impl<#impl_generics> ::axum::extract::FromRequestParts<#trait_generics> for #ident #ident_generics
where
#via_path<#via_type_generics>: ::axum::extract::FromRequestParts<#trait_generics>,
#rejection_bound
#state_bounds
{
type Rejection = #associated_rejection_type;
async fn from_request_parts(
parts: &mut ::axum::http::request::Parts,
state: &#state,
) -> ::std::result::Result<Self, Self::Rejection> {
<#via_path<#via_type_generics> as ::axum::extract::FromRequestParts<_>>::from_request_parts(parts, state)
.await
.map(|#via_path(value)| #value_to_self)
.map_err(::std::convert::From::from)
}
}
}
}
};
Ok(tokens)
}
fn impl_enum_by_extracting_all_at_once(
ident: &syn::Ident,
variants: Punctuated<syn::Variant, Token![,]>,
path: &syn::Path,
rejection: Option<&syn::Path>,
state: &State,
tr: Trait,
) -> syn::Result<TokenStream> {
for variant in variants {
let FromRequestFieldAttrs { via } = parse_attrs("from_request", &variant.attrs)?;
if let Some((via, _)) = via {
return Err(syn::Error::new_spanned(
via,
"`#[from_request(via(...))]` cannot be used on variants",
));
}
let fields = match variant.fields {
syn::Fields::Named(fields) => fields.named.into_iter(),
syn::Fields::Unnamed(fields) => fields.unnamed.into_iter(),
syn::Fields::Unit => Punctuated::<_, Token![,]>::new().into_iter(),
};
for field in fields {
let FromRequestFieldAttrs { via } = parse_attrs("from_request", &field.attrs)?;
if let Some((via, _)) = via {
return Err(syn::Error::new_spanned(
via,
"`#[from_request(via(...))]` cannot be used inside variants",
));
}
}
}
let (associated_rejection_type, map_err) = if let Some(rejection) = &rejection {
let rejection = quote! { #rejection };
let map_err = quote! { ::std::convert::From::from };
(rejection, map_err)
} else {
let rejection = quote! {
::axum::response::Response
};
let map_err = quote! { ::axum::response::IntoResponse::into_response };
(rejection, map_err)
};
let path_span = path.span();
let impl_generics = state
.impl_generics()
.collect::<Punctuated<Type, Token![,]>>();
let trait_generics = state
.trait_generics()
.collect::<Punctuated<Type, Token![,]>>();
let state_bounds = state.bounds();
let tokens = match tr {
Trait::FromRequest => {
quote_spanned! {path_span=>
#[automatically_derived]
impl<#impl_generics> ::axum::extract::FromRequest<#trait_generics> for #ident
where
#state_bounds
{
type Rejection = #associated_rejection_type;
async fn from_request(
req: ::axum::http::Request<::axum::body::Body>,
state: &#state,
) -> ::std::result::Result<Self, Self::Rejection> {
<#path::<#ident> as ::axum::extract::FromRequest<_, _>>::from_request(req, state)
.await
.map(|#path(inner)| inner)
.map_err(#map_err)
}
}
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | true |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/generic_without_via_rejection.rs | axum-macros/tests/from_request/fail/generic_without_via_rejection.rs | use axum::{routing::get, Router};
use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
#[from_request(rejection(Foo))]
struct Extractor<T>(T);
async fn foo(_: Extractor<()>) {}
fn main() {
_ = Router::<()>::new().route("/", get(foo));
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/double_via_attr.rs | axum-macros/tests/from_request/fail/double_via_attr.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor(#[from_request(via(axum::Extension), via(axum::Extension))] State);
#[derive(Clone)]
struct State;
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/enum_from_request_ident_in_variant.rs | axum-macros/tests/from_request/fail/enum_from_request_ident_in_variant.rs | use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
#[from_request(via(axum::Extension))]
enum Extractor {
Foo {
#[from_request(via(axum::Extension))]
foo: (),
},
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/enum_from_request_on_variant.rs | axum-macros/tests/from_request/fail/enum_from_request_on_variant.rs | use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
#[from_request(via(axum::Extension))]
enum Extractor {
#[from_request(via(axum::Extension))]
Foo,
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/parts_extracting_body.rs | axum-macros/tests/from_request/fail/parts_extracting_body.rs | use axum::{extract::FromRequestParts, response::Response};
#[derive(FromRequestParts)]
struct Extractor {
body: String,
}
fn assert_from_request()
where
Extractor: FromRequestParts<(), Rejection = Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/generic_without_via.rs | axum-macros/tests/from_request/fail/generic_without_via.rs | use axum::{routing::get, Router};
use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
struct Extractor<T>(T);
async fn foo(_: Extractor<()>) {}
fn main() {
_ = Router::<()>::new().route("/", get(foo));
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/enum_no_via.rs | axum-macros/tests/from_request/fail/enum_no_via.rs | use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
enum Extractor {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/not_enum_or_struct.rs | axum-macros/tests/from_request/fail/not_enum_or_struct.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
union Extractor {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/unknown_attr_container.rs | axum-macros/tests/from_request/fail/unknown_attr_container.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
#[from_request(foo)]
struct Extractor;
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/via_on_container_and_field.rs | axum-macros/tests/from_request/fail/via_on_container_and_field.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
#[from_request(via(axum::Extension))]
struct Extractor(#[from_request(via(axum::Extension))] State);
#[derive(Clone)]
struct State;
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs | axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.rs | use axum::{
extract::rejection::ExtensionRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyExtractor) {}
async fn handler_result(_: Result<MyExtractor, MyRejection>) {}
#[derive(FromRequest, Clone)]
#[from_request(rejection(MyRejection))]
enum MyExtractor {}
struct MyRejection {}
impl From<ExtensionRejection> for MyRejection {
fn from(_: ExtensionRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs | axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs | use axum::extract::State;
use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor {
inner_state: State<AppState>,
other_state: State<OtherState>,
}
#[derive(Clone)]
struct AppState {}
#[derive(Clone)]
struct OtherState {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<AppState, Rejection = axum::response::Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/generic.rs | axum-macros/tests/from_request/fail/generic.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor<T>(Option<T>);
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/fail/unknown_attr_field.rs | axum-macros/tests/from_request/fail/unknown_attr_field.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor(#[from_request(foo)] String);
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/empty_tuple_parts.rs | axum-macros/tests/from_request/pass/empty_tuple_parts.rs | use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor();
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_cookie.rs | axum-macros/tests/from_request/pass/state_cookie.rs | use axum::extract::FromRef;
use axum_extra::extract::cookie::{Key, PrivateCookieJar};
use axum_macros::FromRequest;
#[derive(FromRequest)]
#[from_request(state(AppState))]
struct Extractor {
cookies: PrivateCookieJar,
}
struct AppState {
key: Key,
}
impl FromRef<AppState> for Key {
fn from_ref(input: &AppState) -> Self {
input.key.clone()
}
}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<AppState, Rejection = axum::response::Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_explicit_parts.rs | axum-macros/tests/from_request/pass/state_explicit_parts.rs | use axum::{
extract::{FromRef, Query, State},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
use std::collections::HashMap;
fn main() {
let _: axum::Router = Router::new()
.route("/b", get(|_: Extractor| async {}))
.with_state(AppState::default());
}
#[derive(FromRequestParts)]
#[from_request(state(AppState))]
struct Extractor {
inner_state: State<InnerState>,
other: Query<HashMap<String, String>>,
}
#[derive(Default, Clone)]
struct AppState {
inner: InnerState,
}
#[derive(Clone, Default)]
struct InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(input: &AppState) -> Self {
input.inner.clone()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_non_generic.rs | axum-macros/tests/from_request/pass/override_rejection_non_generic.rs | use axum::{
extract::rejection::JsonRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequest;
use serde::Deserialize;
use std::collections::HashMap;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyJson) {}
async fn handler_result(_: Result<MyJson, MyJsonRejection>) {}
#[derive(FromRequest, Deserialize)]
#[from_request(via(axum::extract::Json), rejection(MyJsonRejection))]
#[serde(transparent)]
struct MyJson(HashMap<String, String>);
struct MyJsonRejection {}
impl From<JsonRejection> for MyJsonRejection {
fn from(_: JsonRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyJsonRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs | axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum_parts.rs | use axum::{
extract::rejection::ExtensionRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyExtractor) {}
async fn handler_result(_: Result<MyExtractor, MyRejection>) {}
#[derive(FromRequestParts, Clone)]
#[from_request(via(axum::Extension), rejection(MyRejection))]
enum MyExtractor {}
struct MyRejection {}
impl From<ExtensionRejection> for MyRejection {
fn from(_: ExtensionRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/named_via_parts.rs | axum-macros/tests/from_request/pass/named_via_parts.rs | use axum::{
extract::{Extension, FromRequestParts},
response::Response,
};
use axum_extra::{
headers::{self, UserAgent},
typed_header::TypedHeaderRejection,
TypedHeader,
};
#[derive(FromRequestParts)]
struct Extractor {
#[from_request(via(Extension))]
state: State,
#[from_request(via(TypedHeader))]
user_agent: UserAgent,
#[from_request(via(TypedHeader))]
content_type: headers::ContentType,
#[from_request(via(TypedHeader))]
etag: Option<headers::ETag>,
#[from_request(via(TypedHeader))]
host: Result<headers::Host, TypedHeaderRejection>,
}
fn assert_from_request()
where
Extractor: FromRequestParts<(), Rejection = Response>,
{
}
#[derive(Clone)]
struct State;
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/enum_via.rs | axum-macros/tests/from_request/pass/enum_via.rs | use axum::{routing::get, Extension, Router};
use axum_macros::FromRequest;
#[derive(FromRequest, Clone)]
#[from_request(via(Extension))]
enum Extractor {}
async fn foo(_: Extractor) {}
fn main() {
_ = Router::<()>::new().route("/", get(foo));
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/empty_tuple.rs | axum-macros/tests/from_request/pass/empty_tuple.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor();
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_via_parts.rs | axum-macros/tests/from_request/pass/state_via_parts.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
fn main() {
let _: axum::Router = Router::new()
.route("/a", get(|_: AppState, _: InnerState, _: String| async {}))
.route("/b", get(|_: AppState, _: String| async {}))
.route("/c", get(|_: InnerState, _: String| async {}))
.with_state(AppState::default());
}
#[derive(Clone, Default, FromRequestParts)]
#[from_request(via(State))]
struct AppState {
inner: InnerState,
}
#[derive(Clone, Default, FromRequestParts)]
#[from_request(via(State), state(AppState))]
struct InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(input: &AppState) -> Self {
input.inner.clone()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/unit.rs | axum-macros/tests/from_request/pass/unit.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor;
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_field_explicit.rs | axum-macros/tests/from_request/pass/state_field_explicit.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/", get(|_: Extractor| async {}))
.with_state(AppState::default());
}
#[derive(FromRequest)]
#[from_request(state(AppState))]
struct Extractor {
#[from_request(via(State))]
state: AppState,
#[from_request(via(State))]
inner: InnerState,
}
#[derive(Clone, Default)]
struct AppState {
inner: InnerState,
}
#[derive(Clone, Default)]
struct InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(input: &AppState) -> Self {
input.inner.clone()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs | axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct.rs | use axum::{
extract::rejection::JsonRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequest;
use serde::Deserialize;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
#[derive(Deserialize)]
struct Payload {}
async fn handler(_: MyJson<Payload>) {}
async fn handler_result(_: Result<MyJson<Payload>, MyJsonRejection>) {}
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(MyJsonRejection))]
struct MyJson<T>(T);
struct MyJsonRejection {}
impl From<JsonRejection> for MyJsonRejection {
fn from(_: JsonRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyJsonRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_same_type_twice.rs | axum-macros/tests/from_request/pass/tuple_same_type_twice.rs | use axum::extract::Query;
use axum_macros::FromRequest;
use serde::Deserialize;
#[derive(FromRequest)]
struct Extractor(Query<Payload>, axum::extract::Json<Payload>);
#[derive(Deserialize)]
struct Payload {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_enum_via_parts.rs | axum-macros/tests/from_request/pass/state_enum_via_parts.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
fn main() {
let _: axum::Router = Router::new()
.route("/a", get(|_: AppState| async {}))
.route("/b", get(|_: InnerState| async {}))
.route("/c", get(|_: AppState, _: InnerState| async {}))
.with_state(AppState::default());
}
#[derive(Clone, FromRequestParts)]
#[from_request(via(State))]
enum AppState {
One,
}
impl Default for AppState {
fn default() -> AppState {
Self::One
}
}
#[derive(FromRequestParts)]
#[from_request(via(State), state(AppState))]
enum InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(_: &AppState) -> Self {
todo!("🤷")
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_parts.rs | axum-macros/tests/from_request/pass/tuple_parts.rs | use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor(axum::http::HeaderMap, axum::http::Method);
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/container.rs | axum-macros/tests/from_request/pass/container.rs | use axum::extract::{
rejection::JsonRejection,
FromRequest,
Json,
};
use serde::Deserialize;
#[derive(Deserialize, FromRequest)]
#[from_request(via(Json))]
struct Extractor {
one: i32,
two: String,
three: bool,
}
fn assert_from_request()
where
Extractor: FromRequest<(), Rejection = JsonRejection>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/container_parts.rs | axum-macros/tests/from_request/pass/container_parts.rs | use axum::extract::{
rejection::ExtensionRejection,
Extension,
FromRequestParts,
};
#[derive(Clone, FromRequestParts)]
#[from_request(via(Extension))]
struct Extractor {
one: i32,
two: String,
three: bool,
}
fn assert_from_request()
where
Extractor: FromRequestParts<(), Rejection = ExtensionRejection>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs | axum-macros/tests/from_request/pass/tuple_same_type_twice_via_parts.rs | use axum::extract::Query;
use axum::response::Response;
use axum_macros::FromRequestParts;
use serde::Deserialize;
#[derive(FromRequestParts)]
struct Extractor(
#[from_request(via(Query))] Payload,
#[from_request(via(axum::extract::Path))] Payload,
);
#[derive(Deserialize)]
struct Payload {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<(), Rejection = Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs | axum-macros/tests/from_request/pass/override_rejection_with_via_on_enum.rs | use axum::{
extract::rejection::ExtensionRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyExtractor) {}
async fn handler_result(_: Result<MyExtractor, MyRejection>) {}
#[derive(FromRequest, Clone)]
#[from_request(via(axum::Extension), rejection(MyRejection))]
enum MyExtractor {}
struct MyRejection {}
impl From<ExtensionRejection> for MyRejection {
fn from(_: ExtensionRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_with_rejection.rs | axum-macros/tests/from_request/pass/state_with_rejection.rs | use axum::{
extract::State,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequest;
use std::convert::Infallible;
fn main() {
let _: axum::Router = Router::new()
.route("/a", get(|_: Extractor| async {}))
.with_state(AppState::default());
}
#[derive(Clone, Default, FromRequest)]
#[from_request(rejection(MyRejection))]
struct Extractor {
state: State<AppState>,
}
#[derive(Clone, Default)]
struct AppState {}
struct MyRejection {}
impl From<Infallible> for MyRejection {
fn from(err: Infallible) -> Self {
match err {}
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
().into_response()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/named_parts.rs | axum-macros/tests/from_request/pass/named_parts.rs | use axum::{extract::FromRequestParts, response::Response};
use axum_extra::{
headers::{self, UserAgent},
typed_header::TypedHeaderRejection,
TypedHeader,
};
#[derive(FromRequestParts)]
struct Extractor {
uri: axum::http::Uri,
user_agent: TypedHeader<UserAgent>,
content_type: TypedHeader<headers::ContentType>,
etag: Option<TypedHeader<headers::ETag>>,
host: Result<TypedHeader<headers::Host>, TypedHeaderRejection>,
}
fn assert_from_request()
where
Extractor: FromRequestParts<(), Rejection = Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/enum_via_parts.rs | axum-macros/tests/from_request/pass/enum_via_parts.rs | use axum::{routing::get, Extension, Router};
use axum_macros::FromRequestParts;
#[derive(FromRequestParts, Clone)]
#[from_request(via(Extension))]
enum Extractor {}
async fn foo(_: Extractor) {}
fn main() {
_ = Router::<()>::new().route("/", get(foo));
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs | axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs | use axum::extract::Query;
use axum::response::Response;
use axum_macros::FromRequest;
use serde::Deserialize;
#[derive(FromRequest)]
struct Extractor(
#[from_request(via(Query))] Payload,
#[from_request(via(axum::extract::Json))] Payload,
);
#[derive(Deserialize)]
struct Payload {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<(), Rejection = Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_via_infer.rs | axum-macros/tests/from_request/pass/state_via_infer.rs | use axum::{extract::State, routing::get, Router};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/b", get(|_: AppState| async {}))
.with_state(AppState::default());
}
// if we're extract "via" `State<AppState>` and not specifying state
// assume `AppState` is the state
#[derive(Clone, Default, FromRequest)]
#[from_request(via(State))]
struct AppState {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/empty_named.rs | axum-macros/tests/from_request/pass/empty_named.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_infer.rs | axum-macros/tests/from_request/pass/state_infer.rs | use axum::extract::State;
use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor {
inner_state: State<AppState>,
}
#[derive(Clone)]
struct AppState {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<AppState, Rejection = axum::response::Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple.rs | axum-macros/tests/from_request/pass/tuple.rs | use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor(axum::http::HeaderMap, String);
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/empty_named_parts.rs | axum-macros/tests/from_request/pass/empty_named_parts.rs | use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/named.rs | axum-macros/tests/from_request/pass/named.rs | use axum::{extract::FromRequest, response::Response};
use axum_extra::{
headers::{self, UserAgent},
typed_header::TypedHeaderRejection,
TypedHeader,
};
#[derive(FromRequest)]
struct Extractor {
uri: axum::http::Uri,
user_agent: TypedHeader<UserAgent>,
content_type: TypedHeader<headers::ContentType>,
etag: Option<TypedHeader<headers::ETag>>,
host: Result<TypedHeader<headers::Host>, TypedHeaderRejection>,
body: String,
}
fn assert_from_request()
where
Extractor: FromRequest<(), Rejection = Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_enum_via.rs | axum-macros/tests/from_request/pass/state_enum_via.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/a", get(|_: AppState| async {}))
.route("/b", get(|_: InnerState| async {}))
.with_state(AppState::default());
}
#[derive(Clone, FromRequest)]
#[from_request(via(State))]
enum AppState {
One,
}
impl Default for AppState {
fn default() -> AppState {
Self::One
}
}
#[derive(FromRequest)]
#[from_request(via(State), state(AppState))]
enum InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(_: &AppState) -> Self {
todo!("🤷")
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_via.rs | axum-macros/tests/from_request/pass/state_via.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/b", get(|_: (), _: AppState| async {}))
.route("/c", get(|_: (), _: InnerState| async {}))
.with_state(AppState::default());
}
#[derive(Clone, Default, FromRequest)]
#[from_request(via(State), state(AppState))]
struct AppState {
inner: InnerState,
}
#[derive(Clone, Default, FromRequest)]
#[from_request(via(State), state(AppState))]
struct InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(input: &AppState) -> Self {
input.inner.clone()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_via_parts.rs | axum-macros/tests/from_request/pass/tuple_via_parts.rs | use axum::Extension;
use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor(#[from_request(via(Extension))] State);
#[derive(Clone)]
struct State;
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_infer_multiple.rs | axum-macros/tests/from_request/pass/state_infer_multiple.rs | use axum::extract::State;
use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor {
inner_state: State<AppState>,
also_inner_state: State<AppState>,
}
#[derive(Clone)]
struct AppState {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<AppState, Rejection = axum::response::Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection.rs | axum-macros/tests/from_request/pass/override_rejection.rs | use axum::{
extract::{rejection::ExtensionRejection, FromRequest, Request},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Extension, Router,
};
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyExtractor) {}
async fn handler_result(_: Result<MyExtractor, MyRejection>) {}
#[derive(FromRequest)]
#[from_request(rejection(MyRejection))]
struct MyExtractor {
one: Extension<String>,
#[from_request(via(Extension))]
two: String,
three: OtherExtractor,
}
struct OtherExtractor;
impl<S> FromRequest<S> for OtherExtractor
where
S: Send + Sync,
{
// this rejection doesn't implement `Display` and `Error`
type Rejection = (StatusCode, String);
async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> {
todo!()
}
}
struct MyRejection {}
impl From<ExtensionRejection> for MyRejection {
fn from(_: ExtensionRejection) -> Self {
todo!()
}
}
impl From<(StatusCode, String)> for MyRejection {
fn from(_: (StatusCode, String)) -> Self {
todo!()
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_infer_parts.rs | axum-macros/tests/from_request/pass/state_infer_parts.rs | use axum::extract::State;
use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor {
inner_state: State<AppState>,
}
#[derive(Clone)]
struct AppState {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<AppState, Rejection = axum::response::Response>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_explicit.rs | axum-macros/tests/from_request/pass/state_explicit.rs | use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/b", get(|_: Extractor| async {}))
.with_state(AppState::default());
}
#[derive(FromRequest)]
#[from_request(state(AppState))]
struct Extractor {
app_state: State<AppState>,
one: State<One>,
two: State<Two>,
other_extractor: String,
}
#[derive(Clone, Default)]
struct AppState {
one: One,
two: Two,
}
#[derive(Clone, Default)]
struct One {}
impl FromRef<AppState> for One {
fn from_ref(input: &AppState) -> Self {
input.one.clone()
}
}
#[derive(Clone, Default)]
struct Two {}
impl FromRef<AppState> for Two {
fn from_ref(input: &AppState) -> Self {
input.two.clone()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/unit_parts.rs | axum-macros/tests/from_request/pass/unit_parts.rs | use axum_macros::FromRequestParts;
#[derive(FromRequestParts)]
struct Extractor;
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<(), Rejection = std::convert::Infallible>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/named_via.rs | axum-macros/tests/from_request/pass/named_via.rs | use axum::{
extract::{Extension, FromRequest},
response::Response,
};
use axum_extra::{
headers::{self, UserAgent},
typed_header::TypedHeaderRejection,
TypedHeader,
};
#[derive(FromRequest)]
struct Extractor {
#[from_request(via(Extension))]
state: State,
#[from_request(via(TypedHeader))]
user_agent: UserAgent,
#[from_request(via(TypedHeader))]
content_type: headers::ContentType,
#[from_request(via(TypedHeader))]
etag: Option<headers::ETag>,
#[from_request(via(TypedHeader))]
host: Result<headers::Host, TypedHeaderRejection>,
}
fn assert_from_request()
where
Extractor: FromRequest<(), Rejection = Response>,
{
}
#[derive(Clone)]
struct State;
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs | axum-macros/tests/from_request/pass/override_rejection_with_via_on_struct_parts.rs | use axum::{
extract::rejection::QueryRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
use serde::Deserialize;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
#[derive(Deserialize)]
struct Payload {}
async fn handler(_: MyQuery<Payload>) {}
async fn handler_result(_: Result<MyQuery<Payload>, MyQueryRejection>) {}
#[derive(FromRequestParts)]
#[from_request(via(axum::extract::Query), rejection(MyQueryRejection))]
struct MyQuery<T>(T);
struct MyQueryRejection {}
impl From<QueryRejection> for MyQueryRejection {
fn from(_: QueryRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyQueryRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs | axum-macros/tests/from_request/pass/override_rejection_non_generic_parts.rs | use axum::{
extract::rejection::QueryRejection,
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_macros::FromRequestParts;
use serde::Deserialize;
use std::collections::HashMap;
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyQuery) {}
async fn handler_result(_: Result<MyQuery, MyQueryRejection>) {}
#[derive(FromRequestParts, Deserialize)]
#[from_request(via(axum::extract::Query), rejection(MyQueryRejection))]
#[serde(transparent)]
struct MyQuery(HashMap<String, String>);
struct MyQueryRejection {}
impl From<QueryRejection> for MyQueryRejection {
fn from(_: QueryRejection) -> Self {
todo!()
}
}
impl IntoResponse for MyQueryRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_via.rs | axum-macros/tests/from_request/pass/tuple_via.rs | use axum::Extension;
use axum_macros::FromRequest;
#[derive(FromRequest)]
struct Extractor(#[from_request(via(Extension))] State);
#[derive(Clone)]
struct State;
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/override_rejection_parts.rs | axum-macros/tests/from_request/pass/override_rejection_parts.rs | use axum::{
extract::{rejection::ExtensionRejection, FromRequestParts},
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
routing::get,
Extension, Router,
};
fn main() {
let _: Router = Router::new().route("/", get(handler).post(handler_result));
}
async fn handler(_: MyExtractor) {}
async fn handler_result(_: Result<MyExtractor, MyRejection>) {}
#[derive(FromRequestParts)]
#[from_request(rejection(MyRejection))]
struct MyExtractor {
one: Extension<String>,
#[from_request(via(Extension))]
two: String,
three: OtherExtractor,
}
struct OtherExtractor;
impl<S> FromRequestParts<S> for OtherExtractor
where
S: Send + Sync,
{
// this rejection doesn't implement `Display` and `Error`
type Rejection = (StatusCode, String);
async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
todo!()
}
}
struct MyRejection {}
impl From<ExtensionRejection> for MyRejection {
fn from(_: ExtensionRejection) -> Self {
todo!()
}
}
impl From<(StatusCode, String)> for MyRejection {
fn from(_: (StatusCode, String)) -> Self {
todo!()
}
}
impl IntoResponse for MyRejection {
fn into_response(self) -> Response {
todo!()
}
}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs | axum-macros/tests/from_request/pass/tuple_same_type_twice_parts.rs | use axum::extract::Query;
use axum_macros::FromRequestParts;
use serde::Deserialize;
#[derive(FromRequestParts)]
struct Extractor(Query<Payload>, axum::extract::Path<Payload>);
#[derive(Deserialize)]
struct Payload {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequestParts<()>,
{
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_request/pass/state_field_infer.rs | axum-macros/tests/from_request/pass/state_field_infer.rs | use axum::{extract::State, routing::get, Router};
use axum_macros::FromRequest;
fn main() {
let _: axum::Router = Router::new()
.route("/", get(|_: Extractor| async {}))
.with_state(AppState::default());
}
#[derive(FromRequest)]
struct Extractor {
#[from_request(via(State))]
state: AppState,
}
#[derive(Clone, Default)]
struct AppState {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/extract_self_mut.rs | axum-macros/tests/debug_handler/fail/extract_self_mut.rs | use axum::extract::{FromRequest, Request};
use axum_macros::debug_handler;
struct A;
impl<S> FromRequest<S> for A
where
S: Send + Sync,
{
type Rejection = ();
async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> {
unimplemented!()
}
}
impl A {
#[debug_handler]
async fn handler(&mut self) {}
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/wrong_return_type.rs | axum-macros/tests/debug_handler/fail/wrong_return_type.rs | use axum_macros::debug_handler;
#[debug_handler]
async fn handler() -> bool {
false
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/multiple_paths.rs | axum-macros/tests/debug_handler/fail/multiple_paths.rs | use axum::extract::Path;
use axum_macros::debug_handler;
#[debug_handler]
async fn handler(_: Path<String>, _: Path<String>) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs | axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs | #![allow(unused_parens)]
#[axum::debug_handler]
async fn named_type() -> (
axum::http::StatusCode,
axum::Json<&'static str>,
axum::response::AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,
) {
panic!()
}
struct CustomIntoResponse {}
impl axum::response::IntoResponse for CustomIntoResponse {
fn into_response(self) -> axum::response::Response {
todo!()
}
}
#[axum::debug_handler]
async fn custom_type() -> (
axum::http::StatusCode,
CustomIntoResponse,
axum::response::AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>,
) {
panic!()
}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/json_not_deserialize.rs | axum-macros/tests/debug_handler/fail/json_not_deserialize.rs | use axum::Json;
use axum_macros::debug_handler;
struct Struct {}
#[debug_handler]
async fn handler(_foo: Json<Struct>) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/extension_not_clone.rs | axum-macros/tests/debug_handler/fail/extension_not_clone.rs | use axum::extract::Extension;
use axum_macros::debug_handler;
struct NonCloneType;
#[debug_handler]
async fn test_extension_non_clone(_: Extension<NonCloneType>) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/multiple_request_consumers.rs | axum-macros/tests/debug_handler/fail/multiple_request_consumers.rs | use axum::{
body::Bytes,
http::{Method, Uri},
Json,
};
use axum_macros::debug_handler;
#[debug_handler]
async fn one(_: Json<()>, _: String, _: Uri) {}
#[debug_handler]
async fn two(_: Json<()>, _: Method, _: Bytes, _: Uri, _: String) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/not_async.rs | axum-macros/tests/debug_handler/fail/not_async.rs | use axum_macros::debug_handler;
#[debug_handler]
fn handler() {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/argument_not_extractor.rs | axum-macros/tests/debug_handler/fail/argument_not_extractor.rs | use axum_macros::debug_handler;
#[debug_handler]
async fn handler(_foo: bool) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
tokio-rs/axum | https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/generics.rs | axum-macros/tests/debug_handler/fail/generics.rs | use axum_macros::debug_handler;
#[debug_handler]
async fn handler<T>(_extract: T) {}
fn main() {}
| rust | MIT | 183ace306ab126f034c55d9147ea3513c8a5a139 | 2026-01-04T15:37:41.118512Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.