Home > other >  Gin - struct param is validated as null
Gin - struct param is validated as null

Time:08-05

I have a function here to create post requests and add a new user of type struct into a slice (the data for the API is just running in memory, so therefore no database):

type user struct {
    ID        string `json:"id"`
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
    Email     string `json:"email"`
}

var users = []user{
    {ID: "1", FirstName: "John", LastName: "Doe", Email: "[email protected]"},
}

func createUser(c *gin.Context) {

    var newUser user

    if len(newUser.ID) == 0 {
        c.JSON(http.StatusBadRequest, gin.H{"message": "user id is null"})
        return
    }

    users = append(users, newUser)
    c.JSON(http.StatusCreated, newUser)
}

Eveything worked fine, until i tried to make an 'if statement' that checks if an id for a user being sent with a post request is null.

The problem is that the if statement returns true, when it should return false. So if i for example try to make a post request with the following data:

{
    "id": "2",
    "first_name": "Jane",
    "last_name": "Doe",
    "email": "[email protected]"
}

The if statement that checks for an id with the length of 0 will be true, and therefore return a StatusBadRequest. If have also tried this way:

if newUser.ID == "" {
}

But this also returns true when it shouldn't.

If i remove this check and create the POST request it works just fine, and the new added data will appear when i make a new GET request.

Why do these if statements return true?

CodePudding user response:

When you create a new user object with var newUser user statement, you are just creating an empty user object. You still have to bind the JSON string you are sending into that object. for that, what you need to do is: c.BindJSON(&newUser). full code will be like:

func createUser(c *gin.Context) {

    var newUser user
    err := c.BindJSON(&newUser)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    }

    if len(newUser.ID) == 0 {
        c.JSON(http.StatusBadRequest, gin.H{"message": "user id is null"})
        return
    }

    users = append(users, newUser)
    c.JSON(http.StatusCreated, newUser)
}

you can check this link for an example provided by Gin: https://github.com/gin-gonic/examples/blob/master/basic/main.go#L61

  •  Tags:  
  • go
  • Related