Last active
August 29, 2015 14:17
-
-
Save tnolet/dde204cc8abb6996e8fe to your computer and use it in GitHub Desktop.
testing gin deep struct checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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