您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将中间件与Golang Gorilla Mux子路由器一起使用

将中间件与Golang Gorilla Mux子路由器一起使用

以下似乎有效:

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)
    })
}
Go 2022/1/1 18:14:40 有617人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶