• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang gojsonschema.Validate函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/xeipuuv/gojsonschema.Validate函数的典型用法代码示例。如果您正苦于以下问题:Golang Validate函数的具体用法?Golang Validate怎么用?Golang Validate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Validate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
			}
		}
	}
}
开发者ID:Djuke,项目名称:httpapitester,代码行数:28,代码来源:test.go


示例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")
	}
}
开发者ID:tianguanghui,项目名称:git-lfs,代码行数:9,代码来源:schema_validator.go


示例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
}
开发者ID:kadel,项目名称:grasshopper,代码行数:31,代码来源:validator.go


示例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
}
开发者ID:yinshiua,项目名称:amazon-ecs-cli,代码行数:32,代码来源:validation.go


示例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
}
开发者ID:Collinux,项目名称:snap,代码行数:26,代码来源:cfgfile.go


示例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()
	}
}
开发者ID:sanathb,项目名称:go-gin-onboarding,代码行数:59,代码来源:middleware.go


示例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())
}
开发者ID:vincecima,项目名称:just-install,代码行数:10,代码来源:registry_test.go


示例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()
	}
}
开发者ID:tianguanghui,项目名称:git-lfs,代码行数:11,代码来源:schema_validator.go


示例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
}
开发者ID:contiv,项目名称:volplugin,代码行数:13,代码来源:validation.go


示例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)
}
开发者ID:bfloriang,项目名称:dock2box,代码行数:51,代码来源:interface.go


示例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
}
开发者ID:gtrevg,项目名称:golang-rest-raml-validation,代码行数:17,代码来源:main.go


示例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)
}
开发者ID:gitter-badger,项目名称:lucibus,代码行数:16,代码来源:main.go


示例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)
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:17,代码来源:schema.go


示例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
	}
}
开发者ID:reiki4040,项目名称:go-memo,代码行数:16,代码来源:main.go


示例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
}
开发者ID:contiv,项目名称:volplugin,代码行数:16,代码来源:validate_json.go


示例16: validateJson

func validateJson(schemaUrl, docUrl string) {
	schemaLoader := gojsonschema.NewReferenceLoader(schemaUrl)
	docLoader := gojsonschema.NewReferenceLoader(docUrl)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	utils.ExitOnFail(err)
	if result.Valid() {
		fmt.Printf("Document '%v' is valid against '%v'.\n", docUrl, schemaUrl)
	} else {
		fmt.Printf("Document '%v' is INVALID against '%v'.\n", docUrl, schemaUrl)
		for _, desc := range result.Errors() {
			fmt.Println("")
			fmt.Printf("- %s\n", desc)
		}
		// os.Exit(70)
	}
}
开发者ID:taskcluster,项目名称:taskcluster-client-java,代码行数:16,代码来源:model.go


示例17: Validate

func (ts *ThreatSpec) Validate() error {
	schemaLoader := gojsonschema.NewStringLoader(ThreatSpecSchemaStrictv0)
	documentLoader := gojsonschema.NewStringLoader(ts.ToJson())

	if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil {
		return err
	} else if result.Valid() {
		return nil
	} else {
		var errs []string
		for _, desc := range result.Errors() {
			errs = append(errs, fmt.Sprintf("  - %s", desc))
		}
		return errors.New(strings.Join(errs, "\n"))
	}
}
开发者ID:zeroXten,项目名称:threatspec-go,代码行数:16,代码来源:threatspec.go


示例18: validateV2

func validateV2(serviceMap RawServiceMap) error {
	if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
		return err
	}

	serviceMap = convertServiceMapKeysToStrings(serviceMap)

	dataLoader := gojsonschema.NewGoLoader(serviceMap)

	result, err := gojsonschema.Validate(schemaLoaderV2, dataLoader)
	if err != nil {
		return err
	}

	return generateErrorMessages(serviceMap, schemaV2, result)
}
开发者ID:yinshiua,项目名称:amazon-ecs-cli,代码行数:16,代码来源:validation.go


示例19: ValidateSchema

//ValidateSchema validates json schema
func (manager *Manager) ValidateSchema(schemaPath, filePath string) error {
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	documentLoader := gojsonschema.NewReferenceLoader("file://" + filePath)
	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}
	if result.Valid() {
		return nil
	}
	var errMessage string
	for _, err := range result.Errors() {
		errMessage += fmt.Sprintf("%v   ", err)
	}
	return fmt.Errorf("Invalid json: %s", errMessage)
}
开发者ID:gitter-badger,项目名称:gohan,代码行数:17,代码来源:manager.go


示例20: main

func main() {
	nargs := len(os.Args[1:])
	if nargs == 0 || nargs > 2 {
		fmt.Printf("ERROR: usage is: %s <schema.json> [<document.json>]\n", os.Args[0])
		os.Exit(1)
	}

	schemaPath, err := filepath.Abs(os.Args[1])
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	var documentLoader gojsonschema.JSONLoader

	if nargs > 1 {
		documentPath, err := filepath.Abs(os.Args[2])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentLoader = gojsonschema.NewReferenceLoader("file://" + documentPath)
	} else {
		documentBytes, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentString := string(documentBytes)
		documentLoader = gojsonschema.NewStringLoader(documentString)
	}

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		os.Exit(1)
	}
}
开发者ID:jcfr,项目名称:runtime-spec,代码行数:47,代码来源:validate.go



注:本文中的github.com/xeipuuv/gojsonschema.Validate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang gojsonschema.ResultError类代码示例发布时间:2022-05-28
下一篇:
Golang gojsonschema.NewStringLoader函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap