Gin: How to bin string data from Json to uint64

Created on 26 Apr 2018  ·  2Comments  ·  Source: gin-gonic/gin

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

Most helpful comment

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"}

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xpbliss picture xpbliss  ·  3Comments

iiinsomnia picture iiinsomnia  ·  3Comments

kekemuyu picture kekemuyu  ·  3Comments

mdnight picture mdnight  ·  3Comments

Bloomca picture Bloomca  ·  3Comments