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

标签 go goji

我正在使用 Goji ( https://github.com/zenazn/goji ) 并希望定义具有自己的中间件的路由组。例如,/company 下的所有路径都应使用 LDAP 身份验证并定义一个中间件来执行此操作。 /external 下的所有路径都使用不同类型的身份验证,因此它们具有不同的中间件定义。但这是在同一端口上提供服务的单个应用程序,所以我不想完全创建单独的 Web 服务——只是路径(和一些特定的路由)可能使用不同的中间件。

我在 Goji 上看到的所有示例都对所有路由使用一组中间件,因此我不确定如何以干净的方式完成此操作。此外,如果我可以为路由组中的所有路由指定一个基本路径,那就太好了,就像我在其他一些路由框架中看到的那样。

我是否缺少 Goji 库(或 net/http 的扩展名)中允许我将路由组合在一起并让每个组使用自己的中间件堆栈的功能?

我想实现的是这样的(伪代码):

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

最佳答案

你应该能够用这样的方法解决你的问题:

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

您需要为每个组提供自己的web。请记住,您需要在组成员中指定完整路径。

关于go - 如何在 Goji (Golang) 中使用不同的中间件创建单独的路由组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25298646/

相关文章:

go - 如何使用 go-client 在 kubernetes 中获取 pod 的状态

go - 如何用golang获取USB设备的序列号?

json - 将 colly 包输出文本添加到 golang 中的映射

timer - 如何从 Web 服务器重启(或代码刷新/升级)中恢复 Go 计时器?

go - 在 Goji 中映射所有路由及其 http 方法

https - 戈朗 : Right way to serve both http & https from Go web app with Goji?

Goji 子路由器返回 404

json - Go json.Unmarshal 字段案例

java - Go 和 Java 在接口(interface)方面有什么区别?

Golang 枸杞 : How to serve static content and api at the same time