为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
浮云间 2023-06-05 13:30:00
您如何设置 Gorilla Mux r.Use 以在中间件链中返回错误?https://godoc.org/github.com/gorilla/mux#Router.Use主程序r := mux.NewRouter()r.Use(LoggingFunc)r.Use(AuthFunc)基础中间件从日志记录中间件开始,它可以从链的更下游捕获和处理错误type HandlerFunc func(w http.ResponseWriter, r *http.Request) errorfunc 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谢谢
查看完整描述

1 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

根据mux.Use 文档,它的参数类型是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")

}

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


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信