douyue2313 2016-02-22 06:25
浏览 46
已采纳

Negroni中不同路线的不同中间件

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.

- Route-specific Middlewares with Negroni

  • 写回答

1条回答 默认 最新

  • duanjia9577 2016-02-23 12:39
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?