How to exclude specific route from middleware in go-chi

huangapple go评论75阅读模式
英文:

How to exclude specific route from middleware in go-chi

问题

我一直在使用go-chi进行一个项目,并在路由中使用了一个身份验证中间件,像这样:

r := chi.NewRouter()
r.Use(authService.AuthMiddleware)

r.Route("/platform", func(r chi.Router) {
    r.Get("/version", RequestPlatformVersion)
})

这个中间件应用于在此声明之后定义的所有路由,这是可以的。但现在我需要添加一个用于Webhooks的路由。我不想将这个中间件应用于该路由,因为它会失败。我该如何做到这一点?

英文:

I've been using go-chi for a project and using an auth middleware for routes like this

r := chi.NewRouter()
r.Use(authService.AuthMiddleware)

r.Route("/platform", func(r chi.Router) {
	r.Get("/version", RequestPlatformVersion)
})

This is applying to all the routes defined after this declaration which are fine.
But now I need to add a route that is used for webhooks. I don't want to apply this middleware to that route since it'll fail. How can I do that?

答案1

得分: 2

你可以在/platform路由中设置中间件:

r.Route("/platform", func(r chi.Router) {
    r.Use(authService.AuthMiddleware)
    r.Get("/version", RequestPlatformVersion)
})

r.Route("/webhooks", func(r chi.Router) {
    r.Get("/", ...)
})

请注意,这只是代码的翻译部分,不包括其他内容。

英文:

You can set the middleware within the /platform route:

r.Route("/platform", func(r chi.Router) {
    r.Use(authService.AuthMiddleware)
    r.Get("/version", RequestPlatformVersion)
})

r.Route("/webhooks", func(r chi.Router) {
    r.Get("/", ...)
})

huangapple
  • 本文由 发表于 2021年12月27日 16:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70493054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定