如何解决Golang Gin 检索整数数据
我正在尝试使用 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(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)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。