Remove `axum::prelude` (#195)

This commit is contained in:
Florian Thelliez 2021-08-18 00:04:15 +02:00 committed by GitHub
parent f083c3e97e
commit d9a06ef14b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 529 additions and 171 deletions

View File

@ -6,7 +6,10 @@
use axum::{
body::{box_body, Body, BoxBody},
prelude::*,
handler::get,
response::Html,
route,
routing::RoutingDsl,
};
use http::{Response, StatusCode};
use std::net::SocketAddr;
@ -34,8 +37,8 @@ async fn main() {
.unwrap();
}
async fn handler() -> response::Html<&'static str> {
response::Html("<h1>Hello, World!</h1>")
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
fn map_404(response: Response<BoxBody>) -> Response<BoxBody> {

View File

@ -3,18 +3,18 @@ mod starwars;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Request, Response, Schema};
use axum::response::IntoResponse;
use axum::{prelude::*, AddExtensionLayer};
use axum::{
extract::Extension, handler::get, response::Html, route, routing::RoutingDsl,
AddExtensionLayer, Json,
};
use starwars::{QueryRoot, StarWars, StarWarsSchema};
async fn graphql_handler(
schema: extract::Extension<StarWarsSchema>,
req: extract::Json<Request>,
) -> response::Json<Response> {
async fn graphql_handler(schema: Extension<StarWarsSchema>, req: Json<Request>) -> Json<Response> {
schema.execute(req.0).await.into()
}
async fn graphql_playground() -> impl IntoResponse {
response::Html(playground_source(GraphQLPlaygroundConfig::new("/")))
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
}
#[tokio::main]

View File

@ -14,9 +14,14 @@ use futures::{sink::SinkExt, stream::StreamExt};
use tokio::sync::broadcast;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::prelude::*;
use axum::extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
Extension,
};
use axum::handler::get;
use axum::response::{Html, IntoResponse};
use axum::route;
use axum::routing::RoutingDsl;
use axum::AddExtensionLayer;
// Our shared state
@ -46,7 +51,7 @@ async fn main() {
async fn websocket_handler(
ws: WebSocketUpgrade,
extract::Extension(state): extract::Extension<Arc<AppState>>,
Extension(state): Extension<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| websocket(socket, state))
}

View File

@ -11,10 +11,12 @@
use axum::{
async_trait,
extract::{Extension, Json, Path},
prelude::*,
extract::{Extension, Path},
handler::{get, post},
response::IntoResponse,
AddExtensionLayer,
route,
routing::RoutingDsl,
AddExtensionLayer, Json,
};
use bytes::Bytes;
use http::{Response, StatusCode};
@ -60,7 +62,7 @@ async fn main() {
async fn users_show(
Path(user_id): Path<Uuid>,
Extension(user_repo): Extension<DynUserRepo>,
) -> Result<response::Json<User>, AppError> {
) -> Result<Json<User>, AppError> {
let user = user_repo.find(user_id).await?;
Ok(user.into())
@ -70,7 +72,7 @@ async fn users_show(
async fn users_create(
Json(params): Json<CreateUser>,
Extension(user_repo): Extension<DynUserRepo>,
) -> Result<response::Json<User>, AppError> {
) -> Result<Json<User>, AppError> {
let user = user_repo.create(params).await?;
Ok(user.into())
@ -104,7 +106,7 @@ impl IntoResponse for AppError {
}
};
let mut response = response::Json(json!({
let mut response = Json(json!({
"error": error_json,
}))
.into_response();

View File

@ -4,7 +4,7 @@
//! cargo run --example form
//! ```
use axum::prelude::*;
use axum::{extract::Form, handler::get, response::Html, route, routing::RoutingDsl};
use serde::Deserialize;
use std::net::SocketAddr;
@ -28,8 +28,8 @@ async fn main() {
.unwrap();
}
async fn show_form() -> response::Html<&'static str> {
response::Html(
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
@ -60,6 +60,6 @@ struct Input {
email: String,
}
async fn accept_form(extract::Form(input): extract::Form<Input>) {
async fn accept_form(Form(input): Form<Input>) {
dbg!(&input);
}

View File

@ -4,7 +4,7 @@
//! cargo run --example hello_world
//! ```
use axum::prelude::*;
use axum::{handler::get, response::Html, route, routing::RoutingDsl};
use std::net::SocketAddr;
#[tokio::main]
@ -27,6 +27,6 @@ async fn main() {
.unwrap();
}
async fn handler() -> response::Html<&'static str> {
response::Html("<h1>Hello, World!</h1>")
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}

View File

@ -8,9 +8,10 @@
use axum::{
extract::{ContentLengthLimit, Extension, Path},
prelude::*,
handler::{delete, get, Handler},
response::IntoResponse,
routing::BoxRoute,
route,
routing::{BoxRoute, RoutingDsl},
};
use bytes::Bytes;
use http::StatusCode;

View File

@ -6,7 +6,10 @@
use axum::{
extract::{ContentLengthLimit, Multipart},
prelude::*,
handler::get,
response::Html,
route,
routing::RoutingDsl,
};
use std::net::SocketAddr;
@ -31,8 +34,8 @@ async fn main() {
.unwrap();
}
async fn show_form() -> response::Html<&'static str> {
response::Html(
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>

View File

@ -11,8 +11,10 @@ use axum::{
async_trait,
body::{Bytes, Empty},
extract::{Extension, FromRequest, Query, RequestParts, TypedHeader},
prelude::*,
handler::get,
response::{IntoResponse, Redirect},
route,
routing::RoutingDsl,
AddExtensionLayer,
};
use http::{header::SET_COOKIE, HeaderMap};
@ -212,11 +214,11 @@ where
type Rejection = AuthRedirect;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let extract::Extension(store) = extract::Extension::<MemoryStore>::from_request(req)
let Extension(store) = Extension::<MemoryStore>::from_request(req)
.await
.expect("`MemoryStore` extension is missing");
let cookies = extract::TypedHeader::<headers::Cookie>::from_request(req)
let cookies = TypedHeader::<headers::Cookie>::from_request(req)
.await
.expect("could not get cookies");

View File

@ -7,9 +7,11 @@
use async_session::{MemoryStore, Session, SessionStore as _};
use axum::{
async_trait,
extract::{FromRequest, RequestParts},
prelude::*,
extract::{Extension, FromRequest, RequestParts},
handler::get,
response::IntoResponse,
route,
routing::RoutingDsl,
AddExtensionLayer,
};
use http::header::{HeaderMap, HeaderValue};
@ -70,7 +72,7 @@ where
type Rejection = (StatusCode, &'static str);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let extract::Extension(store) = extract::Extension::<MemoryStore>::from_request(req)
let Extension(store) = Extension::<MemoryStore>::from_request(req)
.await
.expect("`MemoryStore` extension missing");

View File

@ -6,9 +6,9 @@
use axum::{
extract::TypedHeader,
prelude::*,
handler::get,
response::sse::{sse, Event, Sse},
routing::nest,
routing::{nest, RoutingDsl},
};
use futures::stream::{self, Stream};
use http::StatusCode;

View File

@ -4,7 +4,7 @@
//! cargo run --example static_file_server
//! ```
use axum::{prelude::*, routing::nest};
use axum::routing::{nest, RoutingDsl};
use http::StatusCode;
use std::net::SocketAddr;
use tower_http::{services::ServeDir, trace::TraceLayer};

View File

@ -5,7 +5,13 @@
//! ```
use askama::Template;
use axum::{prelude::*, response::IntoResponse};
use axum::{
extract,
handler::get,
response::{Html, IntoResponse},
route,
routing::RoutingDsl,
};
use bytes::Bytes;
use http::{Response, StatusCode};
use http_body::Full;
@ -53,7 +59,7 @@ where
fn into_response(self) -> Response<Self::Body> {
match self.0.render() {
Ok(html) => response::Html(html).into_response(),
Ok(html) => Html(html).into_response(),
Err(err) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::from(format!(

View File

@ -4,7 +4,13 @@
//! cargo test --example testing
//! ```
use axum::{prelude::*, routing::BoxRoute};
use axum::{
body::Body,
handler::{get, post},
route,
routing::{BoxRoute, RoutingDsl},
Json,
};
use tower_http::trace::TraceLayer;
#[tokio::main]
@ -32,8 +38,8 @@ fn app() -> BoxRoute<Body> {
route("/", get(|| async { "Hello, World!" }))
.route(
"/json",
post(|payload: extract::Json<serde_json::Value>| async move {
response::Json(serde_json::json!({ "data": payload.0 }))
post(|payload: Json<serde_json::Value>| async move {
Json(serde_json::json!({ "data": payload.0 }))
}),
)
// We can still add middleware
@ -44,7 +50,7 @@ fn app() -> BoxRoute<Body> {
#[cfg(test)]
mod tests {
use super::*;
use http::StatusCode;
use http::{Request, StatusCode};
use serde_json::{json, Value};
use std::net::{SocketAddr, TcpListener};
use tower::ServiceExt; // for `app.oneshot()`

View File

@ -4,7 +4,7 @@
//! cargo run --example tls_rustls
//! ```
use axum::prelude::*;
use axum::{handler::get, route};
use hyper::server::conn::Http;
use std::{fs::File, io::BufReader, sync::Arc};
use tokio::net::TcpListener;

View File

@ -14,9 +14,12 @@
//! ```
use axum::{
extract::{Extension, Json, Path, Query},
prelude::*,
extract::{Extension, Path, Query},
handler::{get, patch},
response::IntoResponse,
route,
routing::RoutingDsl,
Json,
};
use http::StatusCode;
use serde::{Deserialize, Serialize};
@ -95,10 +98,10 @@ async fn todos_index(
.values()
.cloned()
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(std::usize::MAX))
.take(pagination.limit.unwrap_or(usize::MAX))
.collect::<Vec<_>>();
response::Json(todos)
Json(todos)
}
#[derive(Debug, Deserialize)]
@ -118,7 +121,7 @@ async fn todos_create(
db.write().unwrap().insert(todo.id, todo.clone());
(StatusCode::CREATED, response::Json(todo))
(StatusCode::CREATED, Json(todo))
}
#[derive(Debug, Deserialize)]
@ -149,7 +152,7 @@ async fn todos_update(
db.write().unwrap().insert(todo.id, todo.clone());
Ok(response::Json(todo))
Ok(Json(todo))
}
async fn todos_delete(Path(id): Path<Uuid>, Extension(db): Extension<Db>) -> impl IntoResponse {

View File

@ -7,7 +7,9 @@
use axum::{
async_trait,
extract::{Extension, FromRequest, RequestParts},
prelude::*,
handler::get,
route,
routing::RoutingDsl,
AddExtensionLayer,
};
use bb8::{Pool, PooledConnection};

View File

@ -4,7 +4,7 @@
//! cargo run --example tracing_aka_logging
//! ```
use axum::prelude::*;
use axum::{handler::get, response::Html, route, routing::RoutingDsl};
use std::net::SocketAddr;
use tower_http::trace::TraceLayer;
@ -32,6 +32,6 @@ async fn main() {
.unwrap();
}
async fn handler() -> response::Html<&'static str> {
response::Html("<h1>Hello, World!</h1>")
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}

View File

@ -5,8 +5,12 @@
//! ```
use axum::{
body::Body,
extract::connect_info::{self, ConnectInfo},
prelude::*,
handler::get,
http::Request,
route,
routing::RoutingDsl,
};
use futures::ready;
use http::{Method, StatusCode, Uri};

View File

@ -4,11 +4,13 @@
//! cargo run --example versioning
//! ```
use axum::response::IntoResponse;
use axum::{
async_trait,
extract::{FromRequest, RequestParts},
prelude::*,
extract::{FromRequest, Path, RequestParts},
handler::get,
response::IntoResponse,
route,
routing::RoutingDsl,
};
use bytes::Bytes;
use http::Response;
@ -56,7 +58,7 @@ where
type Rejection = Response<Full<Bytes>>;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let params = extract::Path::<HashMap<String, String>>::from_request(req)
let params = Path::<HashMap<String, String>>::from_request(req)
.await
.map_err(IntoResponse::into_response)?;

View File

@ -11,9 +11,9 @@ use axum::{
ws::{Message, WebSocket, WebSocketUpgrade},
TypedHeader,
},
prelude::*,
handler::get,
response::IntoResponse,
routing::nest,
routing::{nest, RoutingDsl},
};
use http::StatusCode;
use std::net::SocketAddr;

View File

@ -130,8 +130,8 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::*;
use crate::Server;
use crate::{handler::get, route, routing::RoutingDsl};
use std::net::{SocketAddr, TcpListener};
#[tokio::test]

View File

@ -9,9 +9,14 @@ use std::ops::Deref;
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::ContentLengthLimit,
/// handler::post,
/// route,
/// routing::RoutingDsl
/// };
///
/// async fn handler(body: extract::ContentLengthLimit<String, 1024>) {
/// async fn handler(body: ContentLengthLimit<String, 1024>) {
/// // ...
/// }
///

View File

@ -9,7 +9,13 @@ use std::ops::Deref;
/// # Example
///
/// ```rust,no_run
/// use axum::{AddExtensionLayer, prelude::*};
/// use axum::{
/// AddExtensionLayer,
/// extract::Extension,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use std::sync::Arc;
///
/// // Some shared state used throughout our application
@ -17,7 +23,7 @@ use std::ops::Deref;
/// // ...
/// }
///
/// async fn handler(state: extract::Extension<Arc<State>>) {
/// async fn handler(state: Extension<Arc<State>>) {
/// // ...
/// }
///

View File

@ -34,7 +34,12 @@ use tower::{BoxError, Layer, Service};
/// # Example
///
/// ```rust
/// use axum::{extract::{extractor_middleware, RequestParts}, prelude::*};
/// use axum::{
/// extract::{extractor_middleware, FromRequest, RequestParts},
/// handler::{get, post},
/// route,
/// routing::RoutingDsl
/// };
/// use http::StatusCode;
/// use async_trait::async_trait;
///
@ -42,7 +47,7 @@ use tower::{BoxError, Layer, Service};
/// struct RequireAuth;
///
/// #[async_trait]
/// impl<B> extract::FromRequest<B> for RequireAuth
/// impl<B> FromRequest<B> for RequireAuth
/// where
/// B: Send,
/// {

View File

@ -14,7 +14,12 @@ use tower::BoxError;
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::Form,
/// handler::post,
/// route,
/// routing::RoutingDsl
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
@ -23,7 +28,7 @@ use tower::BoxError;
/// password: String,
/// }
///
/// async fn accept_form(form: extract::Form<SignUp>) {
/// async fn accept_form(form: Form<SignUp>) {
/// let sign_up: SignUp = form.0;
///
/// // ...

View File

@ -8,7 +8,12 @@
//! deserializes it as JSON into some target type:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! Json,
//! handler::{post, Handler},
//! route,
//! routing::RoutingDsl
//! };
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
@ -17,7 +22,7 @@
//! password: String,
//! }
//!
//! async fn create_user(payload: extract::Json<CreateUser>) {
//! async fn create_user(payload: Json<CreateUser>) {
//! let payload: CreateUser = payload.0;
//!
//! // ...
@ -34,7 +39,13 @@
//! You can also define your own extractors by implementing [`FromRequest`]:
//!
//! ```rust,no_run
//! use axum::{async_trait, extract::{FromRequest, RequestParts}, prelude::*};
//! use axum::{
//! async_trait,
//! extract::{FromRequest, RequestParts},
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use http::{StatusCode, header::{HeaderValue, USER_AGENT}};
//!
//! struct ExtractUserAgent(HeaderValue);
@ -74,14 +85,19 @@
//! Handlers can also contain multiple extractors:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! extract::{Path, Query},
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use std::collections::HashMap;
//!
//! async fn handler(
//! // Extract captured parameters from the URL
//! params: extract::Path<HashMap<String, String>>,
//! params: Path<HashMap<String, String>>,
//! // Parse query string into a `HashMap`
//! query_params: extract::Query<HashMap<String, String>>,
//! query_params: Query<HashMap<String, String>>,
//! // Buffer the request body into a `Bytes`
//! bytes: bytes::Bytes,
//! ) {
@ -102,7 +118,12 @@
//! Wrapping extractors in `Option` will make them optional:
//!
//! ```rust,no_run
//! use axum::{extract::Json, prelude::*};
//! use axum::{
//! extract::Json,
//! handler::post,
//! route,
//! routing::RoutingDsl
//! };
//! use serde_json::Value;
//!
//! async fn create_user(payload: Option<Json<Value>>) {
@ -123,7 +144,12 @@
//! the extraction failed:
//!
//! ```rust,no_run
//! use axum::{extract::{Json, rejection::JsonRejection}, prelude::*};
//! use axum::{
//! extract::{Json, rejection::JsonRejection},
//! handler::post,
//! route,
//! routing::RoutingDsl
//! };
//! use serde_json::Value;
//!
//! async fn create_user(payload: Result<Json<Value>, JsonRejection>) {
@ -156,11 +182,16 @@
//!
//! # Reducing boilerplate
//!
//! If you're feeling adventorous you can even deconstruct the extractors
//! If you're feeling adventurous you can even deconstruct the extractors
//! directly on the function signature:
//!
//! ```rust,no_run
//! use axum::{extract::Json, prelude::*};
//! use axum::{
//! extract::Json,
//! handler::post,
//! route,
//! routing::RoutingDsl
//! };
//! use serde_json::Value;
//!
//! async fn create_user(Json(value): Json<Value>) {
@ -187,7 +218,14 @@
//! pin::Pin,
//! };
//! use tower_http::map_request_body::MapRequestBodyLayer;
//! use axum::prelude::*;
//! use axum::{
//! extract::{self, BodyStream},
//! body::Body,
//! handler::get,
//! http::{header::HeaderMap, Request},
//! route,
//! routing::RoutingDsl
//! };
//!
//! struct MyBody<B>(B);
//!
@ -208,7 +246,7 @@
//! fn poll_trailers(
//! mut self: Pin<&mut Self>,
//! cx: &mut Context<'_>,
//! ) -> Poll<Result<Option<headers::HeaderMap>, Self::Error>> {
//! ) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
//! Pin::new(&mut self.0).poll_trailers(cx)
//! }
//! }

View File

@ -20,10 +20,15 @@ use tower::BoxError;
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::Multipart,
/// handler::post,
/// route,
/// routing::RoutingDsl
/// };
/// use futures::stream::StreamExt;
///
/// async fn upload(mut multipart: extract::Multipart) {
/// async fn upload(mut multipart: Multipart) {
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// let name = field.name().unwrap().to_string();
/// let data = field.bytes().await.unwrap();

View File

@ -11,7 +11,12 @@ use std::ops::{Deref, DerefMut};
/// # Example
///
/// ```rust,no_run
/// use axum::{extract::Path, prelude::*};
/// use axum::{
/// extract::Path,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use uuid::Uuid;
///
/// async fn users_teams_show(
@ -29,7 +34,12 @@ use std::ops::{Deref, DerefMut};
/// If the path contains only one parameter, then you can omit the tuple.
///
/// ```rust,no_run
/// use axum::{extract::Path, prelude::*};
/// use axum::{
/// extract::Path,
/// handler::get,
/// route,
/// routing::RoutingDsl,
/// };
/// use uuid::Uuid;
///
/// async fn user_info(Path(user_id): Path<Uuid>) {
@ -46,7 +56,12 @@ use std::ops::{Deref, DerefMut};
/// Path segment labels will be matched with struct field names.
///
/// ```rust,no_run
/// use axum::{extract::Path, prelude::*};
/// use axum::{
/// extract::Path,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use serde::Deserialize;
/// use uuid::Uuid;
///

View File

@ -10,7 +10,12 @@ use std::ops::Deref;
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::Query,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
@ -21,7 +26,7 @@ use std::ops::Deref;
///
/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
/// // structs.
/// async fn list_things(pagination: extract::Query<Pagination>) {
/// async fn list_things(pagination: Query<Pagination>) {
/// let pagination: Pagination = pagination.0;
///
/// // ...

View File

@ -7,10 +7,15 @@ use std::convert::Infallible;
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::RawQuery,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use futures::StreamExt;
///
/// async fn handler(extract::RawQuery(query): extract::RawQuery) {
/// async fn handler(RawQuery(query): RawQuery) {
/// // ...
/// }
///

View File

@ -90,7 +90,13 @@ where
/// # Example
///
/// ```
/// use axum::{prelude::*, routing::nest, extract::NestedUri, http::Uri};
/// use axum::{
/// handler::get,
/// route,
/// routing::{nest, RoutingDsl},
/// extract::NestedUri,
/// http::Uri
/// };
///
/// let api_routes = route(
/// "/users",
@ -165,10 +171,15 @@ where
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::BodyStream,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use futures::StreamExt;
///
/// async fn handler(mut stream: extract::BodyStream) {
/// async fn handler(mut stream: BodyStream) {
/// while let Some(chunk) = stream.next().await {
/// // ...
/// }
@ -214,10 +225,15 @@ where
/// # Example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract::Body,
/// handler::get,
/// route,
/// routing::RoutingDsl,
/// };
/// use futures::StreamExt;
///
/// async fn handler(extract::Body(body): extract::Body) {
/// async fn handler(Body(body): Body) {
/// // ...
/// }
///
@ -275,7 +291,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::{body::Body, prelude::*, tests::*};
use crate::{body::Body, handler::post, route, tests::*};
use http::StatusCode;
#[tokio::test]

View File

@ -11,7 +11,12 @@ use std::{convert::Infallible, ops::Deref};
/// # Example
///
/// ```rust,no_run
/// use axum::{extract::TypedHeader, prelude::*};
/// use axum::{
/// extract::TypedHeader,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use headers::UserAgent;
///
/// async fn users_teams_show(

View File

@ -4,9 +4,11 @@
//!
//! ```
//! use axum::{
//! prelude::*,
//! extract::ws::{WebSocketUpgrade, WebSocket},
//! handler::get,
//! response::IntoResponse,
//! route,
//! routing::RoutingDsl
//! };
//!
//! let app = route("/ws", get(handler));
@ -109,9 +111,11 @@ impl WebSocketUpgrade {
///
/// ```
/// use axum::{
/// prelude::*,
/// extract::ws::{WebSocketUpgrade, WebSocket},
/// handler::get,
/// response::IntoResponse,
/// route,
/// routing::RoutingDsl
/// };
///
/// let app = route("/ws", get(handler));

View File

@ -28,7 +28,11 @@ pub mod future;
/// # Example
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::any,
/// route,
/// routing::RoutingDsl
/// };
///
/// async fn handler() {}
///
@ -70,7 +74,11 @@ where
/// # Example
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
///
/// async fn handler() {}
///
@ -156,7 +164,11 @@ where
/// # Example
///
/// ```rust
/// use axum::{handler::on, routing::MethodFilter, prelude::*};
/// use axum::{
/// handler::on,
/// route,
/// routing::{MethodFilter, RoutingDsl},
/// };
///
/// async fn handler() {}
///
@ -219,7 +231,11 @@ pub trait Handler<B, T>: Clone + Send + Sized + 'static {
/// can be done like so:
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::{get, Handler},
/// route,
/// routing::RoutingDsl
/// };
/// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
///
/// async fn handler() { /* ... */ }
@ -467,7 +483,7 @@ impl<H, B, T, F> OnMethod<H, B, T, F> {
/// # Example
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{handler::post, route, routing::RoutingDsl};
///
/// async fn handler() {}
///
@ -557,7 +573,11 @@ impl<H, B, T, F> OnMethod<H, B, T, F> {
/// # Example
///
/// ```rust
/// use axum::{routing::MethodFilter, prelude::*};
/// use axum::{
/// handler::get,
/// route,
/// routing::{MethodFilter, RoutingDsl}
/// };
///
/// async fn handler() {}
///

View File

@ -1,6 +1,6 @@
use crate::{
extract::{has_content_type, rejection::*, take_body, FromRequest, RequestParts},
prelude::response::IntoResponse,
response::IntoResponse,
};
use async_trait::async_trait;
use bytes::Bytes;
@ -27,7 +27,12 @@ use tower::BoxError;
/// # Extractor example
///
/// ```rust,no_run
/// use axum::prelude::*;
/// use axum::{
/// extract,
/// handler::post,
/// route,
/// routing::RoutingDsl
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
@ -53,8 +58,10 @@ use tower::BoxError;
///
/// ```
/// use axum::{
/// prelude::*,
/// extract::Path,
/// handler::get,
/// route,
/// routing::RoutingDsl,
/// Json,
/// };
/// use serde::Serialize;

View File

@ -46,7 +46,11 @@
//! The "Hello, World!" of axum is:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//!
//! #[tokio::main]
//! async fn main() {
@ -73,7 +77,6 @@
//! Some examples of handlers:
//!
//! ```rust
//! use axum::prelude::*;
//! use bytes::Bytes;
//! use http::StatusCode;
//!
@ -101,7 +104,11 @@
//! Routing between handlers looks like this:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//!
//! let app = route("/", get(get_slash).post(post_slash))
//! .route("/foo", get(get_foo));
@ -133,7 +140,13 @@
//! higher precedence should be added _after_ routes with lower precedence:
//!
//! ```rust
//! use axum::{prelude::*, body::BoxBody};
//! use axum::{
//! body::{Body, BoxBody},
//! handler::get,
//! http::Request,
//! route,
//! routing::RoutingDsl
//! };
//! use tower::{Service, ServiceExt};
//! use http::{Method, Response, StatusCode};
//! use std::convert::Infallible;
@ -196,7 +209,11 @@
//! once:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! route,
//! handler::{get, post},
//! routing::RoutingDsl
//! };
//!
//! // `GET /` and `POST /` are both accepted
//! let app = route("/", get(handler).post(handler));
@ -216,7 +233,13 @@
//! axum also supports routing to general [`Service`]s:
//!
//! ```rust,no_run
//! use axum::{service, prelude::*};
//! use axum::{
//! body::Body,
//! http::Request,
//! route,
//! routing::RoutingDsl,
//! service
//! };
//! use tower_http::services::ServeFile;
//! use http::Response;
//! use std::convert::Infallible;
@ -260,7 +283,13 @@
//! Routes can be nested by calling [`nest`](routing::nest):
//!
//! ```rust,no_run
//! use axum::{prelude::*, routing::BoxRoute, body::{Body, BoxBody}};
//! use axum::{
//! body::{Body, BoxBody},
//! http::Request,
//! handler::get,
//! route,
//! routing::{BoxRoute, RoutingDsl}
//! };
//! use tower_http::services::ServeFile;
//! use http::Response;
//!
@ -284,7 +313,12 @@
//! body and deserializes it as JSON into some target type:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! extract,
//! handler::post,
//! route,
//! routing::RoutingDsl
//! };
//! use serde::Deserialize;
//!
//! let app = route("/users", post(create_user));
@ -310,7 +344,12 @@
//! [`Uuid`]:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! extract,
//! handler::post,
//! route,
//! routing::RoutingDsl
//! };
//! use uuid::Uuid;
//!
//! let app = route("/users/:id", post(create_user));
@ -326,7 +365,12 @@
//! You can also apply multiple extractors:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! extract,
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use uuid::Uuid;
//! use serde::Deserialize;
//!
@ -360,7 +404,13 @@
//! Additionally `Request<Body>` is itself an extractor:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! body::Body,
//! handler::post,
//! http::Request,
//! route,
//! routing::RoutingDsl
//! };
//!
//! let app = route("/users/:id", post(handler));
//!
@ -386,7 +436,14 @@
//! returned from a handler:
//!
//! ```rust,no_run
//! use axum::{body::Body, response::{Html, Json}, prelude::*};
//! use axum::{
//! body::Body,
//! handler::{get, Handler},
//! http::Request,
//! response::{Html, Json},
//! route,
//! routing::RoutingDsl
//! };
//! use http::{StatusCode, Response, Uri};
//! use serde_json::{Value, json};
//!
@ -466,7 +523,11 @@
//! A middleware can be applied to a single handler like so:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! handler::{get, Handler},
//! route,
//! routing::RoutingDsl
//! };
//! use tower::limit::ConcurrencyLimitLayer;
//!
//! let app = route(
@ -485,7 +546,11 @@
//! Middleware can also be applied to a group of routes like so:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! handler::{get, post},
//! route,
//! routing::RoutingDsl
//! };
//! use tower::limit::ConcurrencyLimitLayer;
//!
//! let app = route("/", get(get_slash))
@ -515,7 +580,11 @@
//! adding a middleware to a handler:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! handler::{get, Handler},
//! route,
//! routing::RoutingDsl
//! };
//! use tower::{
//! BoxError, timeout::{TimeoutLayer, error::Elapsed},
//! };
@ -564,7 +633,13 @@
//! [`tower::ServiceBuilder`] can be used to combine multiple middleware:
//!
//! ```rust,no_run
//! use axum::prelude::*;
//! use axum::{
//! body::Body,
//! handler::get,
//! http::Request,
//! route,
//! routing::RoutingDsl
//! };
//! use tower::ServiceBuilder;
//! use tower_http::compression::CompressionLayer;
//! use std::{borrow::Cow, time::Duration};
@ -595,7 +670,13 @@
//! and the [`extract::Extension`] extractor:
//!
//! ```rust,no_run
//! use axum::{AddExtensionLayer, prelude::*};
//! use axum::{
//! AddExtensionLayer,
//! extract,
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use std::sync::Arc;
//!
//! struct State {
@ -740,21 +821,6 @@ pub use tower_http::add_extension::{AddExtension, AddExtensionLayer};
pub use self::{error::Error, json::Json};
pub mod prelude {
//! Re-exports of important traits, types, and functions used with axum. Meant to be glob
//! imported.
pub use crate::body::Body;
pub use crate::extract;
pub use crate::handler::{
any, connect, delete, get, head, options, patch, post, put, trace, Handler,
};
pub use crate::response;
pub use crate::route;
pub use crate::routing::RoutingDsl;
pub use http::Request;
}
/// Create a route.
///
/// `description` is a string of path segments separated by `/`. Each segment
@ -770,7 +836,12 @@ pub mod prelude {
/// # Examples
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// body::Body,
/// http::Request,
/// route
/// };
///
/// # use std::convert::Infallible;
/// # use http::Response;
/// # let service = tower::service_fn(|_: Request<Body>| async {

View File

@ -41,7 +41,12 @@ pub use self::{
/// response body type:
///
/// ```rust
/// use axum::{prelude::*, response::IntoResponse};
/// use axum::{
/// handler::get,
/// response::IntoResponse,
/// route,
/// routing::RoutingDsl
/// };
/// use http_body::Body;
/// use http::{Response, HeaderMap};
/// use bytes::Bytes;

View File

@ -9,7 +9,12 @@ use std::convert::TryFrom;
/// # Example
///
/// ```rust
/// use axum::{prelude::*, response::Redirect};
/// use axum::{
/// handler::get,
/// response::Redirect,
/// route,
/// routing::RoutingDsl
/// };
///
/// let app = route("/old", get(|| async { Redirect::permanent("/new".parse().unwrap()) }))
/// .route("/new", get(|| async { "Hello!" }));

View File

@ -3,7 +3,11 @@
//! # Example
//!
//! ```
//! use axum::prelude::*;
//! use axum::{
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use axum::response::sse::{sse, Event, KeepAlive, Sse};
//! use std::{time::Duration, convert::Infallible};
//! use tokio_stream::StreamExt as _ ;

View File

@ -54,7 +54,11 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// # Example
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
///
/// async fn first_handler() { /* ... */ }
///
@ -101,7 +105,12 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// return them from functions:
///
/// ```rust
/// use axum::{routing::BoxRoute, body::Body, prelude::*};
/// use axum::{
/// body::Body,
/// handler::get,
/// route,
/// routing::{BoxRoute, RoutingDsl}
/// };
///
/// async fn first_handler() { /* ... */ }
///
@ -153,7 +162,11 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// routes can be done like so:
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
///
/// async fn first_handler() { /* ... */ }
@ -179,7 +192,11 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// entire app:
///
/// ```rust
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use tower_http::trace::TraceLayer;
///
/// async fn first_handler() { /* ... */ }
@ -210,7 +227,11 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// [`Server`](hyper::server::Server):
///
/// ```
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
///
/// let app = route("/", get(|| async { "Hi!" }));
///
@ -239,7 +260,12 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// Extracting [`std::net::SocketAddr`] is supported out of the box:
///
/// ```
/// use axum::{prelude::*, extract::ConnectInfo};
/// use axum::{
/// extract::ConnectInfo,
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use std::net::SocketAddr;
///
/// let app = route("/", get(handler));
@ -262,8 +288,10 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
///
/// ```
/// use axum::{
/// prelude::*,
/// extract::connect_info::{ConnectInfo, Connected},
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// use hyper::server::conn::AddrStream;
///
@ -323,7 +351,11 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// into one.
///
/// ```
/// use axum::prelude::*;
/// use axum::{
/// handler::get,
/// route,
/// routing::RoutingDsl
/// };
/// #
/// # async fn users_list() {}
/// # async fn users_show() {}
@ -359,7 +391,12 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// # Example
///
/// ```
/// use axum::{http::StatusCode, prelude::*};
/// use axum::{
/// handler::get,
/// http::StatusCode,
/// route,
/// routing::RoutingDsl
/// };
/// use tower::{BoxError, timeout::TimeoutLayer};
/// use std::{time::Duration, convert::Infallible};
///
@ -394,7 +431,12 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized {
/// some errors:
///
/// ```
/// use axum::{http::StatusCode, prelude::*};
/// use axum::{
/// handler::get,
/// http::StatusCode,
/// route,
/// routing::RoutingDsl
/// };
/// use tower::{BoxError, timeout::TimeoutLayer};
/// use std::time::Duration;
///
@ -794,7 +836,11 @@ where
/// them together.
///
/// ```
/// use axum::{routing::nest, prelude::*};
/// use axum::{
/// handler::get,
/// route,
/// routing::{nest, RoutingDsl},
/// };
/// use http::Uri;
///
/// async fn users_get(uri: Uri) {
@ -818,10 +864,15 @@ where
/// captures from the outer routes:
///
/// ```
/// use axum::{routing::nest, prelude::*};
/// use axum::{
/// extract::Path,
/// handler::get,
/// route,
/// routing::{nest, RoutingDsl},
/// };
/// use std::collections::HashMap;
///
/// async fn users_get(extract::Path(params): extract::Path<HashMap<String, String>>) {
/// async fn users_get(Path(params): Path<HashMap<String, String>>) {
/// // Both `version` and `id` were captured even though `users_api` only
/// // explicitly captures `id`.
/// let version = params.get("version");
@ -841,7 +892,8 @@ where
///
/// ```
/// use axum::{
/// routing::nest, service::get, prelude::*,
/// routing::{nest, RoutingDsl},
/// service::get,
/// };
/// use tower_http::services::ServeDir;
///

View File

@ -11,14 +11,21 @@
//!
//! ```
//! use tower_http::services::Redirect;
//! use axum::{service, handler, prelude::*};
//! use axum::{
//! body::Body,
//! handler::get,
//! http::Request,
//! route,
//! routing::RoutingDsl,
//! service,
//! };
//!
//! async fn handler(request: Request<Body>) { /* ... */ }
//!
//! let redirect_service = Redirect::<Body>::permanent("/new".parse().unwrap());
//!
//! let app = route("/old", service::get(redirect_service))
//! .route("/new", handler::get(handler));
//! .route("/new", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
@ -58,7 +65,11 @@
//! themselves services:
//!
//! ```rust
//! use axum::prelude::*;
//! use axum::{
//! handler::get,
//! route,
//! routing::RoutingDsl
//! };
//! use tower::ServiceBuilder;
//! # let some_backpressure_sensitive_middleware =
//! # tower::layer::util::Identity::new();
@ -137,7 +148,12 @@ where
/// # Example
///
/// ```rust
/// use axum::{service, prelude::*};
/// use axum::{
/// http::Request,
/// route,
/// routing::RoutingDsl,
/// service,
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
@ -228,7 +244,13 @@ where
/// # Example
///
/// ```rust
/// use axum::{handler::on, service, routing::MethodFilter, prelude::*};
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// route,
/// routing::{MethodFilter, RoutingDsl},
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
@ -317,7 +339,13 @@ impl<S, F, B> OnMethod<S, F, B> {
/// # Example
///
/// ```rust
/// use axum::{handler::on, service, routing::MethodFilter, prelude::*};
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// route,
/// routing::{MethodFilter, RoutingDsl},
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
@ -414,7 +442,13 @@ impl<S, F, B> OnMethod<S, F, B> {
/// # Example
///
/// ```rust
/// use axum::{handler::on, service, routing::MethodFilter, prelude::*};
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// route,
/// routing::{MethodFilter, RoutingDsl},
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
@ -583,7 +617,7 @@ where
}
/// ```compile_fail
/// use crate::{service::ServiceExt, prelude::*};
/// use crate::{service::ServiceExt};
/// use tower::service_fn;
/// use hyper::Body;
/// use http::{Request, Response, StatusCode};

View File

@ -1,7 +1,12 @@
#![allow(clippy::blacklisted_name)]
use crate::{
extract::RequestParts, handler::on, prelude::*, routing::nest, routing::MethodFilter, service,
extract,
handler::{any, delete, get, on, patch, post, Handler},
route,
routing::nest,
routing::{MethodFilter, RoutingDsl},
service,
};
use bytes::Bytes;
use futures_util::future::Ready;
@ -442,7 +447,7 @@ async fn test_extractor_middleware() {
{
type Rejection = StatusCode;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
async fn from_request(req: &mut extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
if let Some(auth) = req
.headers()
.expect("headers already extracted")