Unable to access json data from request in request handler after calling BindJSON in middleware

170 Views Asked by At

I have created a basic CRUD API using Go-Gin. Calling BindJSON in request handler gives me a blank object after calling BindJSON in middleware but works fine if I remove BindJSON in middleware.

This is the user model:

type User struct {
    ID      uint   `json:"id" gorm:"primary_key"`
    Rollnum string `json:"rollnum" gorm:"primary_key;unique"`
    Name    string `json:"name"`
    Email   string `json:"email"`
    Phone   uint   `json:"phone"`
    Address string `json:"address"`
}

This is my middleware:

func NameMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        var user Models.User
        c.BindJSON(&user)
        fmt.Println(user.Rollnum)
        if user.Name == "" {
            c.JSON(http.StatusNotFound, gin.H{"No Key": "Name"})
            c.AbortWithStatus(http.StatusNotFound)
        }
    }
}

This is my route:

r := gin.Default()
grp1 := r.Group("/user-api")
grp1.POST("user", Middleware.NameMiddleware(), Controllers.CreateUser)

And this is my handler for the POST request:

func CreateUser(c *gin.Context) {
    var user Models.User
    c.BindJSON(&user)

    fmt.Println(user)

    err := Models.CreateUser(&user)
    return
}

Works fine if the BindJSON in middleware is removed. Is it possible that you can only BindJSON once? What should I do to get that object again in my request handler?

1

There are 1 best solutions below

0
Erkin Djindjiev On

The c.bindJSON() is intended to be used in the initial request handler and not in the middleware. If you want, you can pass data to your middleware using context https://www.nicolasmerouze.com/share-values-between-middlewares-context-golang but I think this can get ugly quik.

If you just want to perform validation on the JSON, I'd recommend performing this logic in your handler and not the middleware.