gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
20.92k stars 1.85k forks source link

Feature route middleware with `.Use` #759

Closed cornejong closed 5 months ago

cornejong commented 6 months ago

What type of PR is this? (check all applicable)

Description

Added support for route specific middleware using the .Use method. Using the .Use method on Route middlewares can be set on a specific route.

Example:

router.HandleFunc("/", handlerFunc).Use(middleware)

Related Tickets & Documents

Added/updated tests?

Run verifications and test

cornejong commented 6 months ago

Currently, you can add middleware to a single route by wrapping the handler in it:

router.Handle("/", middleware(http.HandlerFunc(myHandlerFunc)))

This approach works fine for a single middleware but becomes cluttered quickly when adding more than one:

router.Handle("/", middleware1(middleware2(http.HandlerFunc(myHandlerFunc))))

This got me thinking that it would be great if we could assign middleware to a route using the .Use method, similar to how it's done on the router. This would result in cleaner, more consistent, and more readable code. For example:

router.HandleFunc("/", handlerFunc)
    .Methods(http.MethodGet)
    .Use(middleware1, middleware2)
    .Name("route")
pcfreak30 commented 5 months ago

really appreciate creating this. I am needing this now to keep my sanity, lol.

would love to see this merged

AlexVulaj commented 5 months ago

This looks like a pretty solid addition, thanks for the contribution!

cornejong commented 5 months ago

Thanks for the merge! Always happy to contribute.