本文整理汇总了Golang中github.com/xeipuuv/gojsonschema.NewGoLoader函数的典型用法代码示例。如果您正苦于以下问题:Golang NewGoLoader函数的具体用法?Golang NewGoLoader怎么用?Golang NewGoLoader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewGoLoader函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:kunalkushwaha,项目名称:libcompose,代码行数:25,代码来源:schema_helpers.go
示例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))
}
}
}
}
开发者ID:Djuke,项目名称:httpapitester,代码行数:28,代码来源:test.go
示例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)
}
开发者ID:hidu,项目名称:goutils,代码行数:35,代码来源:genSchema_test.go
示例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)
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:17,代码来源:schema.go
示例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
}
开发者ID:gophergala2016,项目名称:dbservice,代码行数:26,代码来源:route.go
示例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
}
开发者ID:yinshiua,项目名称:amazon-ecs-cli,代码行数:32,代码来源:validation.go
示例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)
}
开发者ID:DirkZhao,项目名称:pproxy,代码行数:8,代码来源:fix.go
示例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
}
开发者ID:lucmichalski,项目名称:configure,代码行数:12,代码来源:schema.go
示例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
}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:43,代码来源:helpers.go
示例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
}
开发者ID:contiv,项目名称:volplugin,代码行数:13,代码来源:validation.go
示例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
}
开发者ID:contactless,项目名称:wb-mqtt-confed,代码行数:13,代码来源:schema.go
示例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)
}
开发者ID:bfloriang,项目名称:dock2box,代码行数:51,代码来源:interface.go
示例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, ", "),
)
}
开发者ID:taskcluster,项目名称:taskcluster-worker,代码行数:14,代码来源:schema.go
示例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
}
开发者ID:gravitational,项目名称:configure,代码行数:16,代码来源:schema.go
示例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
}
开发者ID:gtrevg,项目名称:golang-rest-raml-validation,代码行数:17,代码来源:main.go
示例16: validateJSON
func validateJSON(schema string, obj Entity) error {
schemaObj := gojson.NewStringLoader(schema)
doc := gojson.NewGoLoader(obj)
if result, err := gojson.Validate(schemaObj, doc); err != nil {
return err
} else if !result.Valid() {
var errors []string
for _, err := range result.Errors() {
errors = append(errors, fmt.Sprintf("%s\n", err))
}
return errored.New(strings.Join(errors, "\n"))
}
return nil
}
开发者ID:contiv,项目名称:volplugin,代码行数:16,代码来源:validate_json.go
示例17: validateV2
func validateV2(serviceMap RawServiceMap) error {
if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
return err
}
serviceMap = convertServiceMapKeysToStrings(serviceMap)
dataLoader := gojsonschema.NewGoLoader(serviceMap)
result, err := gojsonschema.Validate(schemaLoaderV2, dataLoader)
if err != nil {
return err
}
return generateErrorMessages(serviceMap, schemaV2, result)
}
开发者ID:yinshiua,项目名称:amazon-ecs-cli,代码行数:16,代码来源:validation.go
示例18: 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) {
defaults := setDefaults(j.rawSchema, in)
result, err := j.schema.Validate(gojsonschema.NewGoLoader(defaults))
if err != nil {
return nil, trace.Wrap(err)
}
if !result.Valid() {
errors := result.Errors()
output := make([]string, len(errors))
for i, err := range errors {
output[i] = fmt.Sprintf("%v", err)
}
return nil, trace.Errorf("failed to validate: %v", strings.Join(output, ","))
}
return defaults, nil
}
开发者ID:gravitational,项目名称:configure,代码行数:20,代码来源:schema.go
示例19: 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
示例20: 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.NewGoLoader函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论