本文整理汇总了Golang中github.com/xeipuuv/gojsonschema.NewGoLoader函数的典型用法代码示例。如果您正苦于以下问题:Golang NewGoLoader函数的具体用法?Golang NewGoLoader怎么用?Golang NewGoLoader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewGoLoader函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: setupSchemaLoaders
func setupSchemaLoaders() error {
if schema != nil {
return nil
}
var schemaRaw interface{}
err := json.Unmarshal([]byte(schemaString), &schemaRaw)
if err != nil {
return err
}
schema = schemaRaw.(map[string]interface{})
gojsonschema.FormatCheckers.Add("environment", environmentFormatChecker{})
gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{})
gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{})
schemaLoader = gojsonschema.NewGoLoader(schemaRaw)
definitions := schema["definitions"].(map[string]interface{})
constraints := definitions["constraints"].(map[string]interface{})
service := constraints["service"].(map[string]interface{})
constraintSchemaLoader = gojsonschema.NewGoLoader(service)
return nil
}
示例2: 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))
}
}
}
}
示例3: 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)
}
示例4: 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)
}
示例5: validate
func (self *Route) validate(params interface{}, version int) (string, error) {
route := self.Versions[version]
if route == nil {
return "", fmt.Errorf("Route version %v missing from %v route", version, self.Name)
}
if route.Schema == nil {
return "", nil
}
documentLoader := gojsonschema.NewGoLoader(params)
result, err := route.Schema.Validate(documentLoader)
if err != nil {
return "", err
}
if !result.Valid() {
errors := make(map[string]string)
for _, resultErr := range result.Errors() {
errors[resultErr.Field()] = resultErr.Description()
}
errorsJson, err := json.Marshal(errors)
if err != nil {
return "", err
}
return string(errorsJson), nil
}
return "", nil
}
示例6: 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
}
示例7: FixDataWithSchema
func FixDataWithSchema(data interface{}, schema interface{}) (dataFix interface{}, err error) {
_, err = gojsonschema.NewSchema(gojsonschema.NewGoLoader(schema))
if err != nil {
return nil, err
}
return fixDataWithSchemaInterface(data, schema)
}
示例8: ProcessObject
// ProcessObject checks if the object is valid from this schema's standpoint
// and returns an object with defaults set up according to schema's spec
func (j *JSONSchema) ProcessObject(in interface{}) (interface{}, error) {
result, err := j.schema.Validate(gojsonschema.NewGoLoader(in))
if err != nil {
return nil, trace.Wrap(err)
}
if !result.Valid() {
return nil, trace.Wrap(trace.Errorf("errors: %v", schemaErrors(result.Errors())))
}
return setDefaults(j.rawSchema, in), nil
}
示例9: checkSchema
func checkSchema(chain *chain, value, schema interface{}) {
if chain.failed() {
return
}
valueLoader := gojsonschema.NewGoLoader(value)
var schemaLoader gojsonschema.JSONLoader
if str, ok := toString(schema); ok {
if ok, _ := regexp.MatchString(`^\w+://`, str); ok {
schemaLoader = gojsonschema.NewReferenceLoader(str)
} else {
schemaLoader = gojsonschema.NewStringLoader(str)
}
} else {
schemaLoader = gojsonschema.NewGoLoader(schema)
}
result, err := gojsonschema.Validate(schemaLoader, valueLoader)
if err != nil {
chain.fail("\n%s\n\nschema:\n%s\n\nvalue:\n%s",
err.Error(),
dumpSchema(schema),
dumpValue(value))
return
}
if !result.Valid() {
errors := ""
for _, err := range result.Errors() {
errors += fmt.Sprintf(" %s\n", err)
}
chain.fail(
"\njson schema validation failed, schema:\n%s\n\nvalue:%s\n\nerrors:\n%s",
dumpSchema(schema),
dumpValue(value),
errors)
return
}
}
示例10: 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
}
示例11: getSchema
func (s *JSONSchema) getSchema() (schema *gojsonschema.Schema, err error) {
if s.schema != nil && !s.enumLoader.IsDirty() {
return s.schema, nil
}
loader := gojsonschema.NewGoLoader(s.GetPreprocessed())
s.schema, err = gojsonschema.NewSchema(loader)
if err != nil {
return
}
return s.schema, nil
}
示例12: 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)
}
示例13: Validate
func (s schema) Validate(data interface{}) error {
result, _ := s.schema.Validate(gojsonschema.NewGoLoader(data))
if result.Valid() {
return nil
}
msgs := []string{}
for _, e := range result.Errors() {
msgs = append(msgs, e.Description())
}
return singleIssue("", "Faild to validate sub-schema at {path}, errors: %s",
strings.Join(msgs, ", "),
)
}
示例14: New
// New returns JSON schema created from JSON byte string
// returns a valid schema or error if schema is invalid
func New(data []byte) (*JSONSchema, error) {
j := JSONSchema{}
err := json.Unmarshal(data, &j.rawSchema)
if err != nil {
return nil, trace.Wrap(err)
}
loader := gojsonschema.NewGoLoader(j.rawSchema)
j.schema, err = gojsonschema.NewSchema(loader)
if err != nil {
return nil, trace.Wrap(err)
}
return &j, nil
}
示例15: 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
}