对于不同的路径,我希望有不同的中间件。我当前的实现来自于这个链接
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 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
注意:我通过了下面链接中提到的其他方法,但它们不能满足我的需要。
发布于 2016-02-23 12:39:01
因此,上述实现的问题在于,BaseRouter.Handle()方法采用的是路径,而不是路径,因此所有具有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/ has path_length=1和/abc/xyz有path_length=2
https://stackoverflow.com/questions/35547051
复制相似问题