GO存储数据返回EOF

huangapple go评论95阅读模式
英文:

GO storing data returns EOF

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是golang的新手,正在尝试构建REST API。到目前为止,GET端点对我来说运行良好,但是我在POST方法(创建用户)方面遇到了困难:

这是我的User结构体的样子:

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方法:

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
}

并从控制器调用:

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

我正在使用gorm与数据库进行交互,如果我硬编码输入,例如:

User{Name: "Jinzhu", Email: "test@mail.com", Password: "pass1234"}

那么数据会被存储,但是如果通过Postman传递这些参数,我会收到以下错误:

{"Error":"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: "test@mail.com", 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.

答案1

得分: 1

如mkopriva所指出

c.BindJSON 返回 EOF,这意味着请求中没有发送任何内容

要解决这个问题,你需要在请求体中包含 json,格式应该类似于:

{name: "Jinzhu", email: "test@mail.com", password: "pass1234"}

示例 curl 请求:

curl -X POST localhost:8080 -H 'Content-Type: application/json' --data '{name: "Jinzhu", email: "test@mail.com", password: "pass1234"}'
英文:

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: "test@mail.com", password: "pass1234"}

Example curl request:

curl -X POST localhost:8080 -H 'Content-Type: application/json' --data '{name: "Jinzhu", email: "test@mail.com", password: "pass1234"}'

huangapple
  • 本文由 发表于 2022年4月4日 20:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/71737403.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定