I sometimes use createTime (unix time) as the key for data segmentation. A common usage is that Service A is responsible for generating creatTime. Service B routes to the corresponding database table based on createTime in the data. It is found that gin does not currently support binding of unix time to time.Time type.
Pseudo code is as follows
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
type shareTime struct {
CreateTime time.Time `form:"createTime" time_format:"unixNano"`
UnixTime time.Time `form:"unixTime" time_format:"unix"`
}
func main() {
r := gin.Default()
unix := r.Group("/unix")
testCT := time.Date(2019, 7, 6, 16, 0, 33, 123, time.Local)
fmt.Printf("%d\n", testCT.UnixNano())
testUT := time.Date(2019, 7, 6, 16, 0, 33, 0, time.Local)
fmt.Printf("%d\n", testUT.Unix())
unix.GET("/nano", func(c *gin.Context) {
s := shareTime{}
c.ShouldBindQuery(&s)
if !testCT.Equal(s.CreateTime) {
c.String(500, "want %d got %d", testCT.UnixNano(), s.CreateTime)
return
}
c.JSON(200, s)
})
unix.GET("/sec", func(c *gin.Context) {
s := shareTime{}
c.ShouldBindQuery(&s)
if !testUT.Equal(s.UnixTime) {
c.String(500, "want %d got %d", testCT.Unix(), s.UnixTime)
return
}
c.JSON(200, s)
})
r.Run()
}
// client
//
// curl -X GET "127.0.0.1:8080/unix/sec?unixTime=1562400033"
// {"CreateTime":"0001-01-01T00:00:00Z","UnixTime":"2019-07-06T16:00:33+08:00"}
// curl -X GET "127.0.0.1:8080/unix/nano?createTime=1562400033000000123"
// {"CreateTime":"2019-07-06T16:00:33.000000123+08:00","UnixTime":"0001-01-01T00:00:00Z"}
Comment From: IsQiao
the feature can't bind requrest json body property. any solution about it?
Comment From: takanuva15
the feature can't bind requrest json body property. any solution about it?
json binding is handled separately from form binding used for query params. You can customize json binding by providing a custom implementation of binding.Binding
and then passing it to c.ShouldBindWith(obj, myCustomJsonBinding{})
. You can see gin's version of json binding here for reference