Skip to content

docs(examples): add custom either middleware example#709

Open
Isvane wants to merge 3 commits into
tower-rs:mainfrom
Isvane:docs/add-custom-either-mid-example
Open

docs(examples): add custom either middleware example#709
Isvane wants to merge 3 commits into
tower-rs:mainfrom
Isvane:docs/add-custom-either-mid-example

Conversation

@Isvane

@Isvane Isvane commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Description

Hey! Opening this PR to add a new example showing how to handle conditional, short-circuiting responses in custom tower middleware.

I’ve set it up under examples/custom-middleware-either with its own Cargo.toml, README.md, and src/main.rs to match the layout of the existing examples.

Note: The code is working but a bit rough around the edges, and my doc comments and the README.md are definitely lacking right now. I couldn't quite find the right words to make it super clear. I'd love some feedback on both the wording and the code during the review.

Motivation

This comes from a recent Discord discussion from Tony, Darius and @jlizen. Because Service forces you to have one concrete Response associated type, you run into a wall if your middleware wants to either bounce a request early (with an error body) or let it pass through to the inner service (with whatever body that service returns)

Solution

I added the custom-middleware-either example. Which contains:

  • Using Either<B, Full<Bytes>> to gracefully unify the happy-path body and the early-rejection error body.
  • Short-circuiting the future using std::future::ready for the error path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant