使用Gin中间件访问路由

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

Accessing route in middleware using Gin

问题

我有一个在我的 Golang API 中的 user.save 路由(如下所示),可以根据请求对象中是否提供了 id 来进行用户的 创建更新。该路由使用了 auth 中间件,其他路由也使用了该中间件。

  1. api.POST("/user.save", auth(), user.Save())
  2. api.POST("/user.somethingElse", auth(), user.SomethingElse())

这是我的中间件:

  1. func auth() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. // 我想在这里知道是否调用了 user.save 路由
  4. // 进行身份验证操作
  5. }
  6. }

我在考虑,如果我能在 auth 中间件中检测到是否调用了 user.save 路由,那么我就可以检查是否包含了 id,并决定是继续执行还是返回。

英文:

I have a user.save route (below) in my Golang API that can be used to create and update a user depending on whether an id was provided in the request object. The route uses the auth middleware which other routes do too.

  1. api.POST("/user.save", auth(), user.Save())
  2. api.POST("/user.somethingElse", auth(), user.SomethingElse())

Here is my middleware:

  1. func auth() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. //I would like to know here if user.save was the route called
  4. //do authy stuff
  5. }
  6. }

I'm thinking that if I can detect in the auth middleware whether the user.save route was called I can then check to see if an id was included and decide whether to continue or return.

答案1

得分: 8

你可以从授权处理程序中检查URL。实际请求在上下文中,所以很容易实现:

  1. if c.Request.URL.Path == "/user.save" {
  2. // 做你的事情
  3. }

另一种解决方案是将授权中间件参数化,类似于这样:

  1. api.POST("/user.save", auth(true), user.Save())
  2. api.POST("/user.somethingElse", auth(false), user.SomethingElse())
  3. func auth(isUserSave bool) gin.HandlerFunc {
  4. return func(c *gin.Context) {
  5. if isUserSave {
  6. // 做你的事情
  7. }
  8. }
  9. }
英文:

You could check the url from the auth handler. The actual request is on the context, so it's as easy as:

  1. if c.Request.URL.Path == "/user.save" {
  2. // Do your thing
  3. }

Another solution is to parameterize your auth middleware, something like this:

  1. api.POST("/user.save", auth(true), user.Save())
  2. api.POST("/user.somethingElse", auth(false), user.SomethingElse())
  3. func auth(isUserSave bool) gin.HandlerFunc {
  4. return func(c *gin.Context) {
  5. if isUserSave {
  6. // Do your thing
  7. }
  8. }
  9. }

huangapple
  • 本文由 发表于 2015年12月24日 00:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/34440246.html
匿名

发表评论

匿名网友

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

确定