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
- 1 回答
- 0 關注
- 196 瀏覽
添加回答
舉報