在不创建条件的情况下,在路由组中传递处理程序。

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

Passing the handler in route group without creating condition

问题

我想创建一个路由组,其中只能传递“repo.GetUsers”,而不需要创建if语句,以简化代码。

我正在练习一个CRUD应用程序,如果有人能帮我解决这个问题,那将是非常大的帮助。

上面的代码是我使用的代码,它可以工作,但我希望它只变成这样:

func (repo *Repository) SetupRoutes(app *gin.Engine) {

	api := app.Group("/api")

	{
		api.GET("/users", repo.GetUsers)
	}

}
英文:

I wanted to create a route group wherein I can only passed the "repo.GetUsers" only and not create an if statement, for simplicity.

I'm practicing a crud application and if someone can help me solve this, then it would be a really big help.

package repository

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func (repo *Repository) SetupRoutes(app *gin.Engine) {

	api := app.Group("/api")

	{
		api.GET("/users", func(ctx *gin.Context) {
			err := repo.GetUsers(ctx)

			if err != nil {
				// Handle the error, if needed
				ctx.IndentedJSON(http.StatusInternalServerError, gin.H{
					"data":    err.Error(),
					"message": "failed to get users",
					"success": false,
				})

				return

			}
		})
	}

}

The code above is the code that I used and it works, but I wanted it to only become like this:

func (repo *Repository) SetupRoutes(app *gin.Engine) {

	api := app.Group("/api")

	{
		api.GET("/users", repo.GetUsers)
	}

}

答案1

得分: 2

你可以编写一个函数,具有以下特点:

  1. 具有类型为func的输入参数,其签名与你的GetUsers函数的签名匹配。
  2. 具有类型为func的返回参数,其签名与gin处理程序函数的签名匹配。
func gh(h func(*gin.Context) error) (g func(*gin.Context)) {
    return func(c *gin.Context) {
        if err := h(c); err != nil {
            // 处理错误,如果需要的话
            c.IndentedJSON(http.StatusInternalServerError, gin.H{
                "data":    err.Error(),
                "message": "获取用户失败",
                "success": false,
            })
            return
        }
    }
}

然后你可以这样做:

api.GET("/users", gh(repo.GetUsers))
英文:

You can write a function that:

  1. Has an input parameter of type func, with signature matching your GetUsers' signature.
  2. Has a return parameter of type func, with signature that matches the gin handler func's signature.
func gh(h func(*gin.Context) error) (g func(*gin.Context)) {
    return func(c *gin.Context) {
        if err := h(c); err != nil {
            // Handle the error, if needed
            c.IndentedJSON(http.StatusInternalServerError, gin.H{
                "data":    err.Error(),
                "message": "failed to get users",
                "success": false,
            })
            return
        }
    }
}

Then you can do:

api.GET("/users", gh(repo.GetUsers))

huangapple
  • 本文由 发表于 2023年6月20日 20:48:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76514886.html
匿名

发表评论

匿名网友

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

确定