A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.
package jsonschema
import "github.com/nsgo-dev/game/pkg/tooling/jsonschema"Visão geral
Package jsonschema builds JSON Schemas (draft-07) from Go types and checks decoded YAML or JSON values against them, so editors and AI tools can complete and validate the YAML files a game's author writes.
Reflect walks a Go type the way its loader decodes it: struct fields become properties named by their yaml tags (or by Options.FieldName), structs become definitions shared through $ref, and a `schema` struct tag adds the constraints a type alone cannot say, such as `schema:"required,const=1"` or `schema:"enum=world|screen"`. Schema.Marshal writes deterministic, indented JSON, so a generated schema can be committed and checked for drift in CI, and Schema.Validate checks a value decoded from YAML or JSON against the keywords Reflect emits.
Índice
- Constantes
- func DecodeYAML(data []byte) (any, error)
- func PackageDocs(dir string) (map[string]string, error)
- type Field
- type Issue
- type Options
- type Property
- type Schema
- func False() *Schema
- func Reflect(t reflect.Type, opts Options) (*Schema, error)
- func True() *Schema
- func (s *Schema) Boolean() (value, ok bool)
- func (s *Schema) Marshal() ([]byte, error)
- func (s *Schema) MarshalJSON() ([]byte, error)
- func (s *Schema) Property(name string) *Schema
- func (s *Schema) Validate(v any) error
- func (s *Schema) ValidateYAML(data []byte) error
- type Type
- type ValidationError
Constantes
const Draft07 = "http://json-schema.org/draft-07/schema#"Draft07 is the $schema URI of the JSON Schema dialect this package writes, the newest one editors' YAML and JSON language servers support everywhere.
Funções
func DecodeYAML(data []byte) (any, error)DecodeYAML decodes the single YAML document in data into the plain values Validate takes; empty input decodes to nil.
func PackageDocs(dir string) (map[string]string, error)PackageDocs reads the doc comments of the Go package in dir (its non-test .go files) into the map Options.Docs takes: each type's comment under its name, and each struct field's under "Type.Field".
A field with no comment of its own takes the comment of the nearest commented field before it in the same struct when that comment names it, as in "X and Y are the world coordinates", so a pair documented together gets the same description. A comment's lines are joined into paragraphs separated by a blank line.
Tipos
type Field struct {
// Name is the key the field is written under.
Name string
// Skip leaves the field out of the schema, as a `yaml:"-"` tag does.
Skip bool
// Inline merges the fields of a struct-typed field into its parent, as a `yaml:",inline"` tag does.
Inline bool
}Field says how a loader reads one Go struct field: the key it is written under, whether it is skipped, and whether its fields are read as if they were the parent's.
func YAMLField(f reflect.StructField) FieldYAMLField maps a struct field the way go.yaml.in/yaml/v3 does: the first part of its `yaml` tag names it, "-" skips it, ",inline" merges it, and an untagged field is named by its Go name in lower case.
type Issue struct {
// Path is the JSON Pointer (RFC 6901) of the value within the document, "" for the document itself.
Path string
// Message says what is wrong with the value.
Message string
}Issue is one place where a value breaks its schema.
func (i Issue) String() stringString returns the issue as "<path>: <message>", with "/" standing for the document itself.
type Options struct {
// ID is the $id URI the schema is published at; empty omits it.
ID string
// Title is the root schema's title; empty omits it.
Title string
// Description is the root schema's description; empty uses Docs for the root type.
Description string
// FieldName maps a struct field to the key its loader reads; nil uses YAMLField.
FieldName func(reflect.StructField) Field
// Docs maps a Go type's name ("SceneDoc") or a type's field ("SceneDoc.Name") to the description written for it, as PackageDocs reads them from a package's doc comments.
Docs map[string]string
// Types overrides the schema of a Go type wherever it appears, for types a loader reads in a form their kind does not say, such as a time.Duration written "1.5s". Each use gets its own copy.
Types map[reflect.Type]*Schema
// AllowUnknown leaves additionalProperties unset on struct schemas, for loaders that ignore keys they do not know; by default unknown keys are refused, as a decoder with KnownFields(true) does.
AllowUnknown bool
// FirstFieldWins keeps the first field written under a key and leaves out later ones, for loaders that bind each key to the first field claiming it, such as datatable's CSV and JSON loaders; by default two fields under one key are an error.
FirstFieldWins bool
}Options configures Reflect.
type Property struct {
// Name is the key the property is written under.
Name string
// Schema constrains the property's value.
Schema *Schema
}Property is one named entry of an object schema's properties, kept in declaration order so a generated schema reads in the same order as the Go type.
type Schema struct {
// Schema is the $schema dialect URI, set on a root schema only.
Schema string
// ID is the $id URI a root schema is published at.
ID string
// Ref is a $ref to "#" or "#/definitions/<name>" in the root schema. Validate ignores the other keywords of a schema with a Ref, as draft-07 does.
Ref string
// Title is a short human-readable name.
Title string
// Description is shown by editors on hover and completion.
Description string
// Types lists the allowed JSON types; empty allows every type.
Types []Type
// Const, when non-nil, is the only allowed value.
Const any
// Enum, when non-empty, lists the allowed values.
Enum []any
// Minimum and Maximum bound a number inclusively.
Minimum, Maximum *float64
// ExclusiveMinimum and ExclusiveMaximum bound a number exclusively.
ExclusiveMinimum, ExclusiveMaximum *float64
// MinLength is the fewest characters (Unicode code points) a string may have.
MinLength *int
// MinItems is the fewest elements an array may have.
MinItems *int
// MaxItems is the most elements an array may have.
MaxItems *int
// Items constrains every element of an array.
Items *Schema
// Properties constrains an object's named properties, in declaration order.
Properties []Property
// Required lists the properties an object must have.
Required []string
// AdditionalProperties constrains the properties not named in Properties; False refuses them and nil allows any.
AdditionalProperties *Schema
// AllOf lists schemas a value must match all of; Reflect uses it to give a $ref a description of its own.
AllOf []*Schema
// Definitions holds the named subschemas that Ref points at, set on a root schema only.
Definitions map[string]*Schema
// contains filtered or unexported fields
}Schema is a JSON Schema draft-07 document or subschema, limited to the keywords Reflect emits and Validate checks.
The zero Schema accepts every value; True and False return the boolean schemas.
func False() *SchemaFalse returns the boolean schema that accepts no value; as AdditionalProperties it refuses unknown keys.
func Reflect(t reflect.Type, opts Options) (*Schema, error)Reflect builds the schema of values of type t as a loader with opts reads them:
- a struct is an object whose properties are its exported fields, named by opts.FieldName, with unknown keys refused unless opts.AllowUnknown; a struct other than the root is written once under definitions and referenced by $ref;
- a pointer is the schema of what it points to;
- a slice or array is an array of its elements' schema;
- a map with string keys is an object whose values all have the map's element schema;
- strings, booleans, integers and floats map to their JSON types, integers and float32 bounded by the range their Go type holds, and an interface accepts any value.
A field's `schema` struct tag adds what its Go type cannot say, as comma-separated entries: required, const=V, enum=A|B|C, minimum=N, maximum=N, exclusiveMinimum=N, exclusiveMaximum=N, minLength=N and minItems=N, where const and enum values are read as the field's type. Channels, functions, complex numbers and maps with keys other than strings are refused.
func (s *Schema) Boolean() (value, ok bool)Boolean reports whether s is a boolean schema (True or False) and, if so, its value.
func (s *Schema) Marshal() ([]byte, error)Marshal returns s as JSON indented by two spaces with a trailing newline. Keys keep a fixed order (properties in declaration order, definitions sorted by name), so the same schema always yields the same bytes.
func (s *Schema) MarshalJSON() ([]byte, error)MarshalJSON writes s as compact JSON with the key order Marshal documents.
func (s *Schema) Property(name string) *SchemaProperty returns the schema of the named property, or nil when s has none by that name.
func (s *Schema) Validate(v any) errorValidate checks v against s and returns a *ValidationError listing every issue, or nil when v conforms.
v is a value as encoding/json or ValidateYAML decodes one into an interface: nil, bool, string, a number of any Go numeric kind, []any, and map[string]any. $refs resolve against s, so call Validate on the root schema.
func (s *Schema) ValidateYAML(data []byte) errorValidateYAML decodes the single YAML document in data as a YAML language server reads it (mapping keys as strings, timestamps and binary as strings, merge keys merged, a key repeated within one mapping refused) and validates it with Validate. A document that is not YAML, or that holds more than one document, is an error that is not a *ValidationError.
type Type stringType is a JSON Schema primitive type name.
const (
// TypeObject is a mapping with string keys.
TypeObject Type = "object"
// TypeArray is a sequence.
TypeArray Type = "array"
// TypeString is a string.
TypeString Type = "string"
// TypeNumber is any number, integral or not.
TypeNumber Type = "number"
// TypeInteger is a number with no fractional part.
TypeInteger Type = "integer"
// TypeBoolean is true or false.
TypeBoolean Type = "boolean"
// TypeNull is null.
TypeNull Type = "null"
)type ValidationError struct {
// Issues holds one entry per broken keyword, never empty.
Issues []Issue
}ValidationError lists every place a value breaks its schema, in document order.
func (e *ValidationError) Error() stringError returns the issues one per line.