Request: Allow specifying middleware only for selected handlers #9

Open
opened 2025-08-28 04:18:22 +00:00 by mybigman · 3 comments

Currently middleware doesn't respect the order they are applied.

Both middleware 1 and 2 are applied to both routes.

Ideally only middleware 1 should be applied to the first route, then middleware 1 and 2 for the second route.

s.Use(middleware1)

s.Get("/1", func(ctx web.Context) error {
	return ctx.String("Hello 1")
})

s.Use(middleware2)

s.Get("/2", func(ctx web.Context) error {
	return ctx.String("Hello 2")
})

Currently middleware doesn't respect the order they are applied. Both middleware 1 and 2 are applied to both routes. Ideally only middleware 1 should be applied to the first route, then middleware 1 and 2 for the second route. ```go s.Use(middleware1) s.Get("/1", func(ctx web.Context) error { return ctx.String("Hello 1") }) s.Use(middleware2) s.Get("/2", func(ctx web.Context) error { return ctx.String("Hello 2") }) ```
Owner

Marking this as a feature request because it's the currently intended behavior and not a bug.
For an example of a beautiful interface with this functionality, see https://github.com/go-chi/chi.
I am definitely in favor of this, but I will most likely not have the time to work on it because my other project keeps me busy full-time.

Marking this as a feature request because it's the currently intended behavior and not a bug. For an example of a beautiful interface with this functionality, see https://github.com/go-chi/chi. I am definitely in favor of this, but I will most likely not have the time to work on it because my other project keeps me busy full-time.
ed changed title from respect middleware order to Request: Allow specifying middleware only for selected handlers 2025-08-28 06:00:10 +00:00
Author

I have working solution with minimal changes.

s.Use() stil applies global middleware

and for route specific middleware

	s.Get("/", func(ctx web.Context) error {
		return ctx.String("Hello Get")
	}, middleware.Foobar, middleware.Other, ...)

if your ok with this I will submit a PR

I have working solution with minimal changes. `s.Use()` stil applies global middleware and for route specific middleware ```go s.Get("/", func(ctx web.Context) error { return ctx.String("Hello Get") }, middleware.Foobar, middleware.Other, ...) ``` if your ok with this I will submit a PR
Owner

That could work, but is this really the best API we could come up with?
I think we're leaving a better interface on the table.

That could work, but is this really the best API we could come up with? I think we're leaving a better interface on the table.
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: go/web#9
No description provided.