项目作者: Hepri

项目描述 :
Gin jsonschema validation
高级语言: Go
项目地址: git://github.com/Hepri/gin-jsonschema.git
创建时间: 2017-06-06T23:43:22Z
项目社区:https://github.com/Hepri/gin-jsonschema

开源协议:MIT License

下载


gin-jsonschema: JSON Schema validation wrapper for Gin Build Status

Installation

  1. go get github.com/Hepri/gin-jsonschema

Dependencies :

Usage

  1. var testSchema string = `
  2. {
  3. "title": "Test Schema",
  4. "type": "object",
  5. "properties": {
  6. "value": {
  7. "type": "integer"
  8. }
  9. },
  10. "required": ["value"]
  11. }
  12. `
  13. type TestBody struct {
  14. Value int `json:"value"`
  15. }
  16. // using BindJSON
  17. r.POST("/bind", func(c *gin.Context) {
  18. var js TestBody
  19. if schema.BindJSON(c, testSchema, &js) == nil {
  20. // do stuff
  21. }
  22. })
  23. // validate using schema as string
  24. r.POST("/string", schema.Validate(handlerFunc, testSchema))
  25. // validate using schema as *gojsonschema.Schema
  26. loader := gojsonschema.NewStringLoader(testSchema)
  27. sc, _ := gojsonschema.NewSchema(loader)
  28. r.POST("/schema", schema.ValidateSchema(handlerFunc, sc))
  29. // using wrapper inside handler
  30. var someHandler = func(c *gin.Context) {
  31. return schema.Validate(func (c *gin.Context) {
  32. c.JSON(http.StatusOK, gin.H{
  33. "message": "OK",
  34. })
  35. }, testSchema)
  36. }
  37. r.POST("/wrap_inside", someHandler)

Read possible ways to build *gojsonschema.Schema in documentation

Example HTTP Service

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. "github.com/Hepri/gin-jsonschema"
  6. )
  7. var testSchema string = `
  8. {
  9. "title": "Test Schema",
  10. "type": "object",
  11. "properties": {
  12. "value": {
  13. "type": "integer"
  14. }
  15. },
  16. "required": ["value"]
  17. }
  18. `
  19. type testBody struct {
  20. Value int `json:"value"`
  21. }
  22. func handlerFunc(c *gin.Context) {
  23. c.Status(http.StatusOK)
  24. }
  25. func bindJSONHandler(c *gin.Context) {
  26. var js testBody
  27. if schema.BindJSON(c, testSchema, &js) == nil {
  28. c.JSON(http.StatusOK, gin.H{
  29. "value": js.Value,
  30. })
  31. }
  32. }
  33. func main() {
  34. r := gin.Default()
  35. // wrap handler, all invalid json schema requests will produce Bad Request
  36. r.POST("/validate", schema.Validate(handlerFunc, testSchema))
  37. // use BindJSON inside handler
  38. r.POST("/bind", bindJSONHandler)
  39. r.Run(":8080")
  40. }