本文整理汇总了Golang中github.com/xeipuuv/gojsonschema.NewStringLoader函数的典型用法代码示例。如果您正苦于以下问题:Golang NewStringLoader函数的具体用法?Golang NewStringLoader怎么用?Golang NewStringLoader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewStringLoader函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: validateSchema
// and define an implementation for that type that performs the schema validation
func (r *schemaValidatorType) validateSchema(schema, cfg string) []serror.SnapError {
schemaLoader := gojsonschema.NewStringLoader(schema)
testDoc := gojsonschema.NewStringLoader(cfg)
result, err := gojsonschema.Validate(schemaLoader, testDoc)
var serrors []serror.SnapError
// Check for invalid json
if err != nil {
serrors = append(serrors, serror.New(err))
return serrors
}
// check if result passes validation
if result.Valid() {
return nil
}
for _, err := range result.Errors() {
serr := serror.New(errors.New("Validate schema error"))
serr.SetFields(map[string]interface{}{
"value": err.Value(),
"context": err.Context().String("::"),
"description": err.Description(),
})
serrors = append(serrors, serr)
}
return serrors
}
示例2: NewJSONEventTrackingValidator
//NewJSONEventTrackingValidator returns a new JSONEventTrackingValidator with the parsed Schema
func NewJSONEventTrackingValidator() (*JSONEventTrackingValidator, error) {
schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(schema))
if err != nil {
return nil, err
}
return &JSONEventTrackingValidator{schema}, err
}
示例3: LoadSchema
// LoadSchema loads the schema from a string.
func LoadSchema(schema string) error {
var err error
schemaLoader := gojsonschema.NewStringLoader(schema)
movenSchemaValidator, err = gojsonschema.NewSchema(schemaLoader)
return err
}
示例4: 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,
}
}
示例5: ServeHTTP
func (v Validator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(405), 405)
return
}
var resp ValidationResult
render := func() {
if err := json.NewEncoder(w).Encode(resp); err != nil {
http.Error(w, http.StatusText(500), 500)
}
}
jsonDoc := r.FormValue("json")
resp.DocType = r.FormValue("doctype")
schema, ok := v[r.FormValue("doctype")]
if !ok {
resp.Errors = []string{fmt.Sprintf("This document type schema not yet implemented: %q", r.FormValue("doctype"))}
render()
return
}
loader := js.NewStringLoader(jsonDoc)
result, err := schema.Validate(loader)
if err != nil {
resp.Errors = []string{"JSON is not well-formed: " + err.Error()}
} else {
if result.Valid() {
resp.Valid = true
} else {
for _, err := range result.Errors() {
msg := err.Context.String() + ": " + err.Description
resp.Errors = append(resp.Errors, msg)
}
}
}
render()
}
示例6: BenchmarkGojsonschemaParse
func BenchmarkGojsonschemaParse(b *testing.B) {
l := gojsonschema.NewStringLoader(schemaJSON)
for i := 0; i < b.N; i++ {
s, _ := gojsonschema.NewSchema(l)
_ = s
}
}
示例7: Validate
func (ts *ThreatSpec) Validate() error {
schemaLoader := gojsonschema.NewStringLoader(ThreatSpecSchemaStrictv0)
documentLoader := gojsonschema.NewStringLoader(ts.ToJson())
if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil {
return err
} else if result.Valid() {
return nil
} else {
var errs []string
for _, desc := range result.Errors() {
errs = append(errs, fmt.Sprintf(" - %s", desc))
}
return errors.New(strings.Join(errs, "\n"))
}
}
示例8: MustSchema
func MustSchema(schemaString string) *schema.Schema {
s, err := schema.NewSchema(schema.NewStringLoader(schemaString))
if err != nil {
panic(err)
}
return s
}
示例9: ValidateEventTrackingPayloadHandler
//ValidateEventTrackingPayloadHandler validates that the payload has a valid JSON Schema
//Uses a FinalHandler as next because it consumes the request's body
func ValidateEventTrackingPayloadHandler(next *ctx.FinalHandler) *ctx.Handler {
return ctx.NewHandler(next.Context, func(c *ctx.Context, w http.ResponseWriter, r *http.Request) {
//Validate the payload
body, err := ioutil.ReadAll(r.Body)
if err != nil {
c.Logger.Errorf("%s : Error reading body: %s", utilities.GetIP(r), err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
next.Payload = body
requestLoader := gojsonschema.NewStringLoader(string(body))
result, err := c.JSONTrackingEventValidator.Schema.Validate(requestLoader)
if err != nil {
c.Logger.Infof("%s : Json validation error: %s", utilities.GetIP(r), err.Error())
http.Error(w, http.StatusText(400), 400)
return
}
if !result.Valid() {
c.Logger.Infof("%s : Payload is not valid: %+v", utilities.GetIP(r), result.Errors())
http.Error(w, http.StatusText(400), 400)
return
}
next.ServeHTTP(w, r)
})
}
示例10: 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)
}
示例11: validateFile
func validateFile(ctx Context, path string) {
ctx.running <- true
defer func() {
ctx.running <- false
}()
//fmt.Println(path)
bytes, err := ioutil.ReadFile(path)
if err != nil {
ctx.result <- fmt.Sprint(err)
return
}
result, err := ctx.schema.Validate(gojsonschema.NewStringLoader(string(bytes)))
if err != nil {
ctx.result <- fmt.Sprint(path, err)
return
}
if !result.Valid() {
errors := result.Errors()
res := make([]string, 1+len(errors))
res[0] = fmt.Sprintf("%s:", path)
//ctx.result <- fmt.Sprintf("%s:\n", path)
for i, desc := range errors {
res[1+i] = fmt.Sprint(desc)
}
ctx.result <- strings.Join(res, "\n- ") + "\n"
} else {
//ctx.result <- = fmt.Sprintf("%s: ok\n", path)
}
}
示例12: isValidJson
func isValidJson(schema, json string) bool {
schema = strings.TrimSpace(schema)
if len(schema) == 2 {
schema = `{"additionalProperties": false}`
} else {
schema = schema[:len(schema)-1] + `,"additionalProperties":false}`
}
dataLoader := gojsonschema.NewStringLoader(json)
schemaLoader := gojsonschema.NewStringLoader(schema)
if result, validateErr := gojsonschema.Validate(schemaLoader, dataLoader); validateErr == nil {
return result.Valid()
} else {
return false
}
}
示例13: ValidateContent
func (s *JSONSchema) ValidateContent(content []byte) (r *gojsonschema.Result, err error) {
documentLoader := gojsonschema.NewStringLoader(string(content))
schema, err := s.getSchema()
if err != nil {
return
}
return schema.Validate(documentLoader)
}
示例14: 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()
}
}
示例15: validateJSON
func validateJSON(jsonText string, schemaText string) error {
schemaLoader := gojsonschema.NewStringLoader(schemaText)
docLoader := gojsonschema.NewStringLoader(jsonText)
result, err := gojsonschema.Validate(schemaLoader, docLoader)
if err != nil {
return err
}
if !result.Valid() {
errMessage := "The JSON data is not valid:\n"
for _, desc := range result.Errors() {
errMessage += fmt.Sprintf(" %v\n", desc)
}
return errors.New(errMessage)
}
return nil
}