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

Golang gojsonschema.NewStringLoader函数代码示例

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

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



在下文中一共展示了NewStringLoader函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: 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


示例2: NewJSONEventTrackingValidator

//NewJSONEventTrackingValidator returns a new JSONEventTrackingValidator with the parsed Schema
func NewJSONEventTrackingValidator() (*JSONEventTrackingValidator, error) {
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(schema))
	if err != nil {
		return nil, err
	}
	return &JSONEventTrackingValidator{schema}, err
}
开发者ID:OlivierBoucher,项目名称:go-tracking-server,代码行数:8,代码来源:jsonEventTrackingValidator.go


示例3: LoadSchema

// LoadSchema loads the schema from a string.
func LoadSchema(schema string) error {
	var err error
	schemaLoader := gojsonschema.NewStringLoader(schema)

	movenSchemaValidator, err = gojsonschema.NewSchema(schemaLoader)
	return err
}
开发者ID:peterzandbergen,项目名称:jsonschema,代码行数:8,代码来源:validatejs.go


示例4: NewSchemaValidator

func NewSchemaValidator(t *testing.T, schemaName string, got interface{}) *SchemaValidator {
	dir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	// Platform compatibility: use "/" separators always for file://
	dir = filepath.ToSlash(dir)

	schema := gojsonschema.NewReferenceLoader(fmt.Sprintf(
		"file:///%s/schema/%s", dir, schemaName),
	)

	marshalled, err := json.Marshal(got)
	if err != nil {
		t.Fatal(err)
	}

	subject := gojsonschema.NewStringLoader(string(marshalled))

	return &SchemaValidator{
		Schema:  schema,
		Subject: subject,
	}
}
开发者ID:zhaohaiyi,项目名称:git-lfs,代码行数:25,代码来源:schema_validator.go


示例5: ServeHTTP

func (v Validator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, http.StatusText(405), 405)
		return
	}
	var resp ValidationResult
	render := func() {
		if err := json.NewEncoder(w).Encode(resp); err != nil {
			http.Error(w, http.StatusText(500), 500)
		}
	}
	jsonDoc := r.FormValue("json")
	resp.DocType = r.FormValue("doctype")
	schema, ok := v[r.FormValue("doctype")]
	if !ok {
		resp.Errors = []string{fmt.Sprintf("This document type schema not yet implemented: %q", r.FormValue("doctype"))}
		render()
		return
	}
	loader := js.NewStringLoader(jsonDoc)
	result, err := schema.Validate(loader)
	if err != nil {
		resp.Errors = []string{"JSON is not well-formed: " + err.Error()}
	} else {
		if result.Valid() {
			resp.Valid = true
		} else {
			for _, err := range result.Errors() {
				msg := err.Context.String() + ": " + err.Description
				resp.Errors = append(resp.Errors, msg)
			}
		}
	}
	render()
}
开发者ID:gravldo,项目名称:qhp-validator,代码行数:35,代码来源:validator.go


示例6: BenchmarkGojsonschemaParse

func BenchmarkGojsonschemaParse(b *testing.B) {
	l := gojsonschema.NewStringLoader(schemaJSON)
	for i := 0; i < b.N; i++ {
		s, _ := gojsonschema.NewSchema(l)
		_ = s
	}
}
开发者ID:lestrrat,项目名称:go-jsschema,代码行数:7,代码来源:benchmark_test.go


示例7: 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


示例8: MustSchema

func MustSchema(schemaString string) *schema.Schema {
	s, err := schema.NewSchema(schema.NewStringLoader(schemaString))
	if err != nil {
		panic(err)
	}
	return s
}
开发者ID:snikch,项目名称:api,代码行数:7,代码来源:schema.go


示例9: ValidateEventTrackingPayloadHandler

//ValidateEventTrackingPayloadHandler validates that the payload has a valid JSON Schema
//Uses a FinalHandler as next because it consumes the request's body
func ValidateEventTrackingPayloadHandler(next *ctx.FinalHandler) *ctx.Handler {
	return ctx.NewHandler(next.Context, func(c *ctx.Context, w http.ResponseWriter, r *http.Request) {
		//Validate the payload
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			c.Logger.Errorf("%s : Error reading body: %s", utilities.GetIP(r), err.Error())
			http.Error(w, http.StatusText(500), 500)
			return
		}
		next.Payload = body
		requestLoader := gojsonschema.NewStringLoader(string(body))

		result, err := c.JSONTrackingEventValidator.Schema.Validate(requestLoader)
		if err != nil {
			c.Logger.Infof("%s : Json validation error: %s", utilities.GetIP(r), err.Error())
			http.Error(w, http.StatusText(400), 400)
			return
		}

		if !result.Valid() {
			c.Logger.Infof("%s : Payload is not valid: %+v", utilities.GetIP(r), result.Errors())
			http.Error(w, http.StatusText(400), 400)
			return
		}
		next.ServeHTTP(w, r)
	})
}
开发者ID:OlivierBoucher,项目名称:go-tracking-server,代码行数:29,代码来源:middlewares.go


示例10: TestGenJsonSchema

func TestGenJsonSchema(t *testing.T) {
	str := `
		{
		"k1":"a",
		"k2":1,
		"k3":[],
		"k4":["a"],
		"k5":[1],
		"k6":[1.1],
		"k7":{},
		"k8":{"a":1},
		"k9":{"a":1,"b":[]},
		"k10":{"a":1,"b":[],"c":{"d":1.1}},
		"k11":{"a":1,"b":[],"c":{"d":1.1,"f":["a"]}},
		"k12":{"a":1,"b":[{"a":1,"b":[1]}]}
		}
	`
	var obj interface{}
	err := json.Unmarshal([]byte(str), &obj)
	assert.Equal(t, err, nil)

	schema, err := GenJsonSchema(obj)
	assert.Equal(t, err, nil)

	_, err = json.MarshalIndent(schema, "", "  ")
	assert.Equal(t, err, nil)
	//	fmt.Println(string(bs))

	goSchema, err := gojsonschema.NewSchema(gojsonschema.NewGoLoader(schema))
	assert.Equal(t, err, nil)
	documentLoader := gojsonschema.NewStringLoader(str)
	ret, err := goSchema.Validate(documentLoader)
	assert.Equal(t, err, nil)
	assert.Equal(t, ret.Valid(), true)
}
开发者ID:hidu,项目名称:goutils,代码行数:35,代码来源:genSchema_test.go


示例11: validateFile

func validateFile(ctx Context, path string) {
	ctx.running <- true
	defer func() {
		ctx.running <- false
	}()

	//fmt.Println(path)
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		ctx.result <- fmt.Sprint(err)
		return
	}
	result, err := ctx.schema.Validate(gojsonschema.NewStringLoader(string(bytes)))
	if err != nil {
		ctx.result <- fmt.Sprint(path, err)
		return
	}

	if !result.Valid() {
		errors := result.Errors()
		res := make([]string, 1+len(errors))
		res[0] = fmt.Sprintf("%s:", path)
		//ctx.result <- fmt.Sprintf("%s:\n", path)
		for i, desc := range errors {
			res[1+i] = fmt.Sprint(desc)
		}
		ctx.result <- strings.Join(res, "\n- ") + "\n"
	} else {
		//ctx.result <- = fmt.Sprintf("%s: ok\n", path)
	}
}
开发者ID:dolmen,项目名称:jsonchk,代码行数:31,代码来源:main.go


示例12: isValidJson

func isValidJson(schema, json string) bool {
	schema = strings.TrimSpace(schema)
	if len(schema) == 2 {
		schema = `{"additionalProperties": false}`
	} else {
		schema = schema[:len(schema)-1] + `,"additionalProperties":false}`
	}

	dataLoader := gojsonschema.NewStringLoader(json)
	schemaLoader := gojsonschema.NewStringLoader(schema)

	if result, validateErr := gojsonschema.Validate(schemaLoader, dataLoader); validateErr == nil {
		return result.Valid()
	} else {
		return false
	}
}
开发者ID:hdiwan,项目名称:RedRoute,代码行数:17,代码来源:json.go


示例13: ValidateContent

func (s *JSONSchema) ValidateContent(content []byte) (r *gojsonschema.Result, err error) {
	documentLoader := gojsonschema.NewStringLoader(string(content))
	schema, err := s.getSchema()
	if err != nil {
		return
	}
	return schema.Validate(documentLoader)
}
开发者ID:contactless,项目名称:wb-mqtt-confed,代码行数:8,代码来源:schema.go


示例14: 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


示例15: validateJSON

func validateJSON(jsonText string, schemaText string) error {
	schemaLoader := gojsonschema.NewStringLoader(schemaText)
	docLoader := gojsonschema.NewStringLoader(jsonText)

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

	if !result.Valid() {
		errMessage := "The JSON data is not valid:\n"
		for _, desc := range result.Errors() {
			errMessage += fmt.Sprintf("  %v\n", desc)
		}
		return errors.New(errMessage)
	}
	return nil
}
开发者ID:shiwano,项目名称:master,代码行数:18,代码来源:validator.go


示例16: ReadConfigValidate

// Read loadmodel from document - you can provide your own schema to validate the loadmodel.
func (test *TestConfig) ReadConfigValidate(document string, schema string) error {
	documentLoader := gojsonschema.NewStringLoader(document)
	schemaLoader := gojsonschema.NewStringLoader(schema)

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

	if !result.Valid() {
		msg := "the loadmodel is not valid:"
		for _, desc := range result.Errors() {
			msg += fmt.Sprintf("\n- %s", desc)
		}
		return fmt.Errorf(msg)
	}

	return json.Unmarshal([]byte(document), &test.config)
}
开发者ID:finklabs,项目名称:GoGrinder,代码行数:20,代码来源:config.go


示例17: getSchema

func getSchema() (gojsonschema.JSONLoader, error) {
	if schema != nil {
		return schema, nil
	}
	b, err := Asset("schema.json")
	if err != nil {
		return nil, err
	}
	return gojsonschema.NewStringLoader(string(b)), nil
}
开发者ID:gitter-badger,项目名称:lucibus,代码行数:10,代码来源:schema.go


示例18: ParseSchema

func ParseSchema(path string, route *Route) error {
	content, err := ioutil.ReadFile(path + "/schemas/" + route.Name + ".schema")
	if err != nil {
		return nil
	}
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(string(content)))
	if err != nil {
		return err
	}
	route.Schema = schema
	return nil
}
开发者ID:lacion,项目名称:dbservice,代码行数:12,代码来源:parser.go


示例19: 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


示例20: TestPayloadSchemaValid

// Test that the burned in payload schema is a valid json schema
func TestPayloadSchemaValid(t *testing.T) {
	payloadSchema := taskPayloadSchema()
	schemaLoader := gojsonschema.NewStringLoader(payloadSchema)
	_, err := gojsonschema.NewSchema(schemaLoader)
	if err != nil {
		t.Logf("Generic Worker payload schema is not a valid json schema for platform %v.", runtime.GOOS)
		t.Log("Payload schema:")
		t.Log(payloadSchema)
		t.Log("Error:")
		t.Fatalf("%s", err)
	}
}
开发者ID:petemoore,项目名称:generic-worker,代码行数:13,代码来源:payload_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang gojsonschema.Validate函数代码示例发布时间:2022-05-28
下一篇:
Golang gojsonschema.NewReferenceLoader函数代码示例发布时间: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