Last active
November 23, 2021 11:07
-
-
Save komuw/1a40397065d00fd4c7468bd54294d63c to your computer and use it in GitHub Desktop.
golang muxes do not inherit middlewares. Also middlewares are not deduped.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"github.com/go-chi/chi" | |
"github.com/gorilla/mux" | |
) | |
func adminMiddleware(next http.Handler) http.Handler { | |
fmt.Println("\n\n\t adminMiddleware called start.") | |
fn := func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("\n\n\t adminMiddleware called everytime.") | |
next.ServeHTTP(w, r) | |
} | |
return http.HandlerFunc(fn) | |
} | |
func TraceIdMiddleware(next http.Handler) http.Handler { | |
fmt.Println("\n\n\t TraceIdMiddleware called start.") | |
fn := func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("\n\n\t TraceIdMiddleware called everytime.") | |
next.ServeHTTP(w, r) | |
} | |
return http.HandlerFunc(fn) | |
} | |
func checkGorillaMux() { | |
tw := TraceIdMiddleware | |
aw := adminMiddleware | |
r := mux.NewRouter() | |
r.Use(tw) | |
r.Use(TraceIdMiddleware) // both chi and gorilla do not dedupe middlewares. | |
r.Use(TraceIdMiddleware) // so TraceIdMiddleware will be ran thrice for the same request | |
adminRouter := r.PathPrefix("/admin").Subrouter() | |
adminRouter.Use(aw) | |
fmt.Println("tw: ", tw) | |
fmt.Println("aw: ", aw) | |
fmt.Println("r.AllMiddleware(): ", r.AllMiddleware()) | |
fmt.Println("adminRouter.AllMiddleware(): ", adminRouter.AllMiddleware()) | |
} | |
func checkChiMux() { | |
aw := adminMiddleware | |
tw := TraceIdMiddleware | |
r := chi.NewRouter() | |
r.Use(tw) | |
adminRouter := chi.NewRouter() | |
adminRouter.Use(aw) | |
r.Mount("/api", adminRouter) | |
fmt.Println() | |
fmt.Println("tw: ", tw) | |
fmt.Println("aw: ", aw) | |
fmt.Println("r.AllMiddleware(): ", r.AllMiddleware()) | |
fmt.Println("adminRouter.AllMiddleware(): ", adminRouter.AllMiddleware()) | |
} | |
func main() { | |
checkGorillaMux() | |
checkChiMux() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
goimports -w .;gofmt -w -s .;go mod tidy;go run . | |
tw: 0x56f540 | |
aw: 0x56f440 | |
r.AllMiddleware(): [0x56f540] | |
adminRouter.AllMiddleware(): [0x56f440] | |
TraceIdMiddleware called start. | |
tw: 0x56f540 | |
aw: 0x56f440 | |
r.AllMiddleware(): [0x56f540] | |
adminRouter.AllMiddleware(): [0x56f440] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the dedupe issue.