schema

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 8 Imported by: 0

README

Package schema

Пакет schema реализует генерацию и настройку JSON схем для структур Go с поддержкой кастомных генераторов и тегов валидации.

Types

CustomGenerator

Функция для кастомной генерации схемы по полю структуры.

customSchema

Внутренняя структура для управления реестром кастомных генераторов.

Methods:

Register(name string, f CustomGenerator)

Регистрирует кастомный генератор под именем.

Remove(name string)

Удаляет кастомный генератор по имени.

Schema

Псевдоним для *github.com/txix-open/jsonschema.Schema

Generator

Генератор схемы.

Methods:

NewGenerator()

Создать и инициализировать генератор с настройками:

  • FieldNameReflector — функция получения имени и признака обязательного поля,
  • FieldReflector — функция установки свойств поля,
  • ExpandedStruct: true,
  • DoNotReference: true.
Generate(obj any) Schema

Сгенерировать JSON-схему для переданной структуры.

Functions

func GetNameAndRequiredFlag(field reflect.StructField) (string, bool)
  • Возвращает имя поля (с учётом тега json) и флаг обязательности (наличие validate:"required").
  • Игнорирует неэкспортируемые поля.
func SetProperties(field reflect.StructField, s *jsonschema.Schema)
  • Извлекает из тегов поля schema, default, validate, schemaGen.
  • Устанавливает свойства схемы: Title, Description, Default, валидационные ограничения.
  • Если указан кастомный генератор (schemaGen), вызывает его.
Валидация и ограничения
  • Поддерживаются теги validate с опциями: max/lte, min/gte, oneof.
  • Ограничения применяются к типам string, integer, array.
  • Примеры:
    • max=10 ограничение максимальной длины/значения,
    • oneof='val1' 'val2' — перечисление допустимых значений.

Usage

Default usage flow
type MyConfig struct {
    Name string `json:"name" validate:"required,min=3" schema:"Имя,Описание поля"`
    Age  int    `json:"age" validate:"min=18,max=100" default:"18"`
}

gen := schema.NewGenerator()
jsonSchema := gen.Generate(MyConfig{})
// jsonSchema теперь содержит JSON-схему с ограничениями и описаниями

Documentation

Overview

Package schema provides JSON schema generation for Go structs with support for custom field properties, validation constraints, and tag-based configuration.

nolint:goconst,mnd

Index

Constants

This section is empty.

Variables

View Source
var CustomGenerators = &customSchema{
	mapSchema: make(map[string]CustomGenerator),
}

CustomGenerators is the global registry for custom schema generators. Use Register to add custom generators and Remove to delete them.

Functions

func GetFieldName

func GetFieldName(fieldType reflect.StructField) (string, bool)

GetFieldName extracts the JSON field name from a struct field. It checks the "json" tag for an explicit name; if absent, it uses the field name converted to camelCase (first letter lowercase). Returns the field name and true if the field should be included, or empty string and false if not.

func GetNameAndRequiredFlag

func GetNameAndRequiredFlag(field reflect.StructField) (string, bool)

GetNameAndRequiredFlag extracts the JSON field name and determines if the field is required. It checks the struct field's json tag for the name and validate tag for the "required" constraint. Returns the field name and a boolean indicating if the field is required. Unexported fields (those with non-empty PkgPath) are ignored.

func SetProperties

func SetProperties(field reflect.StructField, s *jsonschema.Schema)

SetProperties populates a JSON schema with properties from struct field tags. It processes the following tags:

  • "schema": sets Title and Description (format: "title,description")
  • "default": sets the Default value
  • "validate": sets validation constraints (min, max, oneof, etc.)
  • "schemaGen": applies a custom generator by name

Types

type CustomGenerator

type CustomGenerator func(field reflect.StructField, s *jsonschema.Schema)

CustomGenerator is a function type for customizing JSON schema generation. It receives the struct field and the schema to modify.

type Generator

type Generator struct {
	Reflector *jsonschema.Reflector
}

Generator creates JSON schemas from Go types with custom field reflection logic. It uses a jsonschema.Reflector configured with custom field name and property handlers.

func NewGenerator

func NewGenerator() *Generator

NewGenerator creates a new Generator instance with default configuration. The reflector is set to expand structs and avoid using references ($ref).

func (*Generator) Generate

func (g *Generator) Generate(obj any) Schema

Generate creates a JSON schema from the provided Go value. The obj should typically be a pointer to a struct. Returns the generated Schema representing the JSON schema document.

type Schema

type Schema *jsonschema.Schema

Schema is a pointer to a jsonschema.Schema, representing a JSON Schema document.

Jump to

Keyboard shortcuts

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