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 2 commits
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
25 changes: 25 additions & 0 deletions tower-layer/src/layer_fn.rs
@@ -0,0 +1,25 @@
use super::Layer;

/// Returns a new `impl Layer` with the given closure.
pub fn layer_fn<F, S, T>(f: F) -> impl Layer<S, Service = T> + Clone
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could be nice to have an example here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes ofc. Added one in bbf93a7

where
F: Fn(S) -> T + Clone,
{
LayerFn { f }
}

#[derive(Clone, Copy, Debug)]
hawkw marked this conversation as resolved.
Show resolved Hide resolved
struct LayerFn<F> {
f: F,
}

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

fn layer(&self, inner: S) -> Self::Service {
(self.f)(inner)
}
}
3 changes: 2 additions & 1 deletion tower-layer/src/lib.rs
Expand Up @@ -14,9 +14,10 @@
//! 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, stack::Stack};

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