英文:
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
你可以编写一个函数,具有以下特点:
- 具有类型为
func
的输入参数,其签名与你的GetUsers
函数的签名匹配。 - 具有类型为
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:
- Has an input parameter of type
func
, with signature matching yourGetUsers
' signature. - 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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论