尝试提取API请求令牌并包装我的处理程序

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

You're mixing http.HandleFunc & http.HandlerFunc (note the r)

func WithAuth(us UserService, next http.Handler) http.Handler {
      return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {

but you need to return a http.HandlerFunc instead

 func WithAuth(us UserService, next http.Handler) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {