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

标签 go middleware negroni

我想为不同的路径使用不同的中间件。我当前的实现来自这个 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/

相关文章:

json - 我如何在 Go 中解析 JSON?

go - 如何在范围内的Golang模板中显示变量

go - 我可以将我的功能用作 `negroni` 中间件吗

python - 如果我在中间件中设置一个变量,如何使其可用于views.py 中的 View ?

go - 用于公共(public)和私有(private)路由中间件的 httprouter 和 negroni

go - 在 Negroni 下找不到路由时提供索引文件

go - 有没有一种方法可以将fmt.Scan()函数与一行消息一起使用?

postgresql - 我应该如何在 Postgres 中存储 Go 的 time.Location?

python - 扩展 session 中间件

http - 从外部 Go 中间件控制 HTTP header