Is there anyway to auto convert base type? such as string to int64 int32... in fact, this problem easy implemently?
Comment From: zihengCat
@ChannelCook
The implementation of ShouldBindJSON
is handled by standard library encoding/json
(or compatible third party jsoniter
if user enabled it), so the behavior is the same as standard library.
Comment From: zihengCat
@ChannelCook
I give you a quick example here. You can see Count
field is auto converted from string
to int
handled by standard library.
Example Code Snippet
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// Binding from JSON
type Product struct {
Name string `json:"name"`
Count int `json:"count,string"` // auto convert from string to int
}
func main() {
router := gin.Default()
router.POST("/product", func(c *gin.Context) {
var p Product
if err := c.ShouldBindJSON(&p); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
fmt.Println("Name:", p.Name)
fmt.Println("Count:", p.Count) // already converted
c.JSON(http.StatusOK, gin.H{"message": "Ok"})
})
router.Run(":8080")
}
Test Scripts
curl -X POST -v \
--header "Content-Type: application/json" \
--data '{"name": "abc", "count": "123"}' \
http://localhost:8080/product
Result
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST /product --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080
Name: abc
Count: 123
[GIN] 2021/07/14 - 11:58:09 | 200 | 267.736µs | ::1 | POST "/product"
Comment From: ChannelCook
Great!!!
Comment From: timsegraves
You just saved me hours. Been fighting this for a while now.