I want to use the new context to wrap my handlers so I can have a User struct available in all my handlers (or whatever else I need for the current request to tell me about who is making the request).
I am getting an error with this:
func main() {
router := mux.NewRouter()
router.HandleFunc("/api/v1/user/{id}", userService.GetUsers).Methods("GET")
log.Fatal(http.ListenAndServe(":3001", router))
}
func WithAuth(us UserService, next http.Handler) http.Handler {
return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
next.ServeHTTP(w, r) // continue without token
return
}
// token, err := a.Authorize(auth)
// if err != nil {
// http.Error(w, err.Error(), http.StatusUnauthorized)
// return
// }
ctx := context.WithValue(r.Context(), "hello", "world")
next.ServeHTTP(w, r.WithContext(ctx))
})
}
The error is:
not enough arguments in call to http.HandleFunc have (func(http.ResponseWriter, *http.Request)) want (string, func(http.ResponseWriter, *http.Request)) ./main.go:65:25: http.HandleFunc(func literal) used as value ./main.go:78:12: undefined: context
I tried to adapt the code I read from here: https://gist.github.com/peterbourgon/2d190ddbb8d2cbddb5bceaca80eef20e#file-ctx-go