-
Notifications
You must be signed in to change notification settings - Fork 289
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’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add util::option_layer
and ServiceBuilder::option_layer
#553
Comments
I think something like that would be great --- are you interested in opening a PR? |
Sure, I can try. The credit goes to @LucioFranco. impl<L> ServiceBuilder<L> {
// ...
#[cfg(feature = "util")]
#[cfg_attr(docsrs, doc(cfg(feature = "util")))]
fn optional_layer<T>(self, inner: Option<T>) -> ServiceBuilder<Stack<OptionalLayer<T>, L>> {
self.layer(OptionalLayer::new(inner))
}
}
#[derive(Clone, Debug)]
pub struct OptionalLayer<L> {
inner: Option<L>,
}
impl<L> OptionalLayer<L> {
pub fn new(inner: Option<L>) -> Self {
OptionalLayer { inner }
}
}
impl<S, L> Layer<S> for OptionalLayer<L>
where
L: Layer<S>,
{
type Service = crate::util::Either<L::Service, S>;
fn layer(&self, s: S) -> Self::Service {
if let Some(inner) = &self.inner {
crate::util::Either::A(inner.layer(s))
} else {
crate::util::Either::B(s)
}
}
} Where should |
Great idea! We actually have basically the same thing at Embark but I didn't consider upstreaming it. What we have: use tower::{layer::util::Identity, util::Either};
/// Convert an `Option<Layer>` into a `Layer`
pub fn option_layer<L>(layer: Option<L>) -> Either<L, Identity> {
if let Some(layer) = layer {
Either::A(layer)
} else {
Either::B(Identity::new())
}
} This uses the fact that I think a decent setup would be to have an In my opinion we don't need a new I also prefer the name |
ServiceBuilder::optional_layer
tower::util::option_layer
and ServiceBuilder::option_layer
tower::util::option_layer
and ServiceBuilder::option_layer
util::option_layer
and ServiceBuilder::option_layer
* Add `util::option_layer` and `ServiceBuilder::option_layer` Closes #553 * Apply suggestions to improve the docs Co-authored-by: Eliza Weisman <[email protected]> Co-authored-by: Eliza Weisman <[email protected]>
Hi, thanks for
tower
.kube
is now using it under the hood (replacedreqwest
withtower
+hyper
) 🎉We have a conditional Layer to handle certain authentication methods and found
ServiceBuilderExt::optional_layer
intonic
very useful. Can we have that included intower
?We use it like the following:
The text was updated successfully, but these errors were encountered: