在negroni中为不同的路由使用不同的中间件。

huangapple go评论82阅读模式
英文:

Different middleware for different routes in negroni

问题

我想为不同的路径使用不同的中间件。我目前的实现是参考这个链接

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实例,并将它们传递给相应的路由器。由于我希望所有这些都在同一个应用程序的同一个端口上运行,所以我创建了一个包装路由器和negroni实例,并将它们与现有的关联起来,如下所示。

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

n := negroni.New(middleware.NewLogger()) // 在这里附加其他常用的中间件
n.UseHandler(router.BaseRouter)
n.Run(":8080")

在这种方法中遇到的问题是:
当我访问/health时,它可以正常运行,但是当我访问/apps/{app_name}/something时,我得到一个404: Not Found的错误。

注意:我阅读了下面链接中提到的其他方法,但它们不满足我的需求。

英文:

I want to have different middleware for different path. My current implementation is from this link

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

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

I created three different routers, so that I can assosiate them with different path and middleware

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

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

I created two different negroni instances and passed them the respective routers. As I wanted all this to run part of the same application on the same port so I created a Wrapper Router and negroni instance and associated them with the existing like below

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")

Issues faced in this approach:
When I run /health it runs properly but when I run /apps/{app_name}/something I get a 404: Not Found

Note : I went through other approaches mentioned in below link but they don't satisfy my need.

答案1

得分: 0

所以,上述实现的问题在于BaseRouter.Handle()方法接受一个路径(path)而不是路径匹配器/模板(path_matcher/template),所以所有路径长度大于1的URL都无法正常工作。

我找到了两种实现我所需的方法:
第一种方法

// 创建一个根路由器
var rootRouter *mux.Router = mux.NewRouter()

// 创建任意数量的子路由器,并指定前缀
var appsBasePath string = "/apps"
var adminBasePath string = "/admin"
upRouter := rootRouter.PathPrefix(appsBasePath).Subrouter()
apRouter := rootRouter.PathPrefix(adminBasePath).Subrouter()

// 注册所有路径,并为每个路径指定特定的中间件
// 这里的中间件是一个具有以下签名的方法:
// 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, "欢迎访问首页!")
})))

n := negroni.New(middleware.NewLogger()) // 在这里添加其他常见的中间件
n.UseHandler(rootRouter)
n.Run(":8080")

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

// 将BaseRouter.handle()替换为以下内容
// 因为PathPrefix接受一个模板,所以不会出现我们之前遇到的问题

BaseRouter.PathPrefix(UserBasePath).Handler(nUserPath)

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

注意:
通过路径长度,我指的是像这样的路径-- /abc或/abc/ 的路径长度为1,/abc/xyz 的路径长度为2。

英文:

So, the issue with the above implementation is that BaseRouter.Handle() method take a path and not a path_matcher/template so all the url's which has path_length more than one were not working.

I figured out two ways to achieve what I needed:
First approach

// 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")

Second approach
This is extension/solution of the original issue in the question

// 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)  

Thing to remember here is that within negroni nUserPath RequestContext of the middleware attached will be different from that of the actual router's HandlerMethod

Note:
By path length I mean something like this -- /abc or /abc/ has path_length=1 and /abc/xyz has path_length=2

huangapple
  • 本文由 发表于 2016年2月22日 14:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/35547051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定