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 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数