Gin – 结构参数被验证为空。

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

Gin - struct param is validated as null

问题

我这里有一个函数,用于创建POST请求并将一个新的结构体用户添加到切片中(API的数据仅在内存中运行,因此没有数据库):

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: "john.doe@email.com"},
}

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

一切都运行正常,直到我尝试使用一个"if语句"来检查通过POST请求发送的用户的id是否为空。

问题在于,这个if语句返回true,而实际上应该返回false。例如,如果我尝试使用以下数据进行POST请求:

{
	"id": "2",
	"first_name": "Jane",
	"last_name": "Doe",
	"email": "jane.doe@email.com"
}

检查长度为0的id的if语句将返回true,因此返回一个StatusBadRequest。我还尝试了以下方式:

if newUser.ID == "" {
}

但是这也在不应该返回true的情况下返回了true。

如果我移除这个检查并创建POST请求,它就能正常工作,并且在进行新的GET请求时,新添加的数据将出现。

为什么这些if语句会返回true呢?

英文:

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: "john.doe@email.com"},
}

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": "jane.doe@email.com"
}

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?

答案1

得分: 1

当你使用var newUser user语句创建一个新的用户对象时,你只是创建了一个空的用户对象。你仍然需要将你发送的JSON字符串绑定到该对象中。为此,你需要执行c.BindJSON(&newUser)。完整的代码如下:

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

你可以查看Gin提供的示例链接以获取示例:https://github.com/gin-gonic/examples/blob/master/basic/main.go#L61

英文:

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

huangapple
  • 本文由 发表于 2022年8月4日 23:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/73238398.html
匿名

发表评论

匿名网友

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

确定