使用带有 Go-chi 参数的中间件包装处理程序
Wrapping a handler with a middleware that has parameters with Go-chi
我一直在尝试使用 go-chi 实现 this 教程,尤其是关于包装/将参数传递给包装器的部分。
我的目标是能够使用具有该路由的自定义参数的中间件来包装一些特定的路由,而不是让中间件对我的所有路由都是“全局的”,但我在这样做时遇到了问题。
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
我似乎找不到让它工作或能够用中间件包装单个路由的方法。
有一个 函数 http.HandleFunc
and then there's a type http.HandlerFunc
。您正在使用前者,但您需要后者。
r.Get("/user", MustParams(http.HandlerFunc(sayHello), "key", "auth"))
我一直在尝试使用 go-chi 实现 this 教程,尤其是关于包装/将参数传递给包装器的部分。
我的目标是能够使用具有该路由的自定义参数的中间件来包装一些特定的路由,而不是让中间件对我的所有路由都是“全局的”,但我在这样做时遇到了问题。
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
我似乎找不到让它工作或能够用中间件包装单个路由的方法。
有一个 函数 http.HandleFunc
and then there's a type http.HandlerFunc
。您正在使用前者,但您需要后者。
r.Get("/user", MustParams(http.HandlerFunc(sayHello), "key", "auth"))