dongliantong3229 2018-02-06 03:57
浏览 20
已采纳

尝试提取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

  • 写回答

1条回答 默认 最新

  • dtj88302 2018-02-06 04:42
    关注

    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) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作