schema

package module
v0.0.0-...-29ed749 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2016 License: MIT Imports: 14 Imported by: 106

README

go-jsschema

Build Status

GoDoc

JSON Schema for Go

SYNOPSIS

package schema_test

import (
  "log"

  "github.com/lestrrat/go-jsschema"
  "github.com/lestrrat/go-jsschema/validator"
)

func Example() {
  s, err := schema.ReadFile("schema.json")
  if err != nil {
    log.Printf("failed to read schema: %s", err)
    return
  }

  for name, pdef := range s.Properties {
    // Do what you will with `pdef`, which contain
    // Schema information for `name` property
    _ = name
    _ = pdef
  }

  // You can also validate an arbitrary piece of data
  var p interface{} // initialize using json.Unmarshal...
  v := validator.New(s)
  if err := v.Validate(p); err != nil {
    log.Printf("failed to validate data: %s", err)
  }
}

TODO

  • Properly resolve ids and $refs (it works in simple cases, but elaborate scopes probably don't work)

References

Name Notes
go-jsval Validator generator
go-jshschema JSON Hyper Schema implementation
go-jsref JSON Reference implementation
go-jspointer JSON Pointer implementations

Documentation

Overview

Example
s, err := schema.ReadFile("schema.json")
if err != nil {
	log.Printf("failed to read schema: %s", err)
	return
}

for name, pdef := range s.Properties {
	// Do what you will with `pdef`, which contain
	// Schema information for `name` property
	_ = name
	_ = pdef
}

// Create a validator
v := validator.New(s)

// You can also validate an arbitrary piece of data
var p interface{} // initialize using json.Unmarshal...
if err := v.Validate(p); err != nil {
	log.Printf("failed to validate data: %s", err)
}
Output:

Index

Examples

Constants

View Source
const (
	SchemaURL      = `http://json-schema.org/draft-04/schema`
	HyperSchemaURL = `http://json-schema.org/draft-03/hyper-schema`
	MIMEType       = "application/schema+json"
)

Variables

View Source
var (
	ErrAdditionalProperties        = errors.New("additional properties are not allowed")
	ErrAnyOfValidationFailed       = errors.New("'anyOf' validation failed")
	ErrArrayItemValidationFailed   = errors.New("'array' validation failed")
	ErrInvalidStringArray          = errors.New("invalid value: expected array of string")
	ErrDependencyItemType          = errors.New("'dependency' elements must be a array of strings or a schema")
	ErrOneOfValidationFailed       = errors.New("'oneOf' validation failed")
	ErrIntegerValidationFailed     = errors.New("'integer' validation failed")
	ErrInvalidEnum                 = errors.New("invalid enum type")
	ErrInvalidFormat               = errors.New("invalid format")
	ErrInvalidHostname             = errors.New("invalid hostname")
	ErrInvalidIPv4                 = errors.New("invalid IPv4 address")
	ErrInvalidIPv6                 = errors.New("invalid IPv6 address")
	ErrInvalidSchemaList           = errors.New("invalid schema list")
	ErrInvalidType                 = errors.New("invalid type")
	ErrMissingDependency           = errors.New("missing dependency")
	ErrMultipleOfValidationFailed  = errors.New("'multipleOf' validation failed")
	ErrNotValidationFailed         = errors.New("'not' validation failed")
	ErrNumberValidationFailed      = errors.New("'number' validation failed")
	ErrPropNotFound                = errors.New("property not found")
	ErrUniqueItemsValidationFailed = errors.New("'uniqueItems' validation failed")
	ErrSchemaNotFound              = errors.New("schema not found")
)

Functions

This section is empty.

Types

type AdditionalItems

type AdditionalItems struct {
	*Schema
}

type AdditionalProperties

type AdditionalProperties struct {
	*Schema
}

type Bool

type Bool struct {
	Val         bool
	Default     bool
	Initialized bool
}

func (Bool) Bool

func (b Bool) Bool() bool

type DependencyMap

type DependencyMap struct {
	Names   map[string][]string
	Schemas map[string]*Schema
}

DependencyMap contains the dependencies defined within this schema. for a given dependency name, you can have either a schema or a list of property names

type ErrExtract

type ErrExtract struct {
	Field string
	Err   error
}

func (ErrExtract) Error

func (e ErrExtract) Error() string

type ErrInvalidFieldValue

type ErrInvalidFieldValue struct {
	Message string // may be empty. may be specified to give more context
	Name    string
	Value   reflect.Value
}

func (ErrInvalidFieldValue) Error

func (e ErrInvalidFieldValue) Error() string

type ErrInvalidReference

type ErrInvalidReference struct {
	Reference string
	Message   string
}

func (ErrInvalidReference) Error

func (e ErrInvalidReference) Error() string

type ErrMaxItemsValidationFailed

type ErrMaxItemsValidationFailed struct {
	Len      int
	MaxItems int
}

func (ErrMaxItemsValidationFailed) Error

type ErrMaxLengthValidationFailed

type ErrMaxLengthValidationFailed struct {
	Len       int
	MaxLength int
}

func (ErrMaxLengthValidationFailed) Error

type ErrMaxPropertiesValidationFailed

type ErrMaxPropertiesValidationFailed struct {
	Num int
	Max int
}

func (ErrMaxPropertiesValidationFailed) Error

type ErrMaximumValidationFailed

type ErrMaximumValidationFailed struct {
	Num       float64
	Max       float64
	Exclusive bool
}

func (ErrMaximumValidationFailed) Error

type ErrMinItemsValidationFailed

type ErrMinItemsValidationFailed struct {
	Len      int
	MinItems int
}

func (ErrMinItemsValidationFailed) Error

type ErrMinLengthValidationFailed

type ErrMinLengthValidationFailed struct {
	Len       int
	MinLength int
}

func (ErrMinLengthValidationFailed) Error

type ErrMinPropertiesValidationFailed

type ErrMinPropertiesValidationFailed struct {
	Num int
	Min int
}

func (ErrMinPropertiesValidationFailed) Error

type ErrMinimumValidationFailed

type ErrMinimumValidationFailed struct {
	Num       float64
	Min       float64
	Exclusive bool
}

func (ErrMinimumValidationFailed) Error

type ErrPatternValidationFailed

type ErrPatternValidationFailed struct {
	Str     string
	Pattern *regexp.Regexp
}

func (ErrPatternValidationFailed) Error

type ErrRequiredField

type ErrRequiredField struct {
	Name string
}

func (ErrRequiredField) Error

func (e ErrRequiredField) Error() string

type Format

type Format string
const (
	FormatDateTime Format = "date-time"
	FormatEmail    Format = "email"
	FormatHostname Format = "hostname"
	FormatIPv4     Format = "ipv4"
	FormatIPv6     Format = "ipv6"
	FormatURI      Format = "uri"
)

type Integer

type Integer struct {
	Val         int
	Initialized bool
}

type ItemSpec

type ItemSpec struct {
	TupleMode bool // If this is true, the positions mean something. if false, len(Schemas) should be 1, and we should apply the same schema validation to all elements
	Schemas   SchemaList
}

type Number

type Number struct {
	Val         float64
	Initialized bool
}

type PrimitiveType

type PrimitiveType int
const (
	UnspecifiedType PrimitiveType = iota
	NullType
	IntegerType
	StringType
	ObjectType
	ArrayType
	BooleanType
	NumberType
)

func (PrimitiveType) MarshalJSON

func (t PrimitiveType) MarshalJSON() ([]byte, error)

func (PrimitiveType) String

func (t PrimitiveType) String() string

func (*PrimitiveType) UnmarshalJSON

func (t *PrimitiveType) UnmarshalJSON(data []byte) error

type PrimitiveTypes

type PrimitiveTypes []PrimitiveType

func (PrimitiveTypes) Contains

func (ts PrimitiveTypes) Contains(p PrimitiveType) bool

func (PrimitiveTypes) Len

func (pt PrimitiveTypes) Len() int

func (PrimitiveTypes) Less

func (pt PrimitiveTypes) Less(i, j int) bool

func (PrimitiveTypes) Swap

func (pt PrimitiveTypes) Swap(i, j int)

func (*PrimitiveTypes) UnmarshalJSON

func (ts *PrimitiveTypes) UnmarshalJSON(data []byte) error

type Schema

type Schema struct {
	ID          string             `json:"id,omitempty"`
	Title       string             `json:"title,omitempty"`
	Description string             `json:"description,omitempty"`
	Default     interface{}        `json:"default,omitempty"`
	Type        PrimitiveTypes     `json:"type,omitempty"`
	SchemaRef   string             `json:"$schema,omitempty"`
	Definitions map[string]*Schema `json:"definitions,omitempty"`
	Reference   string             `json:"$ref,omitempty"`
	Format      Format             `json:"format,omitempty"`

	// NumericValidations
	MultipleOf       Number `json:"multipleOf,omitempty"`
	Minimum          Number `json:"minimum,omitempty"`
	Maximum          Number `json:"maximum,omitempty"`
	ExclusiveMinimum Bool   `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum Bool   `json:"exclusiveMaximum,omitempty"`

	// StringValidation
	MaxLength Integer        `json:"maxLength,omitempty"`
	MinLength Integer        `json:"minLength,omitempty"`
	Pattern   *regexp.Regexp `json:"pattern,omitempty"`

	// ArrayValidations
	AdditionalItems *AdditionalItems
	Items           *ItemSpec
	MinItems        Integer
	MaxItems        Integer
	UniqueItems     Bool

	// ObjectValidations
	MaxProperties        Integer                    `json:"maxProperties,omitempty"`
	MinProperties        Integer                    `json:"minProperties,omitempty"`
	Required             []string                   `json:"required,omitempty"`
	Dependencies         DependencyMap              `json:"dependencies,omitempty"`
	Properties           map[string]*Schema         `json:"properties,omitempty"`
	AdditionalProperties *AdditionalProperties      `json:"additionalProperties,omitempty"`
	PatternProperties    map[*regexp.Regexp]*Schema `json:"patternProperties,omitempty"`

	Enum   []interface{}          `json:"enum,omitempty"`
	AllOf  SchemaList             `json:"allOf,omitempty"`
	AnyOf  SchemaList             `json:"anyOf,omitempty"`
	OneOf  SchemaList             `json:"oneOf,omitempty"`
	Not    *Schema                `json:"not,omitempty"`
	Extras map[string]interface{} `json:"-"`
	// contains filtered or unexported fields
}

func New

func New() *Schema

func Read

func Read(in io.Reader) (*Schema, error)

func ReadFile

func ReadFile(f string) (*Schema, error)

func (Schema) BaseURL

func (s Schema) BaseURL() *url.URL

func (*Schema) Decode

func (s *Schema) Decode(in io.Reader) error

func (*Schema) Extract

func (s *Schema) Extract(m map[string]interface{}) error

func (Schema) IsPropRequired

func (s Schema) IsPropRequired(pname string) bool

func (*Schema) IsResolved

func (s *Schema) IsResolved() bool

func (Schema) MarshalJSON

func (s Schema) MarshalJSON() ([]byte, error)

func (*Schema) Resolve

func (s *Schema) Resolve(ctx interface{}) (ref *Schema, err error)

Resolve returns the schema after it has been resolved. If s.Reference is the empty string, the current schema is returned.

`ctx` is an optional context to resolve the reference with. If not specified, the root schema as returned by `Root` will be used.

func (Schema) ResolveURL

func (s Schema) ResolveURL(v string) (u *url.URL, err error)

func (*Schema) Root

func (s *Schema) Root() *Schema

func (Schema) Scope

func (s Schema) Scope() string

func (*Schema) UnmarshalJSON

func (s *Schema) UnmarshalJSON(data []byte) error

type SchemaList

type SchemaList []*Schema

func (*SchemaList) Extract

func (l *SchemaList) Extract(v interface{}) error

func (*SchemaList) ExtractIfPresent

func (l *SchemaList) ExtractIfPresent(m map[string]interface{}, name string) error

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL