亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 gorilla mux 中的 Get Subrouter 中為特定路由使用特定中間件

如何在 gorilla mux 中的 Get Subrouter 中為特定路由使用特定中間件

Go
BIG陽 2022-07-11 16:47:40
我對 Gorilla mux 路由有一個特定要求,我想為一個子路由器下的不同路由添加不同的中間件(在我的例子中是 GET 子路由器)。下面是我的路由代碼:    // create a serve mux    sm := mux.NewRouter()    // register handlers    postR := sm.Methods(http.MethodPost).Subrouter()    postR.HandleFunc("/signup", uh.Signup)    postR.HandleFunc("/login", uh.Login)    postR.Use(uh.MiddlewareValidateUser)    getR := sm.Methods(http.MethodGet).Subrouter()    getR.HandleFunc("/refresh-token", uh.RefreshToken)    getR.HandleFunc("/user-profile", uh.GetUserProfile)在上面的路由器邏輯中,我的 /refresh-token 和 /user-profile 令牌都屬于 getR 路由器。我還有兩個名為 ValidateAccessToken 和 ValidateRefreshToken 的中間件函數。我想將 ValidateRefreshToken 中間件函數用于“/refresh-token”路由,并將 ValidateAccessToken 用于 GET 子路由器下的所有其他路由。我想用 Gorilla mux 路由本身來做到這一點。請建議我完成上述場景的適當方法。感謝您的時間和精力。
查看完整描述

2 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

notorious.no 提供的解決方案也非常適合給定的要求。我還遇到了另一個使用 PathPrefix 并解決相同問題的解決方案,并希望獲得相同的建議。


    // create a serve mux

    sm := mux.NewRouter()


    // register handlers

    postR := sm.Methods(http.MethodPost).Subrouter()

    postR.HandleFunc("/signup", uh.Signup)

    postR.HandleFunc("/login", uh.Login)

    postR.Use(uh.MiddlewareValidateUser)


    refToken := sm.PathPrefix("/refresh-token").Subrouter()

    refToken.HandleFunc("", uh.RefreshToken)

    refToken.Use(uh.MiddlewareValidateRefreshToken)


    getR := sm.Methods(http.MethodGet).Subrouter()

    getR.HandleFunc("/greet", uh.Greet)

    getR.Use(uh.MiddlewareValidateAccessToken)

使用參考來到這個解決方案:https ://github.com/gorilla/mux/issues/360


查看完整回答
反對 回復 2022-07-11
?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

我有一個類似的用例,這是我如何解決它的一個例子:


package main


import (

    "log"

    "net/http"

    "time"

)


import (

    "github.com/gorilla/mux"

)


// Adapter is an alias so I dont have to type so much.

type Adapter func(http.Handler) http.Handler


// Adapt takes Handler funcs and chains them to the main handler.

func Adapt(handler http.Handler, adapters ...Adapter) http.Handler {

    // The loop is reversed so the adapters/middleware gets executed in the same

    // order as provided in the array.

    for i := len(adapters); i > 0; i-- {

        handler = adapters[i-1](handler)

    }

    return handler

}


// RefreshToken is the main handler.

func RefreshToken(res http.ResponseWriter, req *http.Request) {

    res.Write([]byte("hello world"))

}


// ValidateRefreshToken is the middleware.

func ValidateRefreshToken(hKey string) Adapter {

    return func(next http.Handler) http.Handler {

        return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {

            // Check if a header key exists and has a value

            if value := req.Header.Get(hKey); value == "" {

                res.WriteHeader(http.StatusForbidden)

                res.Write([]byte("invalid request token"))

                return

            }


            // Serve the next handler

            next.ServeHTTP(res, req)

        })

    }

}


// MethodLogger logs the method of the request.

func MethodLogger() Adapter {

    return func(next http.Handler) http.Handler {

        return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {

            log.Printf("method=%s uri=%s\n", req.Method, req.RequestURI)

            next.ServeHTTP(res, req)

        })

    }

}


func main() {

    sm := mux.NewRouter()

    getR := sm.Methods(http.MethodGet).Subrouter()

    getR.HandleFunc("/refresh-token", Adapt(

        http.HandlerFunc(RefreshToken),

        MethodLogger(),

        ValidateRefreshToken("Vikee-Request-Token"),

    ).ServeHTTP)


    srv := &http.Server{

        Handler:      sm,

        Addr:         "localhost:8888",

        WriteTimeout: 30 * time.Second,

        ReadTimeout:  30 * time.Second,

    }

    log.Fatalln(srv.ListenAndServe())

}

該Adapt函數允許您將多個處理程序鏈接在一起。我已經演示了 2 個中間件函數(ValidateRefreshToken和MethodLogger)。中間件基本上是閉包。您可以將此方法與任何接受http.Handler諸如mux和的框架一起使用chi。


查看完整回答
反對 回復 2022-07-11
  • 2 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號