Documentation
¶
Index ¶
Constants ¶
const (
YAMLPackage = "gopkg.in/yaml.v3"
)
Variables ¶
var ( ErrDurationIsEmpty = errors.New("duration default value must not be an empty string") ErrCannotConvertISO8601ToGoFormat = errors.New("could not convert duration from ISO8601 to Go format") ErrInvalidDefaultValue = errors.New("invalid default value") ErrCannotFindSlideToDump = errors.New("didn't find a slice to dump") ErrDefaultDurationIsNotAString = errors.New("duration default value must be a string") )
var (
ErrCannotDumpDefaultSlice = errors.New("cannot dump default slice")
)
var ErrCannotUnmarshalEnum = fmt.Errorf("cannot unmarshal enum")
var ErrConflictingImportAlias = errors.New(
"conflicting ImportAlias values for the same PackageName on SchemaMappings",
)
ErrConflictingImportAlias is returned when two SchemaMappings declare the same PackageName but different ImportAlias values. resolveImportAlias picks whichever it iterates over first, so the inconsistency would silently degrade to one alias winning and the other being ignored. Reject at New() so the conflict surfaces at the configuration boundary.
var ErrImportAliasCollision = errors.New("two packages would share an import name in one generated file")
ErrImportAliasCollision is returned when one generated file would import two packages under the same name, whether that name is an ImportAlias or derived from the last path segment. Go rejects the file, so generation stops and names both packages.
var ErrInvalidImportAlias = errors.New(
"invalid ImportAlias on SchemaMapping" +
" (must be a Go identifier other than a keyword, _, init, main or documentation)",
)
ErrInvalidImportAlias is returned when a SchemaMapping carries an ImportAlias that cannot name an import (see IsValidImportAlias). Caught at startup so a typo (e.g. "v 1") doesn't silently propagate into broken `import` statements.
var ErrInvalidStrictAdditionalPropertiesMode = errors.New(
"invalid StrictAdditionalProperties mode (expected one of: \"\", \"respect-schema\", \"strict\")",
)
ErrInvalidStrictAdditionalPropertiesMode is returned when Config holds a StrictAdditionalProperties value outside the documented set. Without this check a typo (e.g. "rstrict") would silently fall through the per-type switches and emit strict validators in modes the documented values would not select.
var ( // ErrPropertyNameNotRepresentable is returned for a property name that // encoding/json will not accept in a struct tag. Such a field cannot be // mapped at all — decode leaves it unset and encode emits a truncated key // — so the schema is refused rather than generated with a field that // silently does not round-trip. ErrPropertyNameNotRepresentable = errors.New( "property name cannot be represented in a Go struct tag that encoding/json accepts", ) )
var ErrUnexpectedVariantType = errors.New("oneOf variant: expected *codegen.NamedType from generator")
ErrUnexpectedVariantType is returned when the schema generator produces a Go type for a oneOf variant that is not the expected *codegen.NamedType. This indicates an internal generator inconsistency (e.g. an alias or inline map type was returned where a named struct was required).
var ErrUnknownCollisionStrategy = errors.New(
"invalid collision strategy (expected one of: \"\", \"positional\", \"qualify\")",
)
ErrUnknownCollisionStrategy is returned for a --collision-strategy value outside the known set. Caught at startup rather than silently falling back, since the choice decides generated identifiers.
Functions ¶
func IsSupportedFormat ¶
IsSupportedFormat reports whether the named JSON Schema `format` keyword has a built-in runtime validator. The check normalizes whitespace and case so that callers passing user input (e.g. CLI flag values) match the canonical keyword names.
func IsValidImportAlias ¶
IsValidImportAlias reports whether alias can name an import in generated code: a Go identifier, other than a keyword, the blank identifier `_` (a blank import cannot be referred to) and `init` (which Go reserves for functions). The alias is also the name the package's own files declare, so `main` and `documentation` are refused too: a package named main is a program, which can't be imported, and the go command skips the files of a package named documentation.
func SupportedFormats ¶
func SupportedFormats() []string
SupportedFormats returns the JSON Schema `format` keyword names that have a built-in runtime validator. The returned slice is a fresh copy; callers may sort or modify it without affecting subsequent calls.
Types ¶
type CollisionStrategy ¶
type CollisionStrategy string
CollisionStrategy selects how competing type names are resolved.
const ( // CollisionPositional appends a numeric suffix, so the schema processed // first keeps the bare name and later ones become Name_1, Name_2. The // default, and the historical behaviour. // // Note the binding depends on processing order: with several files each // declaring the same definition name, whichever is passed first owns the // bare identifier. Adding a file can therefore rebind an existing name. CollisionPositional CollisionStrategy = "positional" // CollisionQualify prefixes every definition with its owning schema's // root type name, so the identifier is derived from the schema alone and // does not depend on what else was generated alongside it. CollisionQualify CollisionStrategy = "qualify" )
func ParseCollisionStrategy ¶
func ParseCollisionStrategy(s string) (CollisionStrategy, error)
ParseCollisionStrategy validates a --collision-strategy value.
type Config ¶
type Config struct {
SchemaMappings []SchemaMapping
// ExtraImports allows the generator to pull imports from outside the standard library.
ExtraImports bool
// Capitalizations configures capitalized forms for identifiers which take precedence over the default algorithm.
Capitalizations []string
// ResolveExtensions configures file extensions to use when resolving schema names.
ResolveExtensions []string
// YAMLExtensions configures the file extensions that are recognized as YAML files.
YAMLExtensions []string
// DefaultPackageName configures the package to declare files under.
DefaultPackageName string
// DefaultOutputName configures the file to write.
DefaultOutputName string
// StructNameFromTitle configures the generator to use the schema title as the generated struct name.
StructNameFromTitle bool
// Warner provides a handler for warning messages.
Warner func(string)
// Tags specifies which struct tags should be generated.
Tags []string
// OnlyModels configures the generator to omit unmarshal methods, validations, anything but models.
OnlyModels bool
// MinSizedInts configures the generator to use the smallest int and uint types based on schema maximum values.
MinSizedInts bool
// OpenAPIIntFormats maps an integer's OpenAPI format, int32 or int64, to the Go integer type of that width.
// JSON Schema defines no integer formats, so it is off by default, and an integer is an int, as upstream
// generates it. MinSizedInts still wins where it applies.
OpenAPIIntFormats bool
// UseNumber decodes the numbers that untyped values hold, interface{} fields and the
// values in them, from JSON as json.Number, which keeps them exact, where encoding/json
// gives a float64, which loses integers beyond 2^53. Typed fields are decoded as before.
// YAML is unaffected: yaml.v3 decodes integers exactly.
UseNumber bool
// MinimalNames configures the generator to use the shortest identifier names possible.
MinimalNames bool
// Loader provides a schema loader for the generator.
Loader schemas.Loader
// Cache pre-populates the default loader's URL → *schemas.Schema cache.
// When non-nil and Loader is nil, New() builds the default cached loader
// using this map so that any `$ref` to a URL listed here resolves to the
// pre-loaded schema without an HTTP fetch (or a file lookup, depending on
// the URL scheme). Schemas inserted this way are loaded for resolution
// only — no Go code is emitted for them. Ignored when Loader is non-nil
// (build your own pre-populated CachedLoader and pass it via Loader if
// you need full control over the loader chain).
Cache map[string]*schemas.Schema
// When DisableOmitempty is set to true,
// an "omitempty" tag will never be present in generated struct fields.
// When DisableOmitempty is set to false,
// an "omitempty" tag will be present for all fields that are not required.
DisableOmitEmpty bool
// When DisableOmitZero is set to true,
// an "omitzero" tag will never be present in generated struct fields.
// When DisableOmitZero is set to false,
// an "omitzero" tag will be present for all fields that are not required.
DisableOmitZero bool
// DisableReadOnlyValidation configures the generator to omit validation for read-only fields.
DisableReadOnlyValidation bool
// DisableCustomTypesForMaps configures the generator to avoid creating a custom type for maps,
// and to use the map type directly.
DisableCustomTypesForMaps bool
// AliasSingleAllOfAnyOfRefs will convert types with a single nested anyOf or allOf ref type into a type alias.
AliasSingleAllOfAnyOfRefs bool
// CollisionStrategy decides how two schemas competing for one Go type
// name are resolved. Empty means CollisionPositional.
CollisionStrategy CollisionStrategy
// ExtensionTags maps a schema `x-` extension name onto the struct tag it
// is emitted as, e.g. {"x-dimension": "acme-dimension"}. Only
// extensions named here are emitted, and only onto the field that
// declares them; everything else stays out of the generated output.
//
// The mapping is explicit rather than automatic because a struct tag key
// is part of a package's contract with whatever reflects over it, so it
// is the consumer, not the schema author, that decides the name.
//
// A key already emitted through Tags or another mapping is refused by
// New: reflect reads only the first entry for a key, so the second would
// never be seen. On a field whose goJSONSchema.extraTags sets the key,
// that entry is kept and the extension is skipped with a warning.
ExtensionTags map[string]string
// ValidateNullTypes configures the generator to reject a property that is
// present with an explicit null where the schema's `type` excludes null,
// and likewise an array element, and the value of a declared type that is
// not an object, such as a named string or array. In YAML a document that
// is only null is not checked: yaml.v3 does not pass one to UnmarshalYAML.
//
// Off by default: telling null apart from an omitted field requires
// decoding the payload into a raw map first, so enabling this adds an
// Unmarshal method (and a second decode) to types that would otherwise
// carry none.
ValidateNullTypes bool
// FormatValidation controls runtime validation of JSON Schema `format`
// keywords (uuid, email, uri, uri-reference, hostname, regex). The zero
// value disables all format validation, preserving previous behavior.
FormatValidation FormatValidationConfig
// StrictAdditionalProperties controls runtime rejection of unknown
// fields during both `UnmarshalJSON` and `UnmarshalYAML`. The zero value
// (off) preserves the previous behavior where `additionalProperties:
// false` is silently ignored at unmarshal time.
StrictAdditionalProperties StrictAdditionalPropertiesMode
}
type FormatValidationConfig ¶
type FormatValidationConfig struct {
// Enabled turns on format validation. When false, no validation is generated
// regardless of AllowList.
Enabled bool
// AllowList restricts which formats receive runtime validation. When nil and
// Enabled is true, every supported format keyword is validated. When non-nil,
// only the listed format names are validated; unlisted formats fall back to
// plain `string` with no checks.
AllowList []string
}
FormatValidationConfig controls runtime validation of JSON Schema `format` keywords.
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
type SchemaMapping ¶
type SchemaMapping struct {
SchemaID string
PackageName string
RootType string
OutputName string
// ImportAlias overrides the import alias used in generated code for this
// mapping's PackageName, and is the name every file generated into that
// package declares, those of mappings without an alias included, so the
// two agree. When no mapping of the package sets one, both are derived
// from the last path segment via Package.Name() (the historical behavior).
// Set this when two mapped packages share a last path segment (e.g. both
// end in "/v1") to avoid an `import v1 "..." / import v1 "..."` collision,
// or when the package's name should differ from its directory's.
ImportAlias string
}
type StrictAdditionalPropertiesMode ¶
type StrictAdditionalPropertiesMode string
StrictAdditionalPropertiesMode selects how the generator enforces JSON Schema's `additionalProperties: false` keyword at unmarshal time. Enforcement is applied uniformly to JSON and YAML inputs, since both go through the same generated body.
const ( // StrictAdditionalPropertiesOff silently drops unknown fields from JSON // and YAML input. This is the historical (and zero-value) behavior. StrictAdditionalPropertiesOff StrictAdditionalPropertiesMode = "" // StrictAdditionalPropertiesRespectSchema rejects unknown fields (in // JSON or YAML input) for objects whose schema declares // `additionalProperties: false`. Other objects continue to accept and // silently drop unknown fields. StrictAdditionalPropertiesRespectSchema StrictAdditionalPropertiesMode = "respect-schema" // StrictAdditionalPropertiesStrict rejects unknown fields (in JSON or // YAML input) for every generated object type, regardless of whether // the schema declared `additionalProperties: false`. Skipped when the // schema specifies a typed additionalProperties (a catch-all field is // generated instead). StrictAdditionalPropertiesStrict StrictAdditionalPropertiesMode = "strict" )
func (StrictAdditionalPropertiesMode) IsValid ¶
func (m StrictAdditionalPropertiesMode) IsValid() bool
IsValid reports whether the mode is one of the documented values.
Source Files
¶
- anyof_parent.go
- conditional_discriminator.go
- config.go
- const_constants.go
- default_literal.go
- dependent_required.go
- deprecation.go
- element_validator.go
- enum_varnames.go
- extension_tags.go
- fidelity.go
- forbidden_sets.go
- formatter.go
- generate.go
- integer_bounds.go
- integral_numbers.go
- json_formatter.go
- marshal_empty.go
- name_scope.go
- nullable_branch.go
- oneof_discriminator.go
- oneof_primitive.go
- oneof_tryeach.go
- output.go
- presence_count.go
- primitive_composition.go
- ref_path.go
- schema_generator.go
- unevaluated_properties.go
- unique_items.go
- unmarshal_body.go
- use_number.go
- utils.go
- validator.go
- yaml_formatter.go