I'm trying to retrieve int data from POST requisitions with Gin, but I'm getting an error saying that the functions (PostForm, or any other) expects strings as arguments. I've tried to search for a function expecting int content, but with no success. I have a struct do define the content, see the code below.
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,
})
}
I was thinking in converting the value to int, but if I have 10 inputs this becomes very difficult and impractible.
The error from user.Age:
cannot use c.PostForm("age") (value of type string) as int value in assignmentcompiler
After a lot of source code reading, I finally found out that all you need is to add a 'form' tag on the required field:
Age int `form:"age"`
user strconv.Atoi(c.PostForm("age"))
complete code:
Person:
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)
})

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With