繁体   English   中英

Golang Gin 检索 integer 数据

[英]Golang Gin retrieve integer data

我正在尝试使用 Gin 从 POST 申请中检索 int 数据,但我收到一条错误消息,指出函数(PostForm 或任何其他)期望字符串为 arguments。 我试图搜索期望 int 内容的 function ,但没有成功。 我有一个结构来定义内容,请参见下面的代码。

package userInfo

import(
    "net/http"
    "github.com/gin-gonic/gin"
)

type Person struct {
    Name string
    Age int
}

func ReturnPostContent(c *gin.Context){
    var user Person
    user.Name = c.PostForm("name")
    user.Age = c.PostForm("age")    
    c.JSON(http.StatusOK, gin.H{        
        "user_name": user.Name,
        "user_age": user.Age,       
    })
}

我正在考虑将值转换为 int,但如果我有 10 个输入,这将变得非常困难且不切实际。

来自 user.Age 的错误:

cannot use c.PostForm("age") (value of type string) as int value in assignmentcompiler

用户strconv.Atoi(c.PostForm("age"))

完整代码:

人:

type Person struct {
    Name string
    Age  int
}
r.POST("/profile", func(c *gin.Context) {
    profile := new(Person)

    profile.Name = c.PostForm("name")
    profile.Age, _ = strconv.Atoi(c.PostForm("age"))

    response := gin.H{
        "user_name": profile.Name,
        "user_age":  profile.Age,
    }
    
    c.JSON(http.StatusOK, response)

})

打API

经过大量的源代码修改,最后我发现你只需要在必填字段上添加一个'form'标签。

Age int `form:"age"`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM