猿问

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

您如何设置 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) 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

谢谢


浮云间
浏览 168回答 1
1回答

噜噜哒

根据mux.Use 文档,它的参数类型是MiddlewareFunc,返回类型不是http.Handler错误类型。您必须定义哪种返回类型http.HandlerFunctype Middleware func(http.HandlerFunc) http.HandlerFuncfunc 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.HandlerFuncfunc 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
随时随地看视频慕课网APP

相关分类

Go
我要回答