gpt4 book ai didi

Go Gorilla Mux MiddlewareFunc with r.Use 并返回错误

转载 作者:IT王子 更新时间:2023-10-29 02:31:02 26 4
gpt4 key购买 nike

如何设置 Gorilla Mux r.Use 以在中间件链中返回错误? https://godoc.org/github.com/gorilla/mux#Router.Use

Main.go

r := mux.NewRouter()

r.Use(LoggingFunc)
r.Use(AuthFunc)

基础中间件

从日志记录中间件开始,它可以捕获和处理来自更下游链的错误

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

func LoggingFunc(next HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Logging middleware

defer func() {
if err, ok := recover().(error); ok {
w.WriteHeader(http.StatusInternalServerError)
}
}()

err := next(w, r)
if err != nil {
// log error
}
})
}

下一个中间件处理身份验证并向日志记录中间件返回错误。

func AuthFunc(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {

if r.GET("JWT") == "" {
return fmt.Errorf("No JWT")
}

return next(w, r)
}
}

我不断收到类似这样的错误

  cannot use AuthFunc (type func(handlers.HandlerFunc) http.Handler) as type mux.MiddlewareFunc in argument to r.Use

谢谢

最佳答案

根据mux.Use doc它的参数类型是 MiddlewareFunc哪个返回类型是 http.Handler 而不是错误类型。您必须定义哪个返回类型是 http.HandlerFunc

type Middleware func(http.HandlerFunc) http.HandlerFunc

func main() {
r := mux.NewRouter()

// execute middleware from right to left of the chain
chain := Chain(SayHello, AuthFunc(), LoggingFunc())
r.HandleFunc("/", chain)

println("server listening : 8000")
http.ListenAndServe(":8000", r)
}

// Chain applies middlewares to a http.HandlerFunc
func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
for _, m := range middlewares {
f = m(f)
}
return f
}

func LoggingFunc() Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Loggin middleware

defer func() {
if _, ok := recover().(error); ok {
w.WriteHeader(http.StatusInternalServerError)
}
}()

// Call next middleware/handler in chain
next(w, r)
}
}
}

func AuthFunc() Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

if r.Header.Get("JWT") == "" {
fmt.Errorf("No JWT")
return
}

next(w, r)
}
}

}

func SayHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello client")
}

它将执行 LogginFunc,然后是 AuthFunc,然后是 SayHello 方法,这是您在传递所有这些中间件后想要的方法。

关于Go Gorilla Mux MiddlewareFunc with r.Use 并返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54443388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com