schema

package
v0.11.5 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2022 License: MIT Imports: 11 Imported by: 0

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.

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 GuessType

func GuessType(data string) string

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.

func IsAnonymous

func IsAnonymous(field reflect.StructField) bool

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 Schema

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

func (s *Schema) ApplyDefaults(v any, post bool) error

func (*Schema) GuessType

func (s *Schema) GuessType(data string)

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