将中间件与Golang Gorilla Mux子路由器一起使用 [英] Using middleware with Golang Gorilla mux subrouters

查看:92
本文介绍了将中间件与Golang Gorilla Mux子路由器一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将中间件应用于Go Gorilla Toolkit 多路复用子路由器?

How can I apply middleware to a Go Gorilla Toolkit mux subrouter?

我有以下代码:

router := mux.NewRouter().StrictSlash(true)
apiRouter := router.PathPrefix("/api/").Subrouter()

apiRouter.Methods(http.MethodGet).
    Path("/api/path/to/handler").Handler(handleAPICall)

我想应用一个中间件处理程序来检查安全性令牌,但只能在以/api开头的路径上使用.

I want to apply a middleware handler that checks a security token, but only on those paths that start with /api.

推荐答案

以下似乎有效:

apiRouter := mux.NewRouter()

router.PathPrefix("/api/").Handler(http.StripPrefix("/api",
    adapt(apiRouter, checkTokenHandler)))

apiRouter.Methods(http.MethodGet).
    Path("/path/to/handler").Handler(handleAPICall)
// Note that `/api` has been removed from the path.

其中

func adapt(h http.Handler, adapters ...func(http.Handler) http.Handler)
    http.Handler {
    for _, adapter := range adapters {
        h = adapter(h)
    }
    return h
}

func checkTokenHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        // Check the security cookie.
        h.ServeHTTP(res, req)
    })
}

这篇关于将中间件与Golang Gorilla Mux子路由器一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆