Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Gin retrieve integer data

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
like image 684
Vinicius Mocci Avatar asked Feb 28 '26 07:02

Vinicius Mocci


2 Answers

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"`
like image 166
hugh lu Avatar answered Mar 02 '26 20:03

hugh lu


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)

})

hit the API

like image 25
Muhammad Iqbal Ali Avatar answered Mar 02 '26 21:03

Muhammad Iqbal Ali



Donate For Us

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