gojsonschema

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2019 License: Apache-2.0 Imports: 25 Imported by: 0

README

GoDoc Build Status

gojsonschema

Description

An implementation of JSON Schema for the Go programming language. Supports draft-04, draft-06 and draft-07.

References :

Installation

go get github.com/xeipuuv/gojsonschema

Dependencies :

Usage

Example

package main

import (
    "fmt"
    "github.com/xeipuuv/gojsonschema"
)

func main() {

    schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")
    documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json")

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        panic(err.Error())
    }

    if result.Valid() {
        fmt.Printf("The document is valid\n")
    } else {
        fmt.Printf("The document is not valid. see errors :\n")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}


Loaders

There are various ways to load your JSON data. In order to load your schemas and documents, first declare an appropriate loader :

  • Web / HTTP, using a reference :
loader := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json")
  • Local file, using a reference :
loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")

References use the URI scheme, the prefix (file://) and a full path to the file are required.

  • JSON strings :
loader := gojsonschema.NewStringLoader(`{"type": "string"}`)
  • Custom Go types :
m := map[string]interface{}{"type": "string"}
loader := gojsonschema.NewGoLoader(m)

And

type Root struct {
	Users []User `json:"users"`
}

type User struct {
	Name string `json:"name"`
}

...

data := Root{}
data.Users = append(data.Users, User{"John"})
data.Users = append(data.Users, User{"Sophia"})
data.Users = append(data.Users, User{"Bill"})

loader := gojsonschema.NewGoLoader(data)
Validation

Once the loaders are set, validation is easy :

result, err := gojsonschema.Validate(schemaLoader, documentLoader)

Alternatively, you might want to load a schema only once and process to multiple validations :

schema, err := gojsonschema.NewSchema(schemaLoader)
...
result1, err := schema.Validate(documentLoader1)
...
result2, err := schema.Validate(documentLoader2)
...
// etc ...

To check the result :

    if result.Valid() {
    	fmt.Printf("The document is valid\n")
    } else {
        fmt.Printf("The document is not valid. see errors :\n")
        for _, err := range result.Errors() {
        	// Err implements the ResultError interface
            fmt.Printf("- %s\n", err)
        }
    }

Loading local schemas

By default file and http(s) references to external schemas are loaded automatically via the file system or via http(s). An external schema can also be loaded using a SchemaLoader.

	sl := gojsonschema.NewSchemaLoader()
	loader1 := gojsonschema.NewStringLoader(`{ "type" : "string" }`)
	err := sl.AddSchema("http://some_host.com/string.json", loader1)

Alternatively if your schema already has an $id you can use the AddSchemas function

	loader2 := gojsonschema.NewStringLoader(`{
			"$id" : "http://some_host.com/maxlength.json",
			"maxLength" : 5
		}`)
	err = sl.AddSchemas(loader2)

The main schema should be passed to the Compile function. This main schema can then directly reference the added schemas without needing to download them.

	loader3 := gojsonschema.NewStringLoader(`{
		"$id" : "http://some_host.com/main.json",
		"allOf" : [
			{ "$ref" : "http://some_host.com/string.json" },
			{ "$ref" : "http://some_host.com/maxlength.json" }
		]
	}`)

	schema, err := sl.Compile(loader3)

	documentLoader := gojsonschema.NewStringLoader(`"hello world"`)

	result, err := schema.Validate(documentLoader)

It's also possible to pass a ReferenceLoader to the Compile function that references a loaded schema.

err = sl.AddSchemas(loader3)
schema, err := sl.Compile(gojsonschema.NewReferenceLoader("http://some_host.com/main.json"))

Schemas added by AddSchema and AddSchemas are only validated when the entire schema is compiled, unless meta-schema validation is used.

Using a specific draft

By default gojsonschema will try to detect the draft of a schema by using the $schema keyword and parse it in a strict draft-04, draft-06 or draft-07 mode. If $schema is missing, or the draft version is not explicitely set, a hybrid mode is used which merges together functionality of all drafts into one mode.

Autodectection can be turned off with the AutoDetect property. Specific draft versions can be specified with the Draft property.

sl := gojsonschema.NewSchemaLoader()
sl.Draft = gojsonschema.Draft7
sl.AutoDetect = false

If autodetection is on (default), a draft-07 schema can savely reference draft-04 schemas and vice-versa, as long as $schema is specified in all schemas.

Meta-schema validation

Schemas that are added using the AddSchema, AddSchemas and Compile can be validated against their meta-schema by setting the Validate property.

The following example will produce an error as multipleOf must be a number. If Validate is off (default), this error is only returned at the Compile step.

sl := gojsonschema.NewSchemaLoader()
sl.Validate = true
err := sl.AddSchemas(gojsonschema.NewStringLoader(`{
     $id" : "http://some_host.com/invalid.json",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "multipleOf" : true
}`))

Errors returned by meta-schema validation are more readable and contain more information, which helps significantly if you are developing a schema.

Meta-schema validation also works with a custom $schema. In case $schema is missing, or AutoDetect is set to false, the meta-schema of the used draft is used.

Working with Errors

The library handles string error codes which you can customize by creating your own gojsonschema.locale and setting it

gojsonschema.Locale = YourCustomLocale{}

However, each error contains additional contextual information.

Newer versions of gojsonschema may have new additional errors, so code that uses a custom locale will need to be updated when this happens.

err.Type(): string Returns the "type" of error that occurred. Note you can also type check. See below

Note: An error of RequiredType has an err.Type() return value of "required"

"required": RequiredError
"invalid_type": InvalidTypeError
"number_any_of": NumberAnyOfError
"number_one_of": NumberOneOfError
"number_all_of": NumberAllOfError
"number_not": NumberNotError
"missing_dependency": MissingDependencyError
"internal": InternalError
"const": ConstEror
"enum": EnumError
"array_no_additional_items": ArrayNoAdditionalItemsError
"array_min_items": ArrayMinItemsError
"array_max_items": ArrayMaxItemsError
"unique": ItemsMustBeUniqueError
"contains" : ArrayContainsError
"array_min_properties": ArrayMinPropertiesError
"array_max_properties": ArrayMaxPropertiesError
"additional_property_not_allowed": AdditionalPropertyNotAllowedError
"invalid_property_pattern": InvalidPropertyPatternError
"invalid_property_name":  InvalidPropertyNameError
"string_gte": StringLengthGTEError
"string_lte": StringLengthLTEError
"pattern": DoesNotMatchPatternError
"multiple_of": MultipleOfError
"number_gte": NumberGTEError
"number_gt": NumberGTError
"number_lte": NumberLTEError
"number_lt": NumberLTError
"condition_then" : ConditionThenError
"condition_else" : ConditionElseError

err.Value(): interface{} Returns the value given

err.Context(): gojsonschema.JsonContext Returns the context. This has a String() method that will print something like this: (root).firstName

err.Field(): string Returns the fieldname in the format firstName, or for embedded properties, person.firstName. This returns the same as the String() method on err.Context() but removes the (root). prefix.

err.Description(): string The error description. This is based on the locale you are using. See the beginning of this section for overwriting the locale with a custom implementation.

err.DescriptionFormat(): string The error description format. This is relevant if you are adding custom validation errors afterwards to the result.

err.Details(): gojsonschema.ErrorDetails Returns a map[string]interface{} of additional error details specific to the error. For example, GTE errors will have a "min" value, LTE will have a "max" value. See errors.go for a full description of all the error details. Every error always contains a "field" key that holds the value of err.Field()

Note in most cases, the err.Details() will be used to generate replacement strings in your locales, and not used directly. These strings follow the text/template format i.e.

{{.field}} must be greater than or equal to {{.min}}

The library allows you to specify custom template functions, should you require more complex error message handling.

gojsonschema.ErrorTemplateFuncs = map[string]interface{}{
	"allcaps": func(s string) string {
		return strings.ToUpper(s)
	},
}

Given the above definition, you can use the custom function "allcaps" in your localization templates:

{{allcaps .field}} must be greater than or equal to {{.min}}

The above error message would then be rendered with the field value in capital letters. For example:

"PASSWORD must be greater than or equal to 8"

Learn more about what types of template functions you can use in ErrorTemplateFuncs by referring to Go's text/template FuncMap type.

Formats

JSON Schema allows for optional "format" property to validate instances against well-known formats. gojsonschema ships with all of the formats defined in the spec that you can use like this:

{"type": "string", "format": "email"}

Not all formats defined in draft-07 are available. Implemented formats are:

  • date
  • time
  • date-time
  • hostname. Subdomains that start with a number are also supported, but this means that it doesn't strictly follow RFC1034 and has the implication that ipv4 addresses are also recognized as valid hostnames.
  • email. Go's email parser deviates slightly from RFC5322. Includes unicode support.
  • idn-email. Same caveat as email.
  • ipv4
  • ipv6
  • uri. Includes unicode support.
  • uri-reference. Includes unicode support.
  • iri
  • iri-reference
  • uri-template
  • uuid
  • regex. Go uses the RE2 engine and is not ECMA262 compatible.
  • json-pointer
  • relative-json-pointer

email, uri and uri-reference use the same validation code as their unicode counterparts idn-email, iri and iri-reference. If you rely on unicode support you should use the specific unicode enabled formats for the sake of interoperability as other implementations might not support unicode in the regular formats.

The validation code for uri, idn-email and their relatives use mostly standard library code. Go 1.5 and 1.6 contain some minor bugs with handling URIs and unicode. You are encouraged to use Go 1.7+ if you rely on these formats.

For repetitive or more complex formats, you can create custom format checkers and add them to gojsonschema like this:

// Define the format checker
type RoleFormatChecker struct {}

// Ensure it meets the gojsonschema.FormatChecker interface
func (f RoleFormatChecker) IsFormat(input interface{}) bool {

    asString, ok := input.(string)
    if ok == false {
        return false
    }

    return strings.HasPrefix("ROLE_", asString)
}

// Add it to the library
gojsonschema.FormatCheckers.Add("role", RoleFormatChecker{})

Now to use in your json schema:

{"type": "string", "format": "role"}

Another example would be to check if the provided integer matches an id on database:

JSON schema:

{"type": "integer", "format": "ValidUserId"}
// Define the format checker
type ValidUserIdFormatChecker struct {}

// Ensure it meets the gojsonschema.FormatChecker interface
func (f ValidUserIdFormatChecker) IsFormat(input interface{}) bool {

    asFloat64, ok := input.(float64) // Numbers are always float64 here
    if ok == false {
        return false
    }

    // XXX
    // do the magic on the database looking for the int(asFloat64)

    return true
}

// Add it to the library
gojsonschema.FormatCheckers.Add("ValidUserId", ValidUserIdFormatChecker{})

Formats can also be removed, for example if you want to override one of the formats that is defined by default.

gojsonschema.FormatCheckers.Remove("hostname")

Additional custom validation

After the validation has run and you have the results, you may add additional errors using Result.AddError. This is useful to maintain the same format within the resultset instead of having to add special exceptions for your own errors. Below is an example.

type AnswerInvalidError struct {
    gojsonschema.ResultErrorFields
}

func newAnswerInvalidError(context *gojsonschema.JsonContext, value interface{}, details gojsonschema.ErrorDetails) *AnswerInvalidError {
    err := AnswerInvalidError{}
    err.SetContext(context)
    err.SetType("custom_invalid_error")
    // it is important to use SetDescriptionFormat() as this is used to call SetDescription() after it has been parsed
    // using the description of err will be overridden by this.
    err.SetDescriptionFormat("Answer to the Ultimate Question of Life, the Universe, and Everything is {{.answer}}")
    err.SetValue(value)
    err.SetDetails(details)

    return &err
}

func main() {
    // ...
    schema, err := gojsonschema.NewSchema(schemaLoader)
    result, err := gojsonschema.Validate(schemaLoader, documentLoader)

    if true { // some validation
        jsonContext := gojsonschema.NewJsonContext("question", nil)
        errDetail := gojsonschema.ErrorDetails{
            "answer": 42,
        }
        result.AddError(
            newAnswerInvalidError(
                gojsonschema.NewJsonContext("answer", jsonContext),
                52,
                errDetail,
            ),
            errDetail,
        )
    }

    return result, err

}

This is especially useful if you want to add validation beyond what the json schema drafts can provide such business specific logic.

Uses

gojsonschema uses the following test suite :

https://github.com/json-schema/JSON-Schema-Test-Suite

Documentation

Index

Constants

View Source
const (
	STRING_NUMBER                     = "number"
	STRING_ARRAY_OF_STRINGS           = "array of strings"
	STRING_ARRAY_OF_SCHEMAS           = "array of schemas"
	STRING_SCHEMA                     = "valid schema"
	STRING_SCHEMA_OR_ARRAY_OF_STRINGS = "schema or array of strings"
	STRING_PROPERTIES                 = "properties"
	STRING_DEPENDENCY                 = "dependency"
	STRING_PROPERTY                   = "property"
	STRING_UNDEFINED                  = "undefined"
	STRING_CONTEXT_ROOT               = "(root)"
	STRING_ROOT_SCHEMA_PROPERTY       = "(root)"
)
View Source
const (
	KEY_SCHEMA                = "$schema"
	KEY_ID                    = "id"
	KEY_ID_NEW                = "$id"
	KEY_REF                   = "$ref"
	KEY_TITLE                 = "title"
	KEY_DESCRIPTION           = "description"
	KEY_TYPE                  = "type"
	KEY_ITEMS                 = "items"
	KEY_ADDITIONAL_ITEMS      = "additionalItems"
	KEY_PROPERTIES            = "properties"
	KEY_PATTERN_PROPERTIES    = "patternProperties"
	KEY_ADDITIONAL_PROPERTIES = "additionalProperties"
	KEY_PROPERTY_NAMES        = "propertyNames"
	KEY_DEFINITIONS           = "definitions"
	KEY_MULTIPLE_OF           = "multipleOf"
	KEY_MINIMUM               = "minimum"
	KEY_MAXIMUM               = "maximum"
	KEY_EXCLUSIVE_MINIMUM     = "exclusiveMinimum"
	KEY_EXCLUSIVE_MAXIMUM     = "exclusiveMaximum"
	KEY_MIN_LENGTH            = "minLength"
	KEY_MAX_LENGTH            = "maxLength"
	KEY_PATTERN               = "pattern"
	KEY_FORMAT                = "format"
	KEY_MIN_PROPERTIES        = "minProperties"
	KEY_MAX_PROPERTIES        = "maxProperties"
	KEY_DEPENDENCIES          = "dependencies"
	KEY_REQUIRED              = "required"
	KEY_MIN_ITEMS             = "minItems"
	KEY_MAX_ITEMS             = "maxItems"
	KEY_UNIQUE_ITEMS          = "uniqueItems"
	KEY_CONTAINS              = "contains"
	KEY_CONST                 = "const"
	KEY_ENUM                  = "enum"
	KEY_ONE_OF                = "oneOf"
	KEY_ANY_OF                = "anyOf"
	KEY_ALL_OF                = "allOf"
	KEY_NOT                   = "not"
	KEY_IF                    = "if"
	KEY_THEN                  = "then"
	KEY_ELSE                  = "else"
)
View Source
const (
	TYPE_ARRAY   = `array`
	TYPE_BOOLEAN = `boolean`
	TYPE_INTEGER = `integer`
	TYPE_NUMBER  = `number`
	TYPE_NULL    = `null`
	TYPE_OBJECT  = `object`
	TYPE_STRING  = `string`
)

Variables

View Source
var (
	// Locale is the default locale to use
	// Library users can overwrite with their own implementation
	Locale locale = DefaultLocale{}

	// ErrorTemplateFuncs allows you to define custom template funcs for use in localization.
	ErrorTemplateFuncs template.FuncMap
)
View Source
var (
	// Formatters holds the valid formatters, and is a public variable
	// so library users can add custom formatters
	FormatCheckers = FormatCheckerChain{
		// contains filtered or unexported fields
	}
)
View Source
var JSON_TYPES []string
View Source
var SCHEMA_TYPES []string

Functions

func NewRawLoader

func NewRawLoader(source interface{}) *jsonRawLoader

Types

type AdditionalPropertyNotAllowedError

type AdditionalPropertyNotAllowedError struct {
	ResultErrorFields
}

AdditionalPropertyNotAllowedError. ErrorDetails: property

type ArrayContainsError

type ArrayContainsError struct {
	ResultErrorFields
}

ArrayContainsError. ErrorDetails:

type ArrayMaxItemsError

type ArrayMaxItemsError struct {
	ResultErrorFields
}

ArrayMaxItemsError. ErrorDetails: max

type ArrayMaxPropertiesError

type ArrayMaxPropertiesError struct {
	ResultErrorFields
}

ArrayMaxPropertiesError. ErrorDetails: max

type ArrayMinItemsError

type ArrayMinItemsError struct {
	ResultErrorFields
}

ArrayMinItemsError. ErrorDetails: min

type ArrayMinPropertiesError

type ArrayMinPropertiesError struct {
	ResultErrorFields
}

ArrayMinPropertiesError. ErrorDetails: min

type ArrayNoAdditionalItemsError

type ArrayNoAdditionalItemsError struct {
	ResultErrorFields
}

ArrayNoAdditionalItemsError. ErrorDetails: -

type ConditionElseError

type ConditionElseError struct {
	ResultErrorFields
}

ConditionElseError. ErrorDetails: -

type ConditionThenError

type ConditionThenError struct {
	ResultErrorFields
}

ConditionThenError. ErrorDetails: -

type ConstError

type ConstError struct {
	ResultErrorFields
}

ConstError. ErrorDetails: allowed

type DateFormatChecker

type DateFormatChecker struct{}

func (DateFormatChecker) IsFormat

func (f DateFormatChecker) IsFormat(input interface{}) bool

type DateTimeFormatChecker

type DateTimeFormatChecker struct{}

DateTimeFormatChecker verifies date/time formats per RFC3339 5.6

Valid formats:

	Partial Time: HH:MM:SS
	Full Date: YYYY-MM-DD
	Full Time: HH:MM:SSZ-07:00
	Date Time: YYYY-MM-DDTHH:MM:SSZ-0700

Where
	YYYY = 4DIGIT year
	MM = 2DIGIT month ; 01-12
	DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year
	HH = 2DIGIT hour ; 00-23
	MM = 2DIGIT ; 00-59
	SS = 2DIGIT ; 00-58, 00-60 based on leap second rules
	T = Literal
	Z = Literal

Note: Nanoseconds are also suported in all formats

http://tools.ietf.org/html/rfc3339#section-5.6

func (DateTimeFormatChecker) IsFormat

func (f DateTimeFormatChecker) IsFormat(input interface{}) bool

type DefaultJSONLoaderFactory

type DefaultJSONLoaderFactory struct {
}

func (DefaultJSONLoaderFactory) New

type DefaultLocale

type DefaultLocale struct{}

DefaultLocale is the default locale for this package

func (DefaultLocale) AdditionalPropertyNotAllowed

func (l DefaultLocale) AdditionalPropertyNotAllowed() string

func (DefaultLocale) ArrayContains

func (l DefaultLocale) ArrayContains() string

func (DefaultLocale) ArrayMaxItems

func (l DefaultLocale) ArrayMaxItems() string

func (DefaultLocale) ArrayMaxProperties

func (l DefaultLocale) ArrayMaxProperties() string

func (DefaultLocale) ArrayMinItems

func (l DefaultLocale) ArrayMinItems() string

func (DefaultLocale) ArrayMinProperties

func (l DefaultLocale) ArrayMinProperties() string

func (DefaultLocale) ArrayNoAdditionalItems

func (l DefaultLocale) ArrayNoAdditionalItems() string

func (DefaultLocale) ArrayNotEnoughItems

func (l DefaultLocale) ArrayNotEnoughItems() string

func (DefaultLocale) CannotBeGT

func (l DefaultLocale) CannotBeGT() string

func (DefaultLocale) CannotBeUsedWithout

func (l DefaultLocale) CannotBeUsedWithout() string

func (DefaultLocale) ConditionElse

func (l DefaultLocale) ConditionElse() string

func (DefaultLocale) ConditionThen

func (l DefaultLocale) ConditionThen() string

If/Else

func (DefaultLocale) Const

func (l DefaultLocale) Const() string

func (DefaultLocale) DoesNotMatchFormat

func (l DefaultLocale) DoesNotMatchFormat() string

func (DefaultLocale) DoesNotMatchPattern

func (l DefaultLocale) DoesNotMatchPattern() string

func (DefaultLocale) Duplicated

func (l DefaultLocale) Duplicated() string

func (DefaultLocale) Enum

func (l DefaultLocale) Enum() string

func (DefaultLocale) ErrorFormat

func (l DefaultLocale) ErrorFormat() string

Replacement options: field, description, context, value

func (DefaultLocale) GreaterThanZero

func (l DefaultLocale) GreaterThanZero() string

func (DefaultLocale) HttpBadStatus

func (l DefaultLocale) HttpBadStatus() string

func (DefaultLocale) Internal

func (l DefaultLocale) Internal() string

func (DefaultLocale) InvalidPropertyName

func (l DefaultLocale) InvalidPropertyName() string

func (DefaultLocale) InvalidPropertyPattern

func (l DefaultLocale) InvalidPropertyPattern() string

func (DefaultLocale) InvalidType

func (l DefaultLocale) InvalidType() string

func (DefaultLocale) KeyCannotBeGreaterThan

func (l DefaultLocale) KeyCannotBeGreaterThan() string

func (DefaultLocale) KeyItemsMustBeOfType

func (l DefaultLocale) KeyItemsMustBeOfType() string

func (DefaultLocale) KeyItemsMustBeUnique

func (l DefaultLocale) KeyItemsMustBeUnique() string

func (DefaultLocale) MissingDependency

func (l DefaultLocale) MissingDependency() string

func (DefaultLocale) MultipleOf

func (l DefaultLocale) MultipleOf() string

func (DefaultLocale) MustBeGTEZero

func (l DefaultLocale) MustBeGTEZero() string

func (DefaultLocale) MustBeOfA

func (l DefaultLocale) MustBeOfA() string

func (DefaultLocale) MustBeOfAn

func (l DefaultLocale) MustBeOfAn() string

func (DefaultLocale) MustBeOfType

func (l DefaultLocale) MustBeOfType() string

func (DefaultLocale) MustBeValidFormat

func (l DefaultLocale) MustBeValidFormat() string

func (DefaultLocale) MustBeValidRegex

func (l DefaultLocale) MustBeValidRegex() string

func (DefaultLocale) NotAValidType

func (l DefaultLocale) NotAValidType() string

func (DefaultLocale) NumberAllOf

func (l DefaultLocale) NumberAllOf() string

func (DefaultLocale) NumberAnyOf

func (l DefaultLocale) NumberAnyOf() string

func (DefaultLocale) NumberGT

func (l DefaultLocale) NumberGT() string

func (DefaultLocale) NumberGTE

func (l DefaultLocale) NumberGTE() string

func (DefaultLocale) NumberLT

func (l DefaultLocale) NumberLT() string

func (DefaultLocale) NumberLTE

func (l DefaultLocale) NumberLTE() string

func (DefaultLocale) NumberNot

func (l DefaultLocale) NumberNot() string

func (DefaultLocale) NumberOneOf

func (l DefaultLocale) NumberOneOf() string

func (DefaultLocale) ParseError

func (l DefaultLocale) ParseError() string

Parse error

func (DefaultLocale) ReferenceMustBeCanonical

func (l DefaultLocale) ReferenceMustBeCanonical() string

func (DefaultLocale) RegexPattern

func (l DefaultLocale) RegexPattern() string

Schema validators

func (DefaultLocale) Required

func (l DefaultLocale) Required() string

func (DefaultLocale) StringGTE

func (l DefaultLocale) StringGTE() string

func (DefaultLocale) StringLTE

func (l DefaultLocale) StringLTE() string

func (DefaultLocale) Unique

func (l DefaultLocale) Unique() string

type DoesNotMatchFormatError

type DoesNotMatchFormatError struct {
	ResultErrorFields
}

DoesNotMatchFormatError. ErrorDetails: format

type DoesNotMatchPatternError

type DoesNotMatchPatternError struct {
	ResultErrorFields
}

DoesNotMatchPatternError. ErrorDetails: pattern

type Draft

type Draft int
const (
	Draft4 Draft = 4
	Draft6 Draft = 6
	Draft7 Draft = 7
	Hybrid Draft = math.MaxInt32
)

type EmailFormatChecker

type EmailFormatChecker struct{}

EmailFormatter verifies email address formats

func (EmailFormatChecker) IsFormat

func (f EmailFormatChecker) IsFormat(input interface{}) bool

type EnumError

type EnumError struct {
	ResultErrorFields
}

EnumError. ErrorDetails: allowed

type ErrorDetails

type ErrorDetails map[string]interface{}

ErrorDetails is a map of details specific to each error. While the values will vary, every error will contain a "field" value

type FileSystemJSONLoaderFactory

type FileSystemJSONLoaderFactory struct {
	// contains filtered or unexported fields
}

func (FileSystemJSONLoaderFactory) New

type FormatChecker

type FormatChecker interface {
	IsFormat(input interface{}) bool
}

FormatChecker is the interface all formatters added to FormatCheckerChain must implement

type FormatCheckerChain

type FormatCheckerChain struct {
	// contains filtered or unexported fields
}

FormatCheckerChain holds the formatters

func (*FormatCheckerChain) Add

Add adds a FormatChecker to the FormatCheckerChain The name used will be the value used for the format key in your json schema

func (*FormatCheckerChain) Has

func (c *FormatCheckerChain) Has(name string) bool

Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name

func (*FormatCheckerChain) IsFormat

func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool

IsFormat will check an input against a FormatChecker with the given name to see if it is the correct format

func (*FormatCheckerChain) Remove

func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain

Remove deletes a FormatChecker from the FormatCheckerChain (if it exists)

type HostnameFormatChecker

type HostnameFormatChecker struct{}

HostnameFormatChecker validates a hostname is in the correct format

func (HostnameFormatChecker) IsFormat

func (f HostnameFormatChecker) IsFormat(input interface{}) bool

type IPV4FormatChecker

type IPV4FormatChecker struct{}

IPV4FormatChecker verifies IP addresses in the ipv4 format

func (IPV4FormatChecker) IsFormat

func (f IPV4FormatChecker) IsFormat(input interface{}) bool

Credit: https://github.com/asaskevich/govalidator

type IPV6FormatChecker

type IPV6FormatChecker struct{}

IPV6FormatChecker verifies IP addresses in the ipv6 format

func (IPV6FormatChecker) IsFormat

func (f IPV6FormatChecker) IsFormat(input interface{}) bool

Credit: https://github.com/asaskevich/govalidator

type InternalError

type InternalError struct {
	ResultErrorFields
}

InternalError. ErrorDetails: error

type InvalidPropertyNameError

type InvalidPropertyNameError struct {
	ResultErrorFields
}

InvalidPopertyNameError. ErrorDetails: property

type InvalidPropertyPatternError

type InvalidPropertyPatternError struct {
	ResultErrorFields
}

InvalidPropertyPatternError. ErrorDetails: property, pattern

type InvalidTypeError

type InvalidTypeError struct {
	ResultErrorFields
}

InvalidTypeError. ErrorDetails: expected, given

type ItemsMustBeUniqueError

type ItemsMustBeUniqueError struct {
	ResultErrorFields
}

ItemsMustBeUniqueError. ErrorDetails: type, i, j

type JSONLoader

type JSONLoader interface {
	JsonSource() interface{}
	LoadJSON() (interface{}, error)
	JsonReference() (gojsonreference.JsonReference, error)
	LoaderFactory() JSONLoaderFactory
}

func NewBytesLoader

func NewBytesLoader(source []byte) JSONLoader

func NewGoLoader

func NewGoLoader(source interface{}) JSONLoader

func NewReaderLoader

func NewReaderLoader(source io.Reader) (JSONLoader, io.Reader)

func NewReferenceLoader

func NewReferenceLoader(source string) JSONLoader

NewReferenceLoader returns a JSON reference loader using the given source and the local OS file system.

func NewReferenceLoaderFileSystem

func NewReferenceLoaderFileSystem(source string, fs http.FileSystem) JSONLoader

NewReferenceLoaderFileSystem returns a JSON reference loader using the given source and file system.

func NewStringLoader

func NewStringLoader(source string) JSONLoader

func NewWriterLoader

func NewWriterLoader(source io.Writer) (JSONLoader, io.Writer)

type JSONLoaderFactory

type JSONLoaderFactory interface {
	New(source string) JSONLoader
}

type JSONPointerFormatChecker

type JSONPointerFormatChecker struct{}

JSONPointerFormatChecker validates a JSON Pointer per RFC6901

func (JSONPointerFormatChecker) IsFormat

func (f JSONPointerFormatChecker) IsFormat(input interface{}) bool

type JsonContext

type JsonContext struct {
	// contains filtered or unexported fields
}

JsonContext implements a persistent linked-list of strings

func NewJsonContext

func NewJsonContext(head string, tail *JsonContext) *JsonContext

func (*JsonContext) String

func (c *JsonContext) String(del ...string) string

String displays the context in reverse. This plays well with the data structure's persistent nature with Cons and a json document's tree structure.

type MissingDependencyError

type MissingDependencyError struct {
	ResultErrorFields
}

MissingDependencyError. ErrorDetails: dependency

type MultipleOfError

type MultipleOfError struct {
	ResultErrorFields
}

MultipleOfError. ErrorDetails: multiple

type NumberAllOfError

type NumberAllOfError struct {
	ResultErrorFields
}

NumberAllOfError. ErrorDetails: -

type NumberAnyOfError

type NumberAnyOfError struct {
	ResultErrorFields
}

NumberAnyOfError. ErrorDetails: -

type NumberGTEError

type NumberGTEError struct {
	ResultErrorFields
}

NumberGTEError. ErrorDetails: min

type NumberGTError

type NumberGTError struct {
	ResultErrorFields
}

NumberGTError. ErrorDetails: min

type NumberLTEError

type NumberLTEError struct {
	ResultErrorFields
}

NumberLTEError. ErrorDetails: max

type NumberLTError

type NumberLTError struct {
	ResultErrorFields
}

NumberLTError. ErrorDetails: max

type NumberNotError

type NumberNotError struct {
	ResultErrorFields
}

NumberNotError. ErrorDetails: -

type NumberOneOfError

type NumberOneOfError struct {
	ResultErrorFields
}

NumberOneOfError. ErrorDetails: -

type RegexFormatChecker

type RegexFormatChecker struct{}

RegexFormatChecker validates a regex is in the correct format

func (RegexFormatChecker) IsFormat

func (f RegexFormatChecker) IsFormat(input interface{}) bool

IsFormat implements FormatChecker interface.

type RelativeJSONPointerFormatChecker

type RelativeJSONPointerFormatChecker struct{}

RelativeJSONPointerFormatChecker validates a relative JSON Pointer is in the correct format

func (RelativeJSONPointerFormatChecker) IsFormat

func (f RelativeJSONPointerFormatChecker) IsFormat(input interface{}) bool

type RequiredError

type RequiredError struct {
	ResultErrorFields
}

RequiredError. ErrorDetails: property string

type Result

type Result struct {
	// contains filtered or unexported fields
}

func Validate

func Validate(ls JSONLoader, ld JSONLoader) (*Result, error)

func (*Result) AddError

func (v *Result) AddError(err ResultError, details ErrorDetails)

Add a fully filled error to the error set SetDescription() will be called with the result of the parsed err.DescriptionFormat()

func (*Result) Errors

func (v *Result) Errors() []ResultError

func (*Result) Valid

func (v *Result) Valid() bool

type ResultError

type ResultError interface {
	Field() string
	SetType(string)
	Type() string
	SetContext(*JsonContext)
	Context() *JsonContext
	SetDescription(string)
	Description() string
	SetDescriptionFormat(string)
	DescriptionFormat() string
	SetValue(interface{})
	Value() interface{}
	SetDetails(ErrorDetails)
	Details() ErrorDetails
	String() string
}

ResultError is the interface that library errors must implement

type ResultErrorFields

type ResultErrorFields struct {
	// contains filtered or unexported fields
}

ResultErrorFields holds the fields for each ResultError implementation. ResultErrorFields implements the ResultError interface, so custom errors can be defined by just embedding this type

func (*ResultErrorFields) Context

func (v *ResultErrorFields) Context() *JsonContext

func (*ResultErrorFields) Description

func (v *ResultErrorFields) Description() string

func (*ResultErrorFields) DescriptionFormat

func (v *ResultErrorFields) DescriptionFormat() string

func (*ResultErrorFields) Details

func (v *ResultErrorFields) Details() ErrorDetails

func (*ResultErrorFields) Field

func (v *ResultErrorFields) Field() string

Field outputs the field name without the root context i.e. firstName or person.firstName instead of (root).firstName or (root).person.firstName

func (*ResultErrorFields) SetContext

func (v *ResultErrorFields) SetContext(context *JsonContext)

func (*ResultErrorFields) SetDescription

func (v *ResultErrorFields) SetDescription(description string)

func (*ResultErrorFields) SetDescriptionFormat

func (v *ResultErrorFields) SetDescriptionFormat(descriptionFormat string)

func (*ResultErrorFields) SetDetails

func (v *ResultErrorFields) SetDetails(details ErrorDetails)

func (*ResultErrorFields) SetType

func (v *ResultErrorFields) SetType(errorType string)

func (*ResultErrorFields) SetValue

func (v *ResultErrorFields) SetValue(value interface{})

func (ResultErrorFields) String

func (v ResultErrorFields) String() string

func (*ResultErrorFields) Type

func (v *ResultErrorFields) Type() string

func (*ResultErrorFields) Value

func (v *ResultErrorFields) Value() interface{}

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

func NewSchema

func NewSchema(l JSONLoader) (*Schema, error)

func (*Schema) SetRootSchemaName

func (d *Schema) SetRootSchemaName(name string)

func (*Schema) Validate

func (v *Schema) Validate(l JSONLoader) (*Result, error)

type SchemaLoader

type SchemaLoader struct {
	AutoDetect bool
	Validate   bool
	Draft      Draft
	// contains filtered or unexported fields
}

func NewSchemaLoader

func NewSchemaLoader() *SchemaLoader

func (*SchemaLoader) AddSchema

func (sl *SchemaLoader) AddSchema(url string, loader JSONLoader) error

AddSchema adds a schema under the provided URL to the schema cache

func (*SchemaLoader) AddSchemas

func (sl *SchemaLoader) AddSchemas(loaders ...JSONLoader) error

AddSchemas adds an arbritrary amount of schemas to the schema cache. As this function does not require an explicit URL, every schema should contain an $id, so that it can be referenced by the main schema

func (*SchemaLoader) Compile

func (sl *SchemaLoader) Compile(rootSchema JSONLoader) (*Schema, error)

type StringLengthGTEError

type StringLengthGTEError struct {
	ResultErrorFields
}

StringLengthGTEError. ErrorDetails: min

type StringLengthLTEError

type StringLengthLTEError struct {
	ResultErrorFields
}

StringLengthLTEError. ErrorDetails: max

type TimeFormatChecker

type TimeFormatChecker struct{}

func (TimeFormatChecker) IsFormat

func (f TimeFormatChecker) IsFormat(input interface{}) bool

type URIFormatChecker

type URIFormatChecker struct{}

URIFormatChecker validates a URI with a valid Scheme per RFC3986

func (URIFormatChecker) IsFormat

func (f URIFormatChecker) IsFormat(input interface{}) bool

type URIReferenceFormatChecker

type URIReferenceFormatChecker struct{}

URIReferenceFormatChecker validates a URI or relative-reference per RFC3986

func (URIReferenceFormatChecker) IsFormat

func (f URIReferenceFormatChecker) IsFormat(input interface{}) bool

type URITemplateFormatChecker

type URITemplateFormatChecker struct{}

URITemplateFormatChecker validates a URI template per RFC6570

func (URITemplateFormatChecker) IsFormat

func (f URITemplateFormatChecker) IsFormat(input interface{}) bool

type UUIDFormatChecker

type UUIDFormatChecker struct{}

UUIDFormatChecker validates a UUID is in the correct format

func (UUIDFormatChecker) IsFormat

func (f UUIDFormatChecker) IsFormat(input interface{}) bool

Jump to

Keyboard shortcuts

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