Add jsonschema Validate
This commit is contained in:
34
check_valid.go
Normal file
34
check_valid.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package commons
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
|
||||
"github.com/ianlancetaylor/jsonschema"
|
||||
"github.com/ianlancetaylor/jsonschema/draft7"
|
||||
)
|
||||
|
||||
func Validate(schema string, dataAny any) error {
|
||||
data := StructToMapRecursive(dataAny)
|
||||
|
||||
var v any
|
||||
if err := json.Unmarshal([]byte(schema), &v); err != nil {
|
||||
log.Printf("Failed to decode json %#v", err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
vldtor, err := jsonschema.SchemaFromJSON(draft7.SchemaID, nil, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// validate
|
||||
valid := vldtor.Validate(data)
|
||||
|
||||
if valid != nil {
|
||||
return valid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user