Golang Gin检索整数数据
我试图用Gin从POST requisions中检索int数据,但我得到一个错误,即函数(PostForm或任何其他函数)需要字符串作为参数。我试图搜索一个需要int内容的函数,但没有成功。 我有一个定义内容的结构,请参见下面的代码Golang Gin检索整数数据,go,frameworks,go-gin,strconv,Go,Frameworks,Go Gin,Strconv,我试图用Gin从POST requisions中检索int数据,但我得到一个错误,即函数(PostForm或任何其他函数)需要字符串作为参数。我试图搜索一个需要int内容的函数,但没有成功。 我有一个定义内容的结构,请参见下面的代码 package userInfo import( "net/http" "github.com/gin-gonic/gin" ) type Person struct { Name string
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个输入,这将变得非常困难和不可行
来自用户的错误。年龄:
cannot use c.PostForm("age") (value of type string) as int value in assignmentcompiler
用户strconv.Atoi(c.PostForm(“age”))
完整代码:
人:
type Person结构{
名称字符串
年龄智力
}
r.POST(“/profile”,func(c*gin.Context){
档案:=新(人)
profile.Name=c.PostForm(“Name”)
profile.Age,u=strconv.Atoi(c.PostForm(“Age”))
答复:=gin.H{
“用户名”:profile.name,
“用户年龄”:profile.age,
}
c、 JSON(http.StatusOK,响应)
})
使用
strconv.Atoi
将字符串转换为整数。我知道这一点,但如果输入太多,这可能是个问题,我想知道是否有更简单的方法使用Gin-Gonic获取int数据。我试着找它,但没找到。那么你可能在找这个:Tks老兄,为我工作!!