schema

package
v1.14.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2023 License: MIT Imports: 10 Imported by: 3

Documentation

Overview

Package schema implements OpenAPI 3 compatible JSON Schema which can be generated from structs.

Example
type MyObject struct {
	ID     string  `doc:"Object ID" readOnly:"true"`
	Rate   float64 `doc:"Rate of change" minimum:"0"`
	Coords []int   `doc:"X,Y coordinates" minItems:"2" maxItems:"2"`
}

generated, err := Generate(reflect.TypeOf(MyObject{}))
if err != nil {
	panic(err)
}
fmt.Println(generated.Properties["id"].ReadOnly)
Output:

true

Index

Examples

Constants

View Source
const (
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeArray   = "array"
	TypeObject  = "object"
)

JSON Schema type constants

Variables

View Source
var ErrSchemaInvalid = errors.New("schema is invalid")

ErrSchemaInvalid is sent when there is a problem building the schema.

View Source
var GenerateInline bool = true

GenerateInline controls whether schemas are generated inline or as references to components. Inline schemas are the existing default behavior, but do not support recursive schemas. If you need recursive schemas, set this to false before generating any schemas.

Functions

func F

func F(value float64) *float64

F returns a pointer to the given float64. Useful helper function for pointer schema validators like Maximum or Minimum.

func I

func I(value uint64) *uint64

I returns a pointer to the given int. Useful helper function for pointer schema validators like MaxLength or MinItems.

Types

type Mode

type Mode int

Mode defines whether the schema is being generated for read or write mode. Read-only fields are dropped when in write mode, for example.

const (
	// ModeAll is for general purpose use and includes all fields.
	ModeAll Mode = iota
	// ModeRead is for HTTP HEAD & GET and will hide write-only fields.
	ModeRead
	// ModeWrite is for HTTP POST, PUT, PATCH, DELETE and will hide
	// read-only fields.
	ModeWrite
)

type NestedSchemaReference added in v1.14.0

type NestedSchemaReference struct {
	Name string
	Ref  string
	Type reflect.Type
}

type Schema

type Schema struct {
	Type                 string             `json:"type,omitempty"`
	Description          string             `json:"description,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	Properties           map[string]*Schema `json:"properties,omitempty"`
	AdditionalProperties interface{}        `json:"additionalProperties,omitempty"`
	PatternProperties    map[string]*Schema `json:"patternProperties,omitempty"`
	Required             []string           `json:"required,omitempty"`
	Format               string             `json:"format,omitempty"`
	Enum                 []interface{}      `json:"enum,omitempty"`
	Default              interface{}        `json:"default,omitempty"`
	Example              interface{}        `json:"example,omitempty"`
	Minimum              *float64           `json:"minimum,omitempty"`
	ExclusiveMinimum     *bool              `json:"exclusiveMinimum,omitempty"`
	Maximum              *float64           `json:"maximum,omitempty"`
	ExclusiveMaximum     *bool              `json:"exclusiveMaximum,omitempty"`
	MultipleOf           float64            `json:"multipleOf,omitempty"`
	MinLength            *uint64            `json:"minLength,omitempty"`
	MaxLength            *uint64            `json:"maxLength,omitempty"`
	Pattern              string             `json:"pattern,omitempty"`
	MinItems             *uint64            `json:"minItems,omitempty"`
	MaxItems             *uint64            `json:"maxItems,omitempty"`
	UniqueItems          bool               `json:"uniqueItems,omitempty"`
	MinProperties        *uint64            `json:"minProperties,omitempty"`
	MaxProperties        *uint64            `json:"maxProperties,omitempty"`
	AllOf                []*Schema          `json:"allOf,omitempty"`
	AnyOf                []*Schema          `json:"anyOf,omitempty"`
	OneOf                []*Schema          `json:"oneOf,omitempty"`
	Not                  *Schema            `json:"not,omitempty"`
	Nullable             bool               `json:"nullable,omitempty"`
	ReadOnly             bool               `json:"readOnly,omitempty"`
	WriteOnly            bool               `json:"writeOnly,omitempty"`
	Deprecated           bool               `json:"deprecated,omitempty"`
	ContentEncoding      string             `json:"contentEncoding,omitempty"`
	Ref                  string             `json:"$ref,omitempty"`
}

Schema represents a JSON Schema which can be generated from Go structs

func Generate

func Generate(t reflect.Type) (*Schema, error)

Generate creates a JSON schema for a Go type. Struct field tags can be used to provide additional metadata such as descriptions and validation.

func GenerateFromField

func GenerateFromField(f reflect.StructField, mode Mode, definedRefs map[string]NestedSchemaReference) (string, bool, *Schema, error)

GenerateFromField generates a schema for a single struct field. It returns the computed field name, whether it is optional, its schema, and any error which may have occurred.

func GenerateWithMode

func GenerateWithMode(t reflect.Type, mode Mode, schema *Schema, definedRefs map[string]NestedSchemaReference) (*Schema, error)

GenerateWithMode creates a JSON schema for a Go type. Struct field tags can be used to provide additional metadata such as descriptions and validation. The mode can be all, read, or write. In read or write mode any field that is marked as the opposite will be excluded, e.g. a write-only field would not be included in read mode. If a schema is given as input, add to it, otherwise creates a new schema.

func (*Schema) AddSchemaField added in v1.11.0

func (s *Schema) AddSchemaField()

AddSchemaField adds a $schema field if none is present, allowing the resource to be self-descriptive and enabling editor features like code completion / suggestions as you type & inline linting / validation.

func (*Schema) HasValidation

func (s *Schema) HasValidation() bool

HasValidation returns true if at least one validator is set on the schema. This excludes the schema's type but includes most other fields and can be used to trigger additional slow validation steps when needed.

func (*Schema) RemoveProperty

func (s *Schema) RemoveProperty(name string)

RemoveProperty removes a property by name from the schema, making sure to also remove it from the required property set if present.

Jump to

Keyboard shortcuts

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