'GO storing data returns EOF

I'm new to golang and I'm trying to build rest api, So far GET endpoints are working for me fine, but I'm having difficulties with POST method(creating user):

That's how my User struct is looking:

type User struct {
    ID        uint32    `gorm:"primary_key;auto_increment" json:"id"`
    Name      string    `json:"name" binding:"required"`
    Email     string    `json:"email" binding:"required"`
    Password  string    `json:"password" binding:"required"`
    CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
    UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
}

Repo method for storing users:

func CreateUser() (*models.User, error) {

    var input models.User

    user := models.User{Name: input.Name, Email: input.Email, Password: input.Password}

    result := Config.DB.Debug().Create(&user)
    if result.Error != nil {
        msg := result.Error
        return nil, msg
    }
    return &user, nil
}

And called from controller:

func CreateUser(c *gin.Context) {

    //var user models.User
    user := models.User{}
    user.Prepare()

    var input models.User

    err := c.BindJSON(&input)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "Error": err.Error(), //this error is thrown
        })
        return
    }

    userData, err := repo.CreateUser()

    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "error": err,
        })
        return

    }
    c.JSON(http.StatusOK, gin.H{
        "data": userData,
    })
}

I'm using gorm to interact with database and if I'm hardcoding the inputs e.g.

 User{Name: "Jinzhu", Email: "[email protected]", Password: "pass1234"}

Then the data is stored, but if these are passed as parameters via postman, then I'm getting this error:

{"Error":"EOF"}

Been bashing my head for several hours now and still don't understand where's the error.



Solution 1:[1]

As mkopriva pointed

c.BindJSON is returning EOF which means nothing is being sent in request

To solve this you need json in request body which would look something like:

{name: "Jinzhu", email: "[email protected]", password: "pass1234"}

Example curl request:

curl -X POST localhost:8080 -H 'Content-Type: application/json' --data '{name: "Jinzhu", email: "[email protected]", password: "pass1234"}'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chandan