Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 247 Vote(s) - 3.67 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Golang Gin retrieve integer data

#1
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
Reply

#2
user `strconv.Atoi(c.PostForm("age"))`

complete code:

Person:
```go
type Person struct {
Name string
Age int
}
```

```go
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][1]][1]


[1]:
Reply

#3
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"`
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through