42 lines
924 B
Go
42 lines
924 B
Go
|
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
||
|
|
||
|
package resource
|
||
|
|
||
|
import (
|
||
|
_ "encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"github.com/xeipuuv/gojsonschema"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
type Schema struct {
|
||
|
schema gojsonschema.JSONLoader
|
||
|
}
|
||
|
|
||
|
func NewSchema(name string) *Schema {
|
||
|
path := fmt.Sprintf("file://schemas/%s.jsonschema", name)
|
||
|
|
||
|
return &Schema{schema: gojsonschema.NewReferenceLoader(path)}
|
||
|
}
|
||
|
|
||
|
func (s *Schema) Validate(source string) error {
|
||
|
// loader := gojsonschema.NewGoLoader(source)
|
||
|
loader := gojsonschema.NewStringLoader(source)
|
||
|
result, err := gojsonschema.Validate(s.schema, loader)
|
||
|
|
||
|
if err != nil {
|
||
|
fmt.Printf("%#v %#v %#v %#v\n", source, loader, result, err)
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if !result.Valid() {
|
||
|
schemaErrors := strings.Builder{}
|
||
|
for _, err := range result.Errors() {
|
||
|
schemaErrors.WriteString(err.String() + "\n")
|
||
|
}
|
||
|
return errors.New(schemaErrors.String())
|
||
|
}
|
||
|
return nil
|
||
|
}
|