gpt4 book ai didi

go - negroni 中不同路由的不同中间件

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:43 26 4
gpt4 key购买 nike

我想为不同的路径使用不同的中间件。我当前的实现来自这个 link

UserRouter := mux.NewRouter().StrictSlash(true)
AdminRouter := mux.NewRouter().StrictSlash(true)

Router.HandleFunc("/apps/{app_name}/xyz", Handler).Methods("GET")

我创建了三个不同的路由器,以便我可以将它们与不同的路径和中间件相关联

nUserPath := negroni.New(middleware.NewAuthMiddleWare())
nUserPath.UseHandler(UserRouter)

nAdminPath := negroni.New()
nAdminPath.UseHandler(AdminRouter)

我创建了两个不同的 negroni 实例并将它们传递给各自的路由器。因为我希望所有这些都在同一个端口上运行同一个应用程序的一部分,所以我创建了一个 Wrapper Router 和 negroni 实例并将它们与现有的相关联,如下所示

BaseRouter := mux.NewRouter().StrictSlash(true)
BaseRouter.Handle(UserBasePath,nUserPath) // UserBasePath is `/apps`
BaseRouter.Handle(HealthCheck,nUserPath) // HealthCheck is `/health`
BaseRouter.Handle(AdminBasePath,nAdminPath) // AdminBasePath is `/Admin`

n := negroni.New(middleware.NewLogger()) // attached other common middleware here
n.UseHandler(router.BaseRouter)
n.Run(":8080")

这种方法面临的问题:
当我运行 /health 它运行正常但是当我运行 /apps/{app_name}/something 我得到一个 404: Not Found/p>

注意:我经历了下面链接中提到的其他方法,但它们不能满足我的需要。

- Route-specific Middlewares with Negroni

最佳答案

因此,上述实现的问题在于 BaseRouter.Handle() 方法采用路径 而不是path_matcher/template 所以所有具有 path_length 的 url多于一个不工作。

我想出了两种方法来实现我所需要的:
第一种方法

// Create a rootRouter
var rootRouter *mux.Router = mux.NewRouter()

// Create as many subRouter you want with some prefix
var appsBasePath string = "/apps"
var adminBasePath string = "/admin"
upRouter := rootRouter.PathPrefix(appsBasePath).Subrouter()
apRouter := rootRouter.PathPrefix(adminBasePath).Subrouter()

// Register all the paths and mention middleware specifically for all of them
// Here middleware is a method with signature as
// func middleware( http.Handler) http.HandlerFunc {}

upRouter.Path("/test").Methods("POST").Handler(middleware(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request){
fmt.Fprintf(w, "Welcome to the home page!")
})))

n := negroni.New(middleware.NewLogger()) // attached other common middleware here
n.UseHandler(rootRouter)
n.Run(":8080")

第二种方法
这是问题中原始问题的扩展/解决方案

// Replace BaseRouter.handle() as below
// as PathPrefix takes a template so it won't have issue that we were facing

BaseRouter.PathPrefix(UserBasePath).Handler(nUserPath)

这里要记住的是,在 negroni nUserPath 中,附加的中间件的 RequestContext 将与实际路由器的 HandlerMethod 不同

注意:
通过路径长度,我的意思是这样的 -/abc 或/abc/有 path_length=1 和/abc/xyz 有 path_length=2

关于go - negroni 中不同路由的不同中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com