本文整理汇总了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
}
示例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())
}
示例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)
}
}
示例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)
}
示例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,
}
}
示例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)
}
}
示例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()
}
}
示例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)
}
}
}
示例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)
}
示例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
}
示例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)
}
}
示例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
}
示例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)
}
}
}
示例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")
}
}
示例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)
}