我想使用新的上下文来包装我的处理程序,这样我就可以在所有处理程序中使用User结构(或者我当前请求需要的任何其他内容,告诉我谁在发出请求)。
我收到错误:
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))
})
}
错误是:
调用http.HandleFunc时没有足够的参数 (func(http.ResponseWriter,* http.Request))想要(字符串, func(http.ResponseWriter,* http.Request))。/ main.go:65:25: http.HandleFunc(func literal)用作值./main.go:78:12: undefined:context
我尝试调整我从这里读取的代码:https://gist.github.com/peterbourgon/2d190ddbb8d2cbddb5bceaca80eef20e#file-ctx-go
答案 0 :(得分:1)
你正在混合http.HandleFunc& http.Handle r Func(注意r)
func WithAuth(us UserService, next http.Handler) http.Handler {
return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
但您需要返回http.HandlerFunc而不是
func WithAuth(us UserService, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {