我一直在尝试用go-chi实现这教程,特别是关于包装/将参数传递给包装器的部分。
我的目标是能够用带有该路由的自定义参数的中间件包装一些特定的路由,而不是对所有路由都使用“全局”的中间件,但我在这样做时遇到了问题。
package main
import (
"context"
"io"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/user", MustParams(sayHello, "key", "auth"))
http.ListenAndServe(":3000", r)
}
func sayHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hi"))
}
func MustParams(h http.Handler, params ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
for _, param := range params {
if len(q.Get(param)) == 0 {
http.Error(w, "missing "+param, http.StatusBadRequest)
return // exit early
}
}
h.ServeHTTP(w, r) // all params present, proceed
})
}我要去找cannot use sayHello (type func(http.ResponseWriter, *http.Request)) as type http.Handler in argument to MustParams: func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)
如果我尝试输入assert来执行r.Get("/user", MustParams(http.HandleFunc(sayHello), "key", "auth"))
我得到了错误cannot use MustParams(http.HandleFunc(sayHello), "key", "auth") (type http.Handler) as type http.HandlerFunc in argument to r.Get: need type assertion
我似乎找不到一种方法来使它工作,也找不到能够用中间件包装单一路由的方法。
发布于 2021-01-12 04:20:30
有一个函数http.HandleFunc,然后有一个类型的http.HandlerFunc。你用的是前者,但你需要后者。
r.Get("/user", MustParams(http.HandlerFunc(sayHello), "key", "auth"))https://stackoverflow.com/questions/65675434
复制相似问题