Gin: Bind JSON and URI

Created on 24 Mar 2019  路  4Comments  路  Source: gin-gonic/gin

Description

I'm trying to bind JSON and a URI in one request but havn't found out how to yet.

Here's my struct:

type ResetPassword struct {
    Code     string `uri:"code" binding:"required"`
    Password string `json:"password" binding:"required,min=6,max=20"`
}

I'm using c.Bind():

func verifyPasswordReset(c *gin.Context) {
    var data ResetPassword
    if err := c.Bind(&data); err != nil {
        c.JSON(400, gin.H{"error": err})
        return
    }
    fmt.Printf("%+v\n", data)
    c.JSON(http.StatusOK, data)
}

When I make this request it says the code is required:

curl -H "content-type:application/json" -d '{"password":"hunter15"}' "localhost:8080/user/password_reset/jksakhdkh"                                                                     Sun Mar 24 14:29:27 2019
{"error":{".Code":{"FieldNamespace":".Code","NameNamespace":"Code","Field":"Code","Name":"Code","Tag":"required","ActualTag":"required","Kind":24,"Type":{},"Param":"","Value":""}}}

I found a related issue #811 but it wasn't actually solved before being closed.

Most helpful comment

@thinkerou Why not use the uri and form tag together? I think it would be convenient.

All 4 comments

you should split bind uri and json to two struct.

@thinkerou ok, I split it into two structs and used the respective binds:

    if err := c.ShouldBindUri(&dataURI); err != nil {
        c.JSON(400, gin.H{"error": err})
        return
    }

    if err := c.ShouldBindJSON(&dataJSON); err != nil {
        c.JSON(400, gin.H{"error": err})
        return
    }

That works fine and removes my workaround of using c.Params.ByName("code"), thanks!

@thinkerou Why not use the uri and form tag together? I think it would be convenient.

no, I want to use it in one struct

Was this page helpful?
0 / 5 - 0 ratings