Skip to content

Instantly share code, notes, and snippets.

@hugows
Created March 19, 2019 10:02
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 hugows/01e6ed085f6d2a6e94f00e0c4fe1858c to your computer and use it in GitHub Desktop.
Save hugows/01e6ed085f6d2a6e94f00e0c4fe1858c to your computer and use it in GitHub Desktop.
gojsonschema and echo
var mySchema = `{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"color": {
"description": "The price of the product",
"type": "string",
"enum": ["blue", "red", "black"],
"exclusiveMinimum": 0
}
},
"required": [ "color" ]
}`
func (s *Server) objCreate(c echo.Context) error {
schemaLoader := gojsonschema.NewStringLoader(consultaSchema)
reqBody := []byte{}
if c.Request().Body != nil { // Read
reqBody, _ = ioutil.ReadAll(c.Request().Body)
}
c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(reqBody)) // Reset
requestLoader := gojsonschema.NewBytesLoader(reqBody)
result, err := gojsonschema.Validate(schemaLoader, requestLoader)
if err != nil {
log.Println(err.Error())
}
if !result.Valid() {
validationResponse := map[string]string{}
for _, err := range result.Errors() {
validationResponse[err.String()] = err.Description()
}
return c.JSON(http.StatusBadRequest, validationResponse)
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment