当前位置: 首页>>代码示例>>Golang>>正文


Golang gojsonschema.NewReferenceLoader函数代码示例

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


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

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

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

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

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

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

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

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

示例8: main

func main() {

	schemaLoader := gojsonschema.NewReferenceLoader("file:///code/schema.json")
	documentLoader := gojsonschema.NewReferenceLoader("file:///code/sample.json")

	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)
		}
	}

}
开发者ID:gitter-badger,项目名称:lucibus,代码行数:20,代码来源:gojsonschema.go

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

示例10: Load

func (s *Schema) Load() error {
	p, err := filepath.Abs(s.File)
	if err != nil {
		return err
	}

	if _, err := os.Stat(p); err != nil {
		return err
	}

	p = fmt.Sprintf("file://%s", p)
	s.loader = gojsonschema.NewReferenceLoader(p)
	return nil
}
开发者ID:chop-dbhi,项目名称:scds,代码行数:14,代码来源:schema.go

示例11: validateSchema

func validateSchema(schemaPathString string, docPathString string) {
	schemaPath, _ := filepath.Abs(schemaPathString)
	schemaUri := "file://" + schemaPath
	schemaLoader := gojsonschema.NewReferenceLoader(schemaUri)

	docPath, _ := filepath.Abs(docPathString)
	docUri := "file://" + docPath
	docLoader := gojsonschema.NewReferenceLoader(docUri)

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

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

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

示例13: main

func main() {
	result := make(chan string)
	running := make(chan bool)
	ctx := Context{
		result:  result,
		running: running,
	}

	schemaFile, err := filepath.Abs(os.Args[1])
	u := url.URL{
		Scheme: "file",
		Path:   schemaFile,
	}
	ctx.schema, err = gojsonschema.NewSchema(gojsonschema.NewReferenceLoader(u.String()))
	if err != nil {
		panic(err)
	}

	if len(os.Args) == 2 {
		fmt.Println("missing files/dir to process")
		return
	}

	for _, arg := range os.Args[2:] {
		validateAny(ctx, arg)
	}
	count := 0
	for {
		select {
		case r := <-running:
			if r {
				count++
			} else {
				count--
				if count == 0 {
					//fmt.Println("Done.")
					return
				}
			}
			//fmt.Println("Running: ", count)
		case r := <-result:
			fmt.Print(r)
		}
	}
}
开发者ID:dolmen,项目名称:jsonchk,代码行数:45,代码来源:main.go

示例14: validateFunc

func validateFunc(e Etcdtool, dir string, d interface{}) {
	// Map directory to routes.
	var schema string
	for _, r := range e.Routes {
		match, err := regexp.MatchString(r.Regexp, dir)
		if err != nil {
			fatal(err.Error())
		}
		if match {
			schema = r.Schema
		}
	}

	if schema == "" {
		fatal("Couldn't determine which JSON schema to use for validation")
	}

	/*
	   if schema == "" && len(c.Args()) == 1 {
	       fatal("You need to specify JSON schema URI")
	   }

	   if len(c.Args()) > 1 {
	       schema = c.Args()[1]
	   }
	*/

	// Validate directory.
	infof("Using JSON schema: %s", schema)
	schemaLoader := gojsonschema.NewReferenceLoader(schema)
	docLoader := gojsonschema.NewGoLoader(d)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		fatal(err.Error())
	}

	// Print results.
	if !result.Valid() {
		for _, err := range result.Errors() {
			fmt.Printf("%s: %s\n", strings.Replace(err.Context().String("/"), "(root)", dir, 1), err.Description())
		}
		fatal("Data validation failed aborting")
	}
}
开发者ID:mickep76,项目名称:etcdtool,代码行数:44,代码来源:validate_command.go

示例15: Create

func (c *TenantController) Create(w http.ResponseWriter, r *http.Request) {
	// Initialize empty struct
	s := models.Tenant{}

	// 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
	}

	// Set ID
	s.ID = bson.NewObjectId()

	// Validate input using JSON Schema
	log.Printf("Using schema: %s", c.schemaURI)
	docLoader := gojsonschema.NewGoLoader(s)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)

	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		jsonError(w, r, 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
	}

	// Insert entry
	if err := c.session.DB(c.database).C("tenants").Insert(s); err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusCreated, c.envelope)
}
开发者ID:bfloriang,项目名称:dock2box,代码行数:43,代码来源:tenant.go


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