dousi7579 2014-08-14 01:21
浏览 75
已采纳

如何在Goji(Golang)中使用不同的中间件创建单独的路由组?

I am using Goji (https://github.com/zenazn/goji) and would like to define groups of routes that have their own middleware. For example, all paths under /company should use an LDAP authentication and have a middleware defined to do this. All paths under /external use a different type of authentication so they have a different middleware definition. But this is a single application served on the same port, so I don't want to create separate web services altogether -- just the paths (and some specific routes) may use different middleware.

All the examples I've seen with Goji are using a single set of middleware for all routes, so I am not sure how to accomplish this in a clean way. Additionally it would be nice if I could specify a base path for all routes within a route group, similar to how I've seen in some other routing frameworks.

Am I missing this functionality in the Goji library (or net/http by extension) that allows me to group routes together and have each group use its own middleware stack?

What I would like to achieve is something like this (psedocode):

// Use an LDAP authenticator for:
// GET /company/employees
// and
// POST /company/records
companyGroup = &RouteGroup{"basePath": "/company"}
companyGroup.Use(LDAPAuthenticator)
companyGroup.Add(goji.Get("/employees", Employees.ListAll))
companyGroup.Add(goji.Post("/records", Records.Create))

// Use a special external user authenticator for: GET /external/products
externalGroup = &RouteGroup{"basePath": "/external"}
externalGroup.Use(ExternalUserAuthenticator)
externalGroup.Add(goji.Get("/products", Products.ListAll))
  • 写回答

3条回答 默认 最新

  • dongmu1914 2014-08-14 01:29
    关注

    You should be able to solve your problem with something like this:

    // Use an LDAP authenticator 
    companyGroup := web.New()
    companyGroup.Use(LDAPAuthenticator)
    companyGroup.Get("/company/employees", Employees.ListAll)
    companyGroup.Post("/company/records", Records.Create)
    goji.Handle("/company/*", companyGroup)
    
    // Use a special external user authenticator for: GET /external/products
    externalGroup := web.New()
    externalGroup.Use(ExternalUserAuthenticator)
    externalGroup.Get("/external/products", Products.ListAll)
    goji.Handle("/external/*", externalGroup)
    

    You need to give each group its own web. Just keep in mind you need to specify the full path within the group members.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下