Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add layer_fn #491

Merged
merged 6 commits into from Dec 29, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions tower-layer/src/layer_fn.rs
@@ -0,0 +1,23 @@
use super::Layer;

/// Returns a new `LayerFn` with the given closure.
pub fn layer_fn<T>(f: T) -> LayerFn<T> {
hawkw marked this conversation as resolved.
Show resolved Hide resolved
LayerFn { f }
}

/// A `Layer` implemented by a closure.
#[derive(Clone, Copy, Debug)]
hawkw marked this conversation as resolved.
Show resolved Hide resolved
pub struct LayerFn<F> {
f: F,
}

impl<F, S, Out> Layer<S> for LayerFn<F>
where
F: Fn(S) -> Out,
{
type Service = Out;

fn layer(&self, inner: S) -> Self::Service {
(self.f)(inner)
}
}
7 changes: 6 additions & 1 deletion tower-layer/src/lib.rs
Expand Up @@ -14,9 +14,14 @@
//! A middleware implements the [`Layer`] and [`Service`] trait.

mod identity;
mod layer_fn;
mod stack;

pub use self::{identity::Identity, stack::Stack};
pub use self::{
identity::Identity,
layer_fn::{layer_fn, LayerFn},
stack::Stack,
};

/// Decorates a `Service`, transforming either the request or the response.
///
Expand Down