Search code examples
javascriptreactjsgohandlergo-gin

Passing the handler in route group without creating condition


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

}


Solution

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