Skip to content

Commit

Permalink
Add serve function and remove Server re-export (#1868)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidpdrsn committed Apr 21, 2023
1 parent 82fb192 commit a71c8be
Show file tree
Hide file tree
Showing 86 changed files with 641 additions and 564 deletions.
4 changes: 1 addition & 3 deletions axum-extra/src/extract/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ use std::fmt;
/// }
///
/// let app = Router::new().route("/list_things", get(list_things));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// # let _: Router = app;
/// ```
///
/// If the query string cannot be parsed it will reject the request with a `400
Expand Down
2 changes: 1 addition & 1 deletion axum-extra/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ use axum_macros::__private_axum_test as test;
pub(crate) mod test_helpers {
#![allow(unused_imports)]

use axum::{body::HttpBody, BoxError, Router};
use axum::{extract::Request, response::Response, serve};

mod test_client {
#![allow(dead_code)]
Expand Down
8 changes: 2 additions & 6 deletions axum-extra/src/protobuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ use prost::Message;
/// }
///
/// let app = Router::new().route("/users", post(create_user));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// # let _: Router = app;
/// ```
///
/// # As response
Expand Down Expand Up @@ -85,9 +83,7 @@ use prost::Message;
/// }
///
/// let app = Router::new().route("/users/:id", get(get_user));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// # let _: Router = app;
/// ```
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(docsrs, doc(cfg(feature = "protobuf")))]
Expand Down
18 changes: 6 additions & 12 deletions axum-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,10 +416,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream {
/// async fn main() {
/// let app = Router::new().route("/", get(handler));
///
/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// .serve(app.into_make_service())
/// .await
/// .unwrap();
/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// axum::serve(listener, app).await.unwrap();
/// }
///
/// fn handler() -> &'static str {
Expand All @@ -438,10 +436,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream {
/// # async fn main() {
/// # let app = Router::new().route("/", get(handler));
/// #
/// # axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// # .serve(app.into_make_service())
/// # .await
/// # .unwrap();
/// # let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// # axum::serve(listener, app).await.unwrap();
/// # }
/// #
/// #[debug_handler]
Expand All @@ -468,10 +464,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream {
/// # async {
/// let app = Router::new().route("/", get(handler));
///
/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// .serve(app.into_make_service())
/// .await
/// .unwrap();
/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// axum::serve(listener, app).await.unwrap();
/// # };
/// }
///
Expand Down
3 changes: 3 additions & 0 deletions axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **added:** Add `axum::extract::Request` type alias where the body is `axum::body::Body` ([#1789])
- **added:** Add `Router::as_service` and `Router::into_service` to workaround
type inference issues when calling `ServiceExt` methods on a `Router` ([#1835])
- **breaking:** Removed `axum::Server` as it was removed in hyper 1.0. Instead
use `axum::serve(listener, service)` or hyper/hyper-util for more configuration options ([#1868])

[#1664]: https://github.com/tokio-rs/axum/pull/1664
[#1751]: https://github.com/tokio-rs/axum/pull/1751
[#1762]: https://github.com/tokio-rs/axum/pull/1762
[#1835]: https://github.com/tokio-rs/axum/pull/1835
[#1789]: https://github.com/tokio-rs/axum/pull/1789
[#1868]: https://github.com/tokio-rs/axum/pull/1868

# 0.6.16 (18. April, 2023)

Expand Down
5 changes: 5 additions & 0 deletions axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ tower = { version = "0.4.13", default-features = false, features = ["util"] }
tower-layer = "0.3.2"
tower-service = "0.3"

# wont need this when axum uses http-body 1.0
hyper1 = { package = "hyper", version = "1.0.0-rc.3", features = ["server", "http1"] }
tower-hyper-http-body-compat = { version = "0.1.4", features = ["server", "http1"] }

# optional dependencies
axum-macros = { path = "../axum-macros", version = "0.3.7", optional = true }
base64 = { version = "0.21.0", optional = true }
Expand Down Expand Up @@ -192,6 +196,7 @@ allowed = [
"http_body",
"hyper",
"serde",
"tokio",
"tower_layer",
"tower_service",
]
Expand Down
9 changes: 2 additions & 7 deletions axum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,8 @@ async fn main() {
.route("/users", post(create_user));

// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}

// basic handler that responds with a static string
Expand Down
4 changes: 2 additions & 2 deletions axum/benches/benches.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use axum::{
extract::State,
routing::{get, post},
Extension, Json, Router, Server,
Extension, Json, Router,
};
use hyper::server::conn::AddrIncoming;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -164,7 +164,7 @@ impl BenchmarkBuilder {
std::thread::spawn(move || {
rt.block_on(async move {
let incoming = AddrIncoming::from_listener(listener).unwrap();
Server::builder(incoming)
hyper::Server::builder(incoming)
.serve(app.into_make_service())
.await
.unwrap();
Expand Down
4 changes: 1 addition & 3 deletions axum/src/body/stream_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ pin_project! {
/// }
///
/// let app = Router::new().route("/", get(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// # let _: Router = app;
/// ```
///
/// [`Stream`]: futures_util::stream::Stream
Expand Down
12 changes: 3 additions & 9 deletions axum/src/docs/error_handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) {
format!("Something went wrong: {}", err),
)
}
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Applying fallible middleware
Expand Down Expand Up @@ -129,9 +127,7 @@ async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) {
)
}
}
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Running extractors for error handling
Expand Down Expand Up @@ -171,9 +167,7 @@ async fn handle_timeout_error(
format!("`{} {}` failed with {}", method, uri, err),
)
}
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

[`tower::Service`]: `tower::Service`
Expand Down
32 changes: 8 additions & 24 deletions axum/src/docs/extract.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ async fn create_user(Json(payload): Json<CreateUser>) {
}
let app = Router::new().route("/users", post(create_user));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Common extractors
Expand Down Expand Up @@ -111,9 +109,7 @@ let app = Router::new()
.route("/json", post(json))
.route("/request", post(request))
.route("/extension", post(extension));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Applying multiple extractors
Expand Down Expand Up @@ -151,9 +147,7 @@ async fn get_user_things(
// ...
}
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# The order of extractors
Expand Down Expand Up @@ -253,9 +247,7 @@ async fn create_user(payload: Option<Json<Value>>) {
}
let app = Router::new().route("/users", post(create_user));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

Wrapping extractors in `Result` makes them optional and gives you the reason
Expand Down Expand Up @@ -295,9 +287,7 @@ async fn create_user(payload: Result<Json<Value>, JsonRejection>) {
}
let app = Router::new().route("/users", post(create_user));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Customizing extractor responses
Expand Down Expand Up @@ -452,9 +442,7 @@ async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) {
}
let app = Router::new().route("/foo", get(handler));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

## Implementing `FromRequest`
Expand Down Expand Up @@ -501,9 +489,7 @@ async fn handler(ValidatedBody(body): ValidatedBody) {
}
let app = Router::new().route("/foo", get(handler));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

## Cannot implement both `FromRequest` and `FromRequestParts`
Expand Down Expand Up @@ -624,9 +610,7 @@ async fn handler(user: AuthenticatedUser) {
let state = State { /* ... */ };

let app = Router::new().route("/", get(handler)).layer(Extension(state));
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Request body limits
Expand Down
4 changes: 1 addition & 3 deletions axum/src/docs/method_routing/layer.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,5 @@ let app = Router::new().route(
// All requests to `GET /` will be sent through `ConcurrencyLimitLayer`
get(hander).layer(ConcurrencyLimitLayer::new(64)),
);
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```
4 changes: 1 addition & 3 deletions axum/src/docs/method_routing/route_layer.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,5 @@ let app = Router::new().route(
// `GET /foo` with a valid token will receive `200 OK`
// `GET /foo` with a invalid token will receive `401 Unauthorized`
// `POST /FOO` with a invalid token will receive `405 Method Not Allowed`
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```
18 changes: 5 additions & 13 deletions axum/src/docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ let app = Router::new()
.layer(TraceLayer::new_for_http())
.layer(Extension(State {}))
);
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

# Commonly used middleware
Expand Down Expand Up @@ -319,9 +317,7 @@ let app = Router::new()
}))
.layer(TimeoutLayer::new(Duration::from_secs(10)))
);
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

See [`error_handling`](crate::error_handling) for more details on axum's error
Expand Down Expand Up @@ -376,9 +372,7 @@ let app = Router::new().route("/", get(handler));
let app = ServiceBuilder::new()
.layer(some_backpressure_sensitive_middleware)
.service(app);
# async {
# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
# };
# let _: Router = app;
```

However when applying middleware around your whole application in this way
Expand Down Expand Up @@ -563,10 +557,8 @@ let app = Router::new();
let app_with_middleware = middleware.layer(app);

# async {
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app_with_middleware.into_make_service())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app_with_middleware.into_make_service()).await.unwrap();
# };
```

Expand Down
22 changes: 7 additions & 15 deletions axum/src/docs/routing/into_make_service_with_connect_info.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,8 @@ async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
}

# async {
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(
app.into_make_service_with_connect_info::<SocketAddr>()
)
.await
.expect("server failed");
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();
# };
```

Expand All @@ -36,9 +32,9 @@ You can implement custom a [`Connected`] like so:
use axum::{
extract::connect_info::{ConnectInfo, Connected},
routing::get,
serve::IncomingStream,
Router,
};
use hyper::server::conn::AddrStream;

let app = Router::new().route("/", get(handler));

Expand All @@ -53,21 +49,17 @@ struct MyConnectInfo {
// ...
}

impl Connected<&AddrStream> for MyConnectInfo {
fn connect_info(target: &AddrStream) -> Self {
impl Connected<IncomingStream<'_>> for MyConnectInfo {
fn connect_info(target: IncomingStream<'_>) -> Self {
MyConnectInfo {
// ...
}
}
}

# async {
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(
app.into_make_service_with_connect_info::<MyConnectInfo>()
)
.await
.expect("server failed");
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<MyConnectInfo>()).await.unwrap();
# };
```

Expand Down
Loading

0 comments on commit a71c8be

Please sign in to comment.