【问题标题】:Golang Gin retrieve integer dataGolang Gin 检索整数数据
【发布时间】:2021-04-05 21:20:18
【问题描述】:

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

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 将字符串转换为整数。
  • 我知道这一点,但是如果我输入太多,这可能是个问题,我想知道是否有更简单的方法来使用 Gin Gonic 获取 int 数据。我试过搜索它,但没有找到。
  • 那么你可能正在寻找这个:Bind Query String or Post Data
  • 谢谢老兄,为我工作!

标签: go frameworks go-gin strconv


【解决方案1】:

用户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)

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2018-05-12
    • 2022-01-27
    相关资源
    最近更新 更多