本文整理汇总了Golang中github.com/xeipuuv/gojsonschema.Validate函数的典型用法代码示例。如果您正苦于以下问题:Golang Validate函数的具体用法?Golang Validate怎么用?Golang Validate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Validate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: evaluateBody
func (t *Test) evaluateBody() {
if !t.Response.BodyCheck {
return
}
if t.Response.BodyString != "" {
b := []byte(t.Response.BodyString)
if bytes.Equal(t.Response.body, b) {
return
}
t.fail(fmt.Errorf("expect response body to equal %q, given %q", t.Response.BodyString, t.Response.body))
} else if t.Response.BodyJsonSchema != nil {
var v interface{}
if err := json.Unmarshal(t.Response.body, &v); err != nil {
t.fail(fmt.Errorf("response json body error %s", err))
return
}
result, err := gojsonschema.Validate(gojsonschema.NewGoLoader(t.Response.BodyJsonSchema), gojsonschema.NewGoLoader(v))
if err != nil {
t.fail(fmt.Errorf("validation error %s", err))
return
}
if !result.Valid() {
for _, desc := range result.Errors() {
t.fail(fmt.Errorf("JSON schema expect %s", desc))
}
}
}
}
示例2: Refute
// Refute refutes that the given subject will validate against a particular
// schema.
func (v *SchemaValidator) Refute(t *testing.T) {
if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil {
t.Fatal(err)
} else if result.Valid() {
t.Fatal("api/schema: expected validation to fail, succeeded")
}
}
示例3: Validate
//Validate will validate a file with a Nulecule Specification
func Validate(schemaVersion string, location *url.URL) (bool, error) {
var rc error
// check if schemaVersion equals nulecule.NuleculeReleasedVersions
if schemaVersion != nulecule.NuleculeReleasedVersions {
return false, fmt.Errorf("The specified version (%s) of the Nulecule Specification is invalid", schemaVersion)
}
schemaLoader := gojsonschema.NewReferenceLoader(schemaLocation[schemaVersion])
documentLoader := gojsonschema.NewReferenceLoader(location.String())
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return false, err
}
if result.Valid() {
return true, nil
}
fmt.Printf("The document is not valid. see errors :\n")
for _, desc := range result.Errors() {
rc = multierror.Append(rc, fmt.Errorf("%s\n", desc.Description()))
fmt.Printf("- %s\n", desc)
}
rc = multierror.Append(fmt.Errorf("The document is not valid with Nulecule Specification version %s", schemaVersion))
return false, rc
}
示例4: validateServiceConstraintsv2
func validateServiceConstraintsv2(service RawService, serviceName string) error {
if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
return err
}
service = convertServiceKeysToStrings(service)
var validationErrors []string
dataLoader := gojsonschema.NewGoLoader(service)
result, err := gojsonschema.Validate(constraintSchemaLoaderV2, dataLoader)
if err != nil {
return err
}
if !result.Valid() {
for _, err := range result.Errors() {
if err.Type() == "required" {
_, containsImage := service["image"]
_, containsBuild := service["build"]
if containsBuild || !containsImage && !containsBuild {
validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build context specified. At least one must be provided.", serviceName))
}
}
}
return fmt.Errorf(strings.Join(validationErrors, "\n"))
}
return nil
}
示例5: validateSchema
// and define an implementation for that type that performs the schema validation
func (r *schemaValidatorType) validateSchema(schema, cfg string) []serror.SnapError {
schemaLoader := gojsonschema.NewStringLoader(schema)
testDoc := gojsonschema.NewStringLoader(cfg)
result, err := gojsonschema.Validate(schemaLoader, testDoc)
var serrors []serror.SnapError
// Check for invalid json
if err != nil {
serrors = append(serrors, serror.New(err))
return serrors
}
// check if result passes validation
if result.Valid() {
return nil
}
for _, err := range result.Errors() {
serr := serror.New(errors.New("Validate schema error"))
serr.SetFields(map[string]interface{}{
"value": err.Value(),
"context": err.Context().String("::"),
"description": err.Description(),
})
serrors = append(serrors, serr)
}
return serrors
}
示例6: JsonSchemaValidator
//middleware for json schema validation
func JsonSchemaValidator() gin.HandlerFunc {
return func(c *gin.Context) {
contextCopy := c.Copy()
var schema string
validateSchema := true
switch c.Request.RequestURI {
case "/signup":
schema = "signup.json"
case "/login":
schema = "login.json"
default:
validateSchema = false
}
if validateSchema {
schemaLoader := gojsonschema.NewReferenceLoader("file://" + myConstants.JsonSchemasFilesLocation + "/" +
schema)
body, _ := ioutil.ReadAll(contextCopy.Request.Body)
//fmt.Printf("%s", body)
documentLoader := gojsonschema.NewStringLoader(string(body))
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
log.Fatalln(myMessages.JsonSchemaValidationError + err.Error())
}
if !result.Valid() {
//fmt.Printf("The document is not valid. see errors :\n")
type errorsList []string
type JsonErrorOutput struct {
Error bool
Message string
Faults errorsList
}
var el errorsList
for _, desc := range result.Errors() {
//fmt.Printf("- %s\n", desc)
el = append(el, fmt.Sprintf("%s", desc))
}
var jeo JsonErrorOutput
jeo.Error = true
jeo.Message = myMessages.JsonSchemaValidationFailed
jeo.Faults = el
c.JSON(http.StatusBadRequest, jeo)
c.Abort()
return
}
}
c.Next()
}
}
示例7: TestValidRegistry
func TestValidRegistry(t *testing.T) {
schemaLoader := gojsonschema.NewReferenceLoader("file://./just-install-schema.json")
documentLoader := gojsonschema.NewReferenceLoader("file://./just-install.json")
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
assert.Nil(t, err)
assert.Empty(t, result.Errors())
assert.True(t, result.Valid())
}
示例8: Assert
// Assert preforms the validation assertion against the given *testing.T.
func (v *SchemaValidator) Assert(t *testing.T) {
if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil {
t.Fatal(err)
} else if !result.Valid() {
for _, err := range result.Errors() {
t.Logf("Validation error: %s", err.Description())
}
t.Fail()
}
}
示例9: ValidateJSON
// ValidateJSON validates the given runtime against its defined schema
func (cfg *RuntimeOptions) ValidateJSON() error {
schema := gojson.NewStringLoader(RuntimeSchema)
doc := gojson.NewGoLoader(cfg)
if result, err := gojson.Validate(schema, doc); err != nil {
return err
} else if !result.Valid() {
return combineErrors(result.Errors())
}
return nil
}
示例10: Update
func (c *InterfaceController) Update(w http.ResponseWriter, r *http.Request) {
// Get ID
id := mux.Vars(r)["id"]
// Validate ObjectId
if !bson.IsObjectIdHex(id) {
w.WriteHeader(http.StatusNotFound)
return
}
// Get object id
oid := bson.ObjectIdHex(id)
// Initialize empty struct
s := models.Interface{}
// Decode JSON into struct
err := json.NewDecoder(r.Body).Decode(&s)
if err != nil {
jsonError(w, r, "Failed to deconde JSON: "+err.Error(), http.StatusInternalServerError, c.envelope)
return
}
// Validate input using JSON Schema
docLoader := gojsonschema.NewGoLoader(s)
schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)
res, err := gojsonschema.Validate(schemaLoader, docLoader)
if err != nil {
jsonError(w, r, "Failed to load schema: "+err.Error(), http.StatusInternalServerError, c.envelope)
return
}
if !res.Valid() {
var errors []string
for _, e := range res.Errors() {
errors = append(errors, fmt.Sprintf("%s: %s", e.Context().String(), e.Description()))
}
jsonError(w, r, errors, http.StatusInternalServerError, c.envelope)
return
}
// Update entry
if err := c.session.DB(c.database).C("interfaces").UpdateId(oid, s); err != nil {
jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
return
}
// Write content-type, header and payload
jsonWriter(w, r, s, http.StatusOK, c.envelope)
}
示例11: validateRequestData
// validateRequestData takes in a schema path and the request
// and will do the legwork of determining if the post data is valid
func validateRequestData(schemaPath string, r *web.Request) (
document map[string]interface{},
result *gojsonschema.Result,
err error,
) {
err = json.NewDecoder(r.Body).Decode(&document)
if err == nil && schemaPath != "" {
schemaLoader := gojsonschema.NewReferenceLoader(schemaPath)
documentLoader := gojsonschema.NewGoLoader(document)
result, err = gojsonschema.Validate(schemaLoader, documentLoader)
}
return document, result, err
}
示例12: Parse
// Parse takes a state json and returns the state for it
func Parse(b []byte) (*State, error) {
schema, err := getSchema()
if err != nil {
return nil, err
}
result, err := gojsonschema.Validate(schema, gojsonschema.NewStringLoader(string(b)))
if err != nil {
return nil, err
}
if !result.Valid() {
return nil, &SchemaError{result.Errors()}
}
var s State
return &s, json.Unmarshal(b, &s)
}
示例13: Validate
//Validate validates json object using jsoncschema
func (schema *Schema) Validate(jsonSchema interface{}, object interface{}) error {
schemaLoader := gojsonschema.NewGoLoader(jsonSchema)
documentLoader := gojsonschema.NewGoLoader(object)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return err
}
if result.Valid() {
return nil
}
errDescription := "Json validation error:"
for _, err := range result.Errors() {
errDescription += fmt.Sprintf("\n\t%v,", err)
}
return fmt.Errorf(errDescription)
}
示例14: validate
func validate(sl gojsonschema.JSONLoader, dl gojsonschema.JSONLoader) (error, []string) {
result, err := gojsonschema.Validate(sl, dl)
if err != nil {
return err, nil
}
if result.Valid() {
return nil, nil
} else {
ss := make([]string, 0, len(result.Errors()))
for _, desc := range result.Errors() {
ss = append(ss, desc.Description())
}
return nil, ss
}
}
示例15: validateJSON
func validateJSON(schema string, obj Entity) error {
schemaObj := gojson.NewStringLoader(schema)
doc := gojson.NewGoLoader(obj)
if result, err := gojson.Validate(schemaObj, doc); err != nil {
return err
} else if !result.Valid() {
var errors []string
for _, err := range result.Errors() {
errors = append(errors, fmt.Sprintf("%s\n", err))
}
return errored.New(strings.Join(errors, "\n"))
}
return nil
}