Skip to content

Commit

Permalink
Move middleware::from_fn into axum (#719)
Browse files Browse the repository at this point in the history
* Move `middleware::from_fn` into axum

* changelog

* fix feature

* Rephrase changelog a bit
  • Loading branch information
davidpdrsn committed Feb 22, 2022
1 parent a14cbfe commit f7a51a0
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 36 deletions.
7 changes: 7 additions & 0 deletions axum-extra/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased

- **fix:** Depend on tower with `default_features = false` ([#666])
- **change:** `middleware::from_fn` has been deprecated and moved into the main
axum crate ([#719])

[#666]: https://github.com/tokio-rs/axum/pull/666
[#719]: https://github.com/tokio-rs/axum/pull/719

# 0.1.2 (13. January, 2021)

- **fix:** Depend on tower with `default_features = false` ([#666])

# 0.1.1 (27. December, 2021)

Expand Down
2 changes: 1 addition & 1 deletion axum-extra/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ http = "0.2"
mime = "0.3"
pin-project-lite = "0.2"
tower = { version = "0.4", default_features = false, features = ["util"] }
tower-http = { version = "0.2", features = ["util", "map-response-body"] }
tower-http = { version = "0.2", features = ["map-response-body"] }
tower-layer = "0.3"
tower-service = "0.3"

Expand Down
1 change: 0 additions & 1 deletion axum-extra/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,5 @@
#![cfg_attr(test, allow(clippy::float_cmp))]

pub mod extract;
pub mod middleware;
pub mod response;
pub mod routing;
5 changes: 0 additions & 5 deletions axum-extra/src/middleware/mod.rs

This file was deleted.

5 changes: 4 additions & 1 deletion axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

# Unreleased

- None.
- **added:** `middleware::from_fn` for creating middleware from async functions.
This previously lived in axum-extra but has been moved to axum ([#719])

[#719]: https://github.com/tokio-rs/axum/pull/719

# 0.4.5 (31. January, 2022)

Expand Down
2 changes: 1 addition & 1 deletion axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ sync_wrapper = "0.1.1"
tokio = { version = "1", features = ["time"] }
tokio-util = "0.6"
tower = { version = "0.4.11", default-features = false, features = ["util", "buffer", "make"] }
tower-http = { version = "0.2.0", features = ["map-response-body"] }
tower-http = { version = "0.2.0", features = ["util", "map-response-body"] }
tower-layer = "0.3"
tower-service = "0.3"

Expand Down
1 change: 1 addition & 0 deletions axum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ pub mod body;
pub mod error_handling;
pub mod extract;
pub mod handler;
pub mod middleware;
pub mod response;
pub mod routing;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
//! Create middleware from async functions.
//!
//! See [`from_fn`] for more details.
use axum::{
use crate::{
body::{self, Bytes, HttpBody},
response::{IntoResponse, Response},
BoxError,
Expand Down Expand Up @@ -39,8 +35,8 @@ use tower_service::Service;
/// http::{Request, StatusCode},
/// routing::get,
/// response::IntoResponse,
/// middleware::{self, Next},
/// };
/// use axum_extra::middleware::{self, Next};
///
/// async fn auth<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
/// let auth_header = req.headers()
Expand Down Expand Up @@ -76,8 +72,8 @@ use tower_service::Service;
/// http::{Request, StatusCode},
/// routing::get,
/// response::IntoResponse,
/// middleware::{self, Next}
/// };
/// use axum_extra::middleware::{self, Next};
///
/// #[derive(Clone)]
/// struct State { /* ... */ }
Expand Down Expand Up @@ -109,9 +105,9 @@ use tower_service::Service;
/// http::{Request, StatusCode},
/// routing::get,
/// response::IntoResponse,
/// middleware::{self, Next},
/// AddExtensionLayer,
/// };
/// use axum_extra::middleware::{self, Next};
/// use tower::ServiceBuilder;
///
/// #[derive(Clone)]
Expand All @@ -138,37 +134,37 @@ use tower_service::Service;
/// );
/// # let app: Router = app;
/// ```
pub fn from_fn<F>(f: F) -> MiddlewareFnLayer<F> {
MiddlewareFnLayer { f }
pub fn from_fn<F>(f: F) -> FromFnLayer<F> {
FromFnLayer { f }
}

/// A [`tower::Layer`] from an async function.
///
/// [`tower::Layer`] is used to apply middleware to [`axum::Router`]s.
/// [`tower::Layer`] is used to apply middleware to [`Router`](crate::Router)'s.
///
/// Created with [`from_fn`]. See that function for more details.
#[derive(Clone, Copy)]
pub struct MiddlewareFnLayer<F> {
pub struct FromFnLayer<F> {
f: F,
}

impl<S, F> Layer<S> for MiddlewareFnLayer<F>
impl<S, F> Layer<S> for FromFnLayer<F>
where
F: Clone,
{
type Service = MiddlewareFn<F, S>;
type Service = FromFn<F, S>;

fn layer(&self, inner: S) -> Self::Service {
MiddlewareFn {
FromFn {
f: self.f.clone(),
inner,
}
}
}

impl<F> fmt::Debug for MiddlewareFnLayer<F> {
impl<F> fmt::Debug for FromFnLayer<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MiddlewareFnLayer")
f.debug_struct("FromFnLayer")
// Write out the type name, without quoting it as `&type_name::<F>()` would
.field("f", &format_args!("{}", type_name::<F>()))
.finish()
Expand All @@ -179,12 +175,12 @@ impl<F> fmt::Debug for MiddlewareFnLayer<F> {
///
/// Created with [`from_fn`]. See that function for more details.
#[derive(Clone, Copy)]
pub struct MiddlewareFn<F, S> {
pub struct FromFn<F, S> {
f: F,
inner: S,
}

impl<F, Fut, Out, S, ReqBody, ResBody> Service<Request<ReqBody>> for MiddlewareFn<F, S>
impl<F, Fut, Out, S, ReqBody, ResBody> Service<Request<ReqBody>> for FromFn<F, S>
where
F: FnMut(Request<ReqBody>, Next<ReqBody>) -> Fut,
Fut: Future<Output = Out>,
Expand Down Expand Up @@ -221,12 +217,12 @@ where
}
}

impl<F, S> fmt::Debug for MiddlewareFn<F, S>
impl<F, S> fmt::Debug for FromFn<F, S>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MiddlewareFnLayer")
f.debug_struct("FromFnLayer")
.field("f", &format_args!("{}", type_name::<F>()))
.field("inner", &self.inner)
.finish()
Expand All @@ -250,14 +246,14 @@ impl<ReqBody> Next<ReqBody> {

impl<ReqBody> fmt::Debug for Next<ReqBody> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MiddlewareFnLayer")
f.debug_struct("FromFnLayer")
.field("inner", &self.inner)
.finish()
}
}

pin_project! {
/// Response future for [`MiddlewareFn`].
/// Response future for [`FromFn`].
pub struct ResponseFuture<F> {
#[pin]
inner: F,
Expand All @@ -283,7 +279,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Empty, routing::get, Router};
use crate::{body::Empty, routing::get, Router};
use http::{HeaderMap, StatusCode};
use tower::ServiceExt;

Expand Down
5 changes: 5 additions & 0 deletions axum/src/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//! Utilities for writing middleware
mod from_fn;

pub use self::from_fn::{from_fn, FromFn, FromFnLayer, Next};
2 changes: 1 addition & 1 deletion examples/print-request-response/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
use axum::{
body::{Body, Bytes},
http::{Request, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::post,
Router,
};
use axum_extra::middleware::{self, Next};
use std::net::SocketAddr;

#[tokio::main]
Expand Down
10 changes: 8 additions & 2 deletions examples/prometheus-metrics/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@
//! cargo run -p example-prometheus-metrics
//! ```
use axum::{extract::MatchedPath, http::Request, response::IntoResponse, routing::get, Router};
use axum_extra::middleware::{self, Next};
use axum::{
extract::MatchedPath,
http::Request,
middleware::{self, Next},
response::IntoResponse,
routing::get,
Router,
};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
use std::{
future::ready,
Expand Down

0 comments on commit f7a51a0

Please sign in to comment.