Skip to content

Instantly share code, notes, and snippets.

@tnolet
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnolet/dde204cc8abb6996e8fe to your computer and use it in GitHub Desktop.
Save tnolet/dde204cc8abb6996e8fe to your computer and use it in GitHub Desktop.
testing gin deep struct checking
save this as main.go
###
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
type Item struct {
RequiredField int `json:"required_field" binding:"required"`
OptionalField string `json:"optional_field"`
}
type Test struct {
Collection []*Item `json"collection" binding:"required"`
RequiredField int `json:"required_field"`
OptionalField struct {
RequiredSubField string `json:"required_sub_field" binding:"required"`
OptionalSubField string `json:"optional_sub_field"`
} `json:"optional_field"`
}
r := gin.Default()
r.POST("/test", func(c *gin.Context) {
var test Test
if c.Bind(&test) {
c.String(http.StatusOK, "JSON OK")
} else {
c.String(http.StatusInternalServerError, "JSON NOTOK")
}
})
r.Run(":9001")
}
###
then run it: go run main.go
then post this json to http://localhost:9001/test
{
"required_field": 10,
"optional_field": {
"required_sub_field" : "hi",
"optional_sub_field": "more"
},
"collection" : [
{
"optional_field" : "test"
}
]
}
It wil return a message saying the JSON is OK, while it is not.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment