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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法