Пример #1
0
func getSchemaValidator(s []byte) (*schema.Validator, error) {
	volSchema, err := ucl.Parse(bytes.NewReader(s))
	if err != nil {
		return nil, err
	}

	rootSchema, err := ucl.Parse(bytes.NewReader(jsonSchema))
	if err != nil {
		return nil, err
	}

	loader := schema.NewLoader()

	if err := loader.Add(rootSchema); err != nil {
		return nil, err
	}

	validator, err := schema.NewValidator(volSchema, loader)
	if err != nil {
		return nil, err
	}

	return validator, nil
}
Пример #2
0
func main() {
	flag.Parse()

	if *schemaFile == "" || *inputFile == "" {
		fmt.Fprintf(os.Stderr, "Need --schema and --input\n")
		os.Exit(1)
	}

	f, err := os.Open(*schemaFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to open %q: %s\n", *schemaFile, err)
		os.Exit(1)
	}

	s, err := json.Parse(f)
	f.Close()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to read schema: %s\n", err)
		os.Exit(1)
	}

	loader := schema.NewLoader()
	loader.EnableNetworkAccess(*network)
	if *extra != "" {
		for _, file := range strings.Split(*extra, " ") {
			f, err := os.Open(file)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to open %q: %s\n", file, err)
				os.Exit(1)
			}
			s, err := json.Parse(f)
			f.Close()
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to parse %q: %s\n", file, err)
				os.Exit(1)
			}
			loader.Add(s)
		}
	}
	if !*skipDefaultSchema {
		ds, err := json.Parse(bytes.NewBuffer(MustAsset("draft04schema.json")))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to parse embedded draft 04 schema: %s\n", err)
			os.Exit(1)
		}
		// Just to be sure, schema.ParseDraft04Schema exercises different code path.
		v, err := schema.NewValidator(ds, loader)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to create validator for draft04 schema, please file a bug: %s\n", err)
		} else {
			if err := v.Validate(s); err != nil {
				fmt.Fprintln(os.Stderr, "If you see this message, please file a bug and attach the schema you're using.")
				fmt.Fprintf(os.Stderr, "Warning: failed to validate %q with draft 04 schema: %s\n", *schemaFile, err)
			}
		}
	}

	validator, err := schema.NewValidator(s, loader)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to create validator: %s\n", err)
		os.Exit(1)
	}

	f, err = os.Open(*inputFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to open input file: %s\n", err)
		os.Exit(1)
	}
	defer f.Close()
	data, err := json.Parse(f)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to parse input file: %s\n", err)
		os.Exit(1)
	}
	if err := validator.Validate(data); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}