2
votes

I am using gorilla mux for request routing. I wrote a basic middleware which I want to add user variable to context for reach in handlers. But I chould not found how can I get route parameter in the middleware:

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/{username}/accounts", AccountListHandler)

log.Fatal(http.ListenAndServe(":8080", AuthMiddleware(router)))

Middleware code:

func AuthMiddleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // params := mux.Vars(r)
        // fmt.Printf("%v", params["username"])
        user := User{Username: "myUsername"}
        ctx := context.WithValue(r.Context(), "user", user)
        h.ServeHTTP(w, r.WithContext(ctx))
    })
}

I want to reach username paramter in the middleware. How can I do this?

1

1 Answers

2
votes

The way you have it setup you will not be able to access the username. The reason for that is that your AuthMiddleware is executed before the path parameters are extracted by the router since it is wrapped inside your middleware (AuthMiddleware(router)).

You need use your middleware to wrap your handlers and then register it with the router like so:

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/{username}/accounts", AuthMiddleware(AccountListHandler))

log.Fatal(http.ListenAndServe(":8080", router))

If you have many handlers that you want to wrap with your middleware without having to repeat yourself too much you can write a simple loop like so:

var handlers = map[string]http.HandlerFunc{
    "/{username}/accounts": AccountListHandler,
    // ...
}

router := mux.NewRouter().StrictSlash(true)    
for pattern, handler := range handlers {
    router.HandleFunc(pattern, AuthMiddleware(handler))
}

log.Fatal(http.ListenAndServe(":8080", router))