Created
March 19, 2019 10:02
-
-
Save hugows/01e6ed085f6d2a6e94f00e0c4fe1858c to your computer and use it in GitHub Desktop.
gojsonschema and echo
This file contains hidden or 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
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