I hava a json from client post to server with string like
type MatSearch struct {
ID uint64 `json: "id"`
Customerid uint64 `json: "customerid"`
}
var matsearch MatSearch
c.Bind(&matsearch)
I need to convert string to uint64 by manual or any function to suppport auto convert string to other type data when bind with gin
You can use json.Number type for abstract “numberish” strings. It is json package's feature, not for gin.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.POST("/", func(c *gin.Context) {
f := struct {
Foo json.Number `json:"foo"`
}{}
if err := c.BindJSON(&f); err != nil {
return
}
bar, err := f.Foo.Int64()
if err != nil {
c.AbortWithStatusJSON(
http.StatusBadRequest,
gin.H{"error": err.Error()},
)
return
}
c.JSON(http.StatusOK, gin.H{"result": bar})
})
r.Run("0:8080")
}
$ curl -X POST --data '{"foo":"12345"}' 0:8080
{"result":12345}
$ curl -X POST --data '{"foo":"foobar"}' 0:8080
{"error":"strconv.ParseInt: parsing \"foobar\": invalid syntax"}
@thanhtungka91 please see @delphinus comment and still have problem please reopen it, thanks!
Most helpful comment
You can use
json.Numbertype for abstract “numberish” strings. It isjsonpackage's feature, not for gin.