golang

package
v0.37.1 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 14 Imported by: 0

README

generator/golang

generator/golang is a library package for model-only generation:

  • OpenAPI schema/component models to Go model source.
  • Go reflection types to OpenAPI schema/component models.
  • No CLI, client generation, server generation, validation runtime, or generated runtime dependency.

OpenAPI To Go

Use RenderSchema for one schema or Generator.RenderSchemas for an ordered component map.

source, err := golang.RenderSchema("Pet", schemaProxy)
if err != nil {
    return err
}
fmt.Println(string(source))

RenderSchemas returns a *GeneratedFile with:

  • PackageName: generated package name.
  • Source: gofmt-formatted Go source.
  • SchemaMetadata: optional schema_metadata.go sidecar source when metadata sidecar generation is enabled.
  • Types: top-level generated type names and kinds.
  • Diagnostics: notable generator decisions.

Go To OpenAPI

Use SchemaFromType for one schema or SchemasFromTypes for a reusable component graph.

set, err := golang.SchemasFromTypes(reflect.TypeOf(Customer{}))
if err != nil {
    return err
}
root := set.Root
components := set.Components

SchemaSet.Root is the first requested root. SchemaSet.Roots contains every requested root keyed by generated type name. Named structs, registered interface unions, and reusable model shapes are emitted into SchemaSet.Components; nested named model references are rendered as #/components/schemas/... refs.

Nullable reflected values render with JSON Schema 2020-12 native nullability: type: [T, "null"] for direct schemas, or anyOf around $ref plus {type: "null"} for nullable component references. The generator does not emit OpenAPI 3.0 nullable: true.

Package-level graph helpers that need options use slice-based variants:

set, err := golang.SchemasFromTypesWithOptions(
    []reflect.Type{reflect.TypeOf(Customer{})},
    golang.WithOneOfTypes((*PaymentMethod)(nil), Card{}, Bank{}),
)

Custom scalar aliases can be mapped without adding methods to the type:

gen := golang.NewGenerator(
    golang.WithTypeSchema(reflect.TypeOf(CustomerID("")), customerIDSchema),
)

Metadata Hooks

Reflection metadata is layered from lightweight to exact:

  • Field tags for simple metadata: openapi:"format=uuid;nullable=false;readOnly;minLength=3;maxLength=4".
  • External registry overrides: WithTypeSchema, WithFieldSchema, and WithFieldSchemaByJSONName.
  • Type-level providers: OpenAPISchema() *base.SchemaProxy, dependency-free OpenAPISchemaMetadata() any, or legacy OpenAPISchemaYAML() string.

Use WithOpenAPITags(true) when generating Go models to include compact openapi tags for metadata that Go reflection cannot infer from type shape alone. Tags support format, title, description, nullable, readOnly, writeOnly, deprecated, scalar/object/array constraints, enum, and const.

Use WithSchemaMetadataSidecar(true) when generated models should carry exact source schemas for high-fidelity reflection. The generated sidecar is a separate schema_metadata.go source file containing typed Go data exposed through OpenAPISchemaMetadata() any, so model packages do not need to import libopenapi or carry escaped YAML strings just to preserve metadata.

Leave the metadata sidecar disabled when generated model source should stay lean and the reverse path only needs canonical Go-shape output. In that mode GeneratedFile.SchemaMetadata is nil and no schema_metadata.go file should be written. This is explicitly lossy for OpenAPI -> Go -> OpenAPI reconstruction: validation-only keywords, exact source ordering, and other non-Go-shape schema details may not be recreated from reflection alone.

For exact per-field shapes without modifying model source, use field schema overrides:

gen := golang.NewGenerator(
    golang.WithFieldSchema(reflect.TypeOf(BookingPayment{}), "Source", sourceSchema),
    golang.WithFieldSchemaByJSONName(reflect.TypeOf(BookingPayment{}), "status", statusSchema),
)

Polymorphism

OpenAPI oneOf renders as a typed union when:

  • The schema has an explicit discriminator.
  • The variants share an inferable required const discriminator property.
  • The variants share an optional const discriminator and WithOptionalConstDiscriminatorUnions(true) is enabled.

Ambiguous oneOf and all anyOf unions render as json.RawMessage wrappers. This keeps generated models dependency-free and avoids embedding validation behavior.

For Go reflection to OpenAPI, register interface variants:

gen := golang.NewGenerator(
    golang.WithOneOfTypes((*PaymentMethod)(nil), Card{}, Bank{}),
    golang.WithDiscriminatorMapping((*PaymentMethod)(nil), "object", map[string]string{
        "card": "#/components/schemas/Card",
        "bank": "#/components/schemas/Bank",
    }),
)

additionalProperties

Schema-valued additionalProperties renders as an AdditionalProperties map[string]T field with json:"-".

Generated objects with schema-valued additionalProperties also receive MarshalJSON and UnmarshalJSON methods. Known properties are encoded normally, and unknown properties round-trip through the additional-properties map.

Use WithAdditionalPropertiesMethods(false) when callers only want the struct field and will provide JSON behavior themselves.

Boolean additionalProperties is preserved when generating OpenAPI from Go/OpenAPI IR, but it does not create a Go field unless a schema value exists.

External References

External $ref values render as Go type names and emit DiagnosticExternalReference. By default, the type name is derived from the reference tail. Use WithExternalRefTypeResolver when an external reference should map to a different local type name.

Diagnostics

Diagnostics have a stable Code, plus Path and human-readable Message. Callers should branch on Code, not message text.

Current diagnostic codes:

  • DiagnosticComponentNameCollision
  • DiagnosticAdditionalPropertiesFalse
  • DiagnosticArrayContains
  • DiagnosticBooleanItems
  • DiagnosticConstKeyword
  • DiagnosticContentSchema
  • DiagnosticConditionalSchema
  • DiagnosticDependentRequired
  • DiagnosticDependentSchemas
  • DiagnosticDynamicReference
  • DiagnosticExternalReference
  • DiagnosticFieldNameCollision
  • DiagnosticImplicitType
  • DiagnosticMixedEnum
  • DiagnosticMultiTypeSchema
  • DiagnosticNotSchema
  • DiagnosticNullEnum
  • DiagnosticOptionalConstDiscriminator
  • DiagnosticPatternProperties
  • DiagnosticPrefixItems
  • DiagnosticPropertyNames
  • DiagnosticRootNameCollision
  • DiagnosticSchemaMetadata
  • DiagnosticStringEncoded
  • DiagnosticTypeNameCollision
  • DiagnosticUnevaluatedItems
  • DiagnosticUnevaluatedProperties
  • DiagnosticValidationKeyword

Diagnostics are intentionally not validation errors. They report lossy model-shape choices, unsupported validation-only keywords, naming collisions, and external reference assumptions.

Naming

The default naming path handles common Go initialisms such as ID, URL, UUID, CVC, IBAN, and JWT.

Inline/nested schema type names use _ as the default parent/child delimiter, for example Order_PaymentSource. Use WithNestedTypeNameDelimiter to change it; pass an empty string to produce compact names such as OrderPaymentSource.

Component names are resolved through a collision registry before refs are rendered, so colliding OpenAPI component keys such as user-id, user_id, and UserID produce stable Go names like UserID, UserID__2, and UserID__3, and local $ref fields point at the resolved names. The double underscore is reserved for collision suffixes, not ordinary nesting.

Use resolvers when project-specific naming is required:

  • WithTypeNameResolver
  • WithFieldNameResolver
  • WithEnumValueNameResolver
  • WithNameResolver as a broad fallback

Current Limits

  • Validation behavior belongs in libopenapi-validator, not generated models.
  • External $ref values render as Go type names and emit diagnostics; this package does not load or generate external dependency packages.
  • Tuple-like prefixItems render as []any.
  • patternProperties, conditional schemas, not, propertyNames, and dependent schemas are reported as diagnostics because they do not map cleanly to plain Go model fields.

Documentation

Overview

Package golang generates Go model types from OpenAPI schemas and generates OpenAPI schemas from Go runtime types.

The package is intentionally library-only. It does not provide a CLI, generated client or server code, a validation runtime, or runtime helper package. Callers provide libopenapi schema models or Go reflection types and receive generated Go source or OpenAPI schema proxies.

OpenAPI to Go model generation starts with RenderSchema for a single schema or Generator.RenderSchemas for component maps. The generated source is gofmt-formatted and diagnostics report schema shapes that do not map directly to plain Go model fields.

Go to OpenAPI generation starts with SchemaFromType for a single schema or Generator.SchemasFromTypes for a reusable component graph. Package-level graph helpers also have WithOptions variants for callers that do not need to keep a Generator instance. Named reflected structs, enums, and registered interface unions are emitted as components, nested named model references are rendered as component $refs, and SchemaSet.Roots exposes every requested root. WithTypeSchema maps reflected project scalar aliases to explicit OpenAPI schema models without adding methods to the scalar type, and WithFieldSchema/WithFieldSchemaByJSONName map individual struct fields to exact schema models while keeping the surrounding type reflected normally. Reflected nullable values use JSON Schema 2020-12 native nullability rather than OpenAPI 3.0 nullable: direct schemas use type arrays that include "null", and nullable component references use anyOf wrappers.

Reflection metadata is layered. Field-level openapi struct tags handle compact scalar metadata such as format, constraints, enum, const, readOnly/writeOnly/deprecated, and nullable overrides. SchemaProvider, SchemaMetadataProvider, and SchemaYAMLProvider methods handle exact type-level schemas. OpenAPI-to-Go generation can opt into WithOpenAPITags and WithSchemaMetadataSidecar to emit those hooks into a separate schema_metadata.go source file for higher-fidelity Go-to-OpenAPI round trips. Disabling the metadata sidecar leaves GeneratedFile.SchemaMetadata nil and keeps generated code leaner, but recreating the original OpenAPI input from reflected Go types becomes intentionally lossy.

Polymorphic oneOf schemas with an explicit discriminator, or an inferable required const discriminator, render as typed union wrappers. Ambiguous oneOf and anyOf schemas render as json.RawMessage wrappers so the generated model remains dependency-free and does not embed validation behavior.

Schema-valued additionalProperties can round-trip unknown JSON object fields through generated marshal/unmarshal methods. WithAdditionalPropertiesMethods disables those methods when callers want to provide JSON behavior themselves.

Inline schema type names use "_" as the default parent/child delimiter. WithNestedTypeNameDelimiter changes that delimiter, including to an empty string for compact names. Name collisions use "__" before the numeric suffix. Component names are collision-resolved before local refs are rendered, so generated fields point at the final Go type names.

Index

Examples

Constants

View Source
const (
	DiagnosticComponentNameCollision     = "componentNameCollision"
	DiagnosticChildSchema                = "childSchema"
	DiagnosticAdditionalPropertiesFalse  = "additionalPropertiesFalse"
	DiagnosticArrayContains              = "arrayContains"
	DiagnosticBooleanItems               = "booleanItems"
	DiagnosticConstKeyword               = "constKeyword"
	DiagnosticContentSchema              = "contentSchema"
	DiagnosticDependentRequired          = "dependentRequired"
	DiagnosticDependentSchemas           = "dependentSchemas"
	DiagnosticDynamicReference           = "dynamicReference"
	DiagnosticExternalReference          = "externalReference"
	DiagnosticFieldNameCollision         = "fieldNameCollision"
	DiagnosticConditionalSchema          = "conditionalSchema"
	DiagnosticImplicitType               = "implicitType"
	DiagnosticMixedEnum                  = "mixedEnum"
	DiagnosticMultiTypeSchema            = "multiTypeSchema"
	DiagnosticNotSchema                  = "notSchema"
	DiagnosticNullEnum                   = "nullEnum"
	DiagnosticOptionalConstDiscriminator = "optionalConstDiscriminator"
	DiagnosticPatternProperties          = "patternProperties"
	DiagnosticPrefixItems                = "prefixItems"
	DiagnosticPropertyNames              = "propertyNames"
	DiagnosticSchemaMetadata             = "schemaMetadata"
	DiagnosticStringEncoded              = "stringEncoded"
	DiagnosticTypeNameCollision          = "typeNameCollision"
	DiagnosticUnevaluatedItems           = "unevaluatedItems"
	DiagnosticRootNameCollision          = "rootNameCollision"
	DiagnosticUnevaluatedProperties      = "unevaluatedProperties"
	DiagnosticValidationKeyword          = "validationKeyword"
)
View Source
const SchemaMetadataFileName = "schema_metadata.go"

Variables

View Source
var (
	ErrNilSchema          = errors.New("nil schema")
	ErrNilType            = errors.New("nil type")
	ErrUnsupportedType    = errors.New("unsupported type")
	ErrUnsupportedMapKey  = errors.New("unsupported map key")
	ErrInvalidPackageName = errors.New("invalid package name")
)

Functions

func RenderSchema

func RenderSchema(name string, schema *highbase.SchemaProxy, opts ...Option) ([]byte, error)

RenderSchema renders a single OpenAPI schema as Go source.

Example
properties := orderedmap.New[string, *highbase.SchemaProxy]()
properties.Set("id", highbase.CreateSchemaProxy(&highbase.Schema{Type: []string{"string"}}))

schema := highbase.CreateSchemaProxy(&highbase.Schema{
	Type:       []string{"object"},
	Required:   []string{"id"},
	Properties: properties,
})
source, err := RenderSchema("Pet", schema, WithOptionalFieldsAsPointers(false))
if err != nil {
	panic(err)
}

fmt.Println(strings.Contains(string(source), "type Pet struct"))
fmt.Println(strings.Contains(string(source), "ID string `json:\"id\"`"))
Output:
true
true

func SchemaFromType

func SchemaFromType(t reflect.Type, opts ...Option) (*highbase.SchemaProxy, error)

SchemaFromType generates an OpenAPI schema for a Go reflection type.

func SchemaFromValue

func SchemaFromValue(value any, opts ...Option) (*highbase.SchemaProxy, error)

SchemaFromValue generates an OpenAPI schema for the runtime type of value.

Types

type Diagnostic

type Diagnostic struct {
	Code    string
	Path    string
	Message string
}

Diagnostic describes a notable generator decision.

type Discriminator

type Discriminator struct {
	PropertyName string
	Mapping      map[string]string
	Optional     bool
}

type ExternalRefResolver

type ExternalRefResolver func(ref string) string

ExternalRefResolver maps an external OpenAPI $ref to a Go type name. Returning an empty string falls back to deriving the type name from the reference tail.

type GeneratedFile

type GeneratedFile struct {
	PackageName    string
	Source         []byte
	SchemaMetadata *GeneratedSourceFile
	Types          []*GeneratedType
	Diagnostics    []Diagnostic
}

GeneratedFile contains Go source generated from OpenAPI schemas.

type GeneratedSourceFile

type GeneratedSourceFile struct {
	Name   string
	Source []byte
}

GeneratedSourceFile contains a named generated source file.

type GeneratedType

type GeneratedType struct {
	Name string
	Kind Kind
}

GeneratedType describes one top-level generated Go type.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator holds immutable configuration for code generation. Each public entry point runs against a fresh copy of this configuration (see run), so a configured Generator carries no per-invocation state and is safe to reuse for many documents and to share across goroutines.

func NewGenerator

func NewGenerator(opts ...Option) *Generator

NewGenerator creates a Go model generator.

func (*Generator) RenderSchema

func (g *Generator) RenderSchema(name string, schema *highbase.SchemaProxy) ([]byte, error)

RenderSchema renders a single OpenAPI schema as Go source using this generator.

func (*Generator) RenderSchemas

func (g *Generator) RenderSchemas(schemas *orderedmap.Map[string, *highbase.SchemaProxy]) (*GeneratedFile, error)

RenderSchemas renders an ordered map of OpenAPI schemas as one Go source file.

func (*Generator) SchemaFromType

func (g *Generator) SchemaFromType(t reflect.Type) (*highbase.SchemaProxy, error)

SchemaFromType generates an OpenAPI schema for a Go reflection type using this generator.

func (*Generator) SchemaFromValue

func (g *Generator) SchemaFromValue(value any) (*highbase.SchemaProxy, error)

SchemaFromValue generates an OpenAPI schema for the runtime type of value using this generator.

func (*Generator) SchemasFromTypes

func (g *Generator) SchemasFromTypes(types ...reflect.Type) (*SchemaSet, error)

SchemasFromTypes generates an OpenAPI component graph for Go reflection types using this generator.

Example
generator := NewGenerator()
set, err := generator.SchemasFromTypes(reflect.TypeOf(ExampleCustomer{}))
if err != nil {
	panic(err)
}

_, hasCustomer := set.Components.Get("ExampleCustomer")
_, hasAddress := set.Components.Get("ExampleBillingAddress")

fmt.Println(set.Root.GetReference())
fmt.Println(hasCustomer, hasAddress)
Output:
#/components/schemas/ExampleCustomer
true true

func (*Generator) SchemasFromValues

func (g *Generator) SchemasFromValues(values ...any) (*SchemaSet, error)

SchemasFromValues generates an OpenAPI component graph for runtime values using this generator.

type Kind

type Kind int
const (
	KindUnknown Kind = iota
	KindAny
	KindObject
	KindArray
	KindMap
	KindString
	KindInteger
	KindNumber
	KindBoolean
	KindRef
	KindEnum
	KindAllOf
	KindUnion
)

type NameResolver

type NameResolver func(string) string

NameResolver maps OpenAPI names to Go identifiers. Returning an empty string falls back to the generator's default naming.

type Option

type Option func(*Generator)

Option configures a Generator.

func WithAdditionalPropertiesMethods

func WithAdditionalPropertiesMethods(enabled bool) Option

WithAdditionalPropertiesMethods controls whether schema-valued additionalProperties generates JSON marshal/unmarshal methods that round-trip unknown fields through the AdditionalProperties map.

func WithDiscriminatorMapping

func WithDiscriminatorMapping(target any, property string, mapping map[string]string) Option

WithDiscriminatorMapping registers discriminator metadata for a reflected interface union.

func WithEnumConstants

func WithEnumConstants(enabled bool) Option

WithEnumConstants controls whether enum values generate Go constants.

func WithEnumValueNameResolver

func WithEnumValueNameResolver(resolver NameResolver) Option

WithEnumValueNameResolver sets a resolver for generated enum constant suffixes.

func WithExternalRefTypeResolver

func WithExternalRefTypeResolver(resolver ExternalRefResolver) Option

WithExternalRefTypeResolver sets a resolver for external OpenAPI $ref values when rendering Go type names. The resolver is not used for local component references.

func WithFieldNameResolver

func WithFieldNameResolver(resolver NameResolver) Option

WithFieldNameResolver sets a resolver for generated Go struct field names.

func WithFieldSchema

func WithFieldSchema(t reflect.Type, fieldName string, schema *highbase.SchemaProxy) Option

WithFieldSchema overrides reflected schema generation for a specific Go struct field name while keeping the surrounding model reflected normally.

func WithFieldSchemaByJSONName

func WithFieldSchemaByJSONName(t reflect.Type, jsonName string, schema *highbase.SchemaProxy) Option

WithFieldSchemaByJSONName overrides reflected schema generation for a specific JSON field name while keeping the surrounding model reflected normally.

func WithFormatMapping

func WithFormatMapping(format, goType, importPath string) Option

WithFormatMapping maps an OpenAPI string format to a Go type and optional import path.

func WithGenerateJSONTags

func WithGenerateJSONTags(enabled bool) Option

WithGenerateJSONTags controls generated json tags.

func WithGenerateYAMLTags

func WithGenerateYAMLTags(enabled bool) Option

WithGenerateYAMLTags controls generated yaml tags.

func WithGeneratedComment

func WithGeneratedComment(enabled bool) Option

WithGeneratedComment writes a standard generated-code comment.

func WithHeaderComment

func WithHeaderComment(text string) Option

WithHeaderComment writes a file header comment before the package clause.

func WithNameResolver

func WithNameResolver(resolver NameResolver) Option

WithNameResolver sets a broad fallback resolver for generated Go names.

func WithNestedTypeNameDelimiter

func WithNestedTypeNameDelimiter(delimiter string) Option

WithNestedTypeNameDelimiter sets the separator inserted between generated parent and child type names for inline schemas. The default is "_"; passing an empty delimiter restores compact names like ParentChild.

func WithNullableAsPointer

func WithNullableAsPointer(enabled bool) Option

WithNullableAsPointer controls whether nullable scalar fields render as pointers.

func WithOmitEmpty

func WithOmitEmpty(enabled bool) Option

WithOmitEmpty controls omitempty on optional generated tags.

func WithOneOfTypes

func WithOneOfTypes(target any, variants ...any) Option

WithOneOfTypes registers concrete variants for a Go interface when producing OpenAPI oneOf schemas from reflection.

func WithOpenAPITags

func WithOpenAPITags(enabled bool) Option

WithOpenAPITags controls whether generated struct fields include compact openapi tags for metadata that cannot be recovered from Go reflection alone.

func WithOptionalConstDiscriminatorUnions

func WithOptionalConstDiscriminatorUnions(enabled bool) Option

WithOptionalConstDiscriminatorUnions allows optional shared const discriminator properties to produce typed oneOf unions.

func WithOptionalFieldsAsPointers

func WithOptionalFieldsAsPointers(enabled bool) Option

WithOptionalFieldsAsPointers controls whether optional scalar fields render as pointers.

func WithPackageComment

func WithPackageComment(text string) Option

WithPackageComment writes a package doc comment before the package clause.

func WithPackageName

func WithPackageName(name string) Option

WithPackageName sets the generated Go package name.

func WithSchemaMetadataSidecar

func WithSchemaMetadataSidecar(enabled bool) Option

WithSchemaMetadataSidecar controls whether generated named types include a typed OpenAPISchemaMetadata sidecar. Enabling the sidecar preserves original OpenAPI schema fidelity for Go reflection round trips. Disabling it keeps the generated model code leaner, but OpenAPI -> Go -> OpenAPI reconstruction is intentionally lossy and falls back to Go type shape plus tags.

func WithTypeNameResolver

func WithTypeNameResolver(resolver NameResolver) Option

WithTypeNameResolver sets a resolver for generated Go type names.

func WithTypeSchema

func WithTypeSchema(t reflect.Type, schema *highbase.SchemaProxy) Option

WithTypeSchema overrides reflected schema generation for a specific Go type. This is useful for project scalar aliases that need a custom OpenAPI format, enum, or extension without implementing SchemaProvider on the type.

type SchemaIR

type SchemaIR struct {
	Name                 string
	Ref                  string
	Kind                 Kind
	DynamicRef           bool
	Format               string
	Description          string
	Title                string
	Nullable             bool
	Required             map[string]struct{}
	Properties           *orderedmap.Map[string, *SchemaIR]
	PatternProperties    *orderedmap.Map[string, *SchemaIR]
	Items                *SchemaIR
	PrefixItems          []*SchemaIR
	AdditionalProperties *SchemaIR
	AdditionalAllowed    *bool
	Enum                 []*yaml.Node
	Const                *yaml.Node
	AllOf                []*SchemaIR
	Union                *UnionIR
	Extensions           *orderedmap.Map[string, *yaml.Node]
	Source               *Source
	ReadOnly             bool
	WriteOnly            bool
	Deprecated           bool
	FieldMetadata        bool
	ExactSource          bool
	Comments             []string
	SourceSchema         *highbase.Schema
}

SchemaIR is the neutral hub both generation directions converge on. It carries two distinct channels. The shaping fields (Kind, Properties, Items, AdditionalProperties, Union, AllOf, Required, Nullable, Format, …) determine the generated Go type. SourceSchema carries the full original schema for the fidelity the IR does not model (validation keywords, conditionals, content, vocabulary, and so on); when ExactSource is set, openapiFromIR emits SourceSchema verbatim and ignores the shaping fields. FieldMetadata marks an IR whose SourceSchema should be rendered as $ref sibling metadata rather than inlined.

type SchemaMetadataProvider

type SchemaMetadataProvider interface {
	OpenAPISchemaMetadata() any
}

type SchemaProvider

type SchemaProvider interface {
	OpenAPISchema() *highbase.SchemaProxy
}

type SchemaSet

type SchemaSet struct {
	// Root is the first generated root schema, kept as a convenience for
	// single-root callers.
	Root *highbase.SchemaProxy
	// Roots contains every requested root schema keyed by generated type name.
	Roots *orderedmap.Map[string, *highbase.SchemaProxy]
	// Components contains reusable schemas discovered while walking the root
	// graph.
	Components *orderedmap.Map[string, *highbase.SchemaProxy]
	// Diagnostics reports schema features that required a lossy or notable
	// model-generation decision.
	Diagnostics []Diagnostic
}

SchemaSet contains OpenAPI schemas generated from one or more Go types.

func SchemasFromTypes

func SchemasFromTypes(types ...reflect.Type) (*SchemaSet, error)

SchemasFromTypes generates an OpenAPI component graph for Go reflection types.

func SchemasFromTypesWithOptions

func SchemasFromTypesWithOptions(types []reflect.Type, opts ...Option) (*SchemaSet, error)

SchemasFromTypesWithOptions generates an OpenAPI component graph for Go reflection types using generator options.

func SchemasFromValues

func SchemasFromValues(values ...any) (*SchemaSet, error)

SchemasFromValues generates an OpenAPI component graph for runtime values.

func SchemasFromValuesWithOptions

func SchemasFromValuesWithOptions(values []any, opts ...Option) (*SchemaSet, error)

SchemasFromValuesWithOptions generates an OpenAPI component graph for runtime values using generator options.

type SchemaYAMLProvider

type SchemaYAMLProvider interface {
	OpenAPISchemaYAML() string
}

type Source

type Source struct {
	Line   int
	Column int
	Ref    string
}

type UnionIR

type UnionIR struct {
	Kind          UnionKind
	Variants      []*SchemaIR
	Discriminator *Discriminator
	Strategy      UnionStrategy
	FromMultiType bool
}

type UnionKind

type UnionKind int
const (
	UnionNone UnionKind = iota
	UnionOneOf
	UnionAnyOf
)

type UnionStrategy

type UnionStrategy int
const (
	UnionRawMessage UnionStrategy = iota
	UnionDiscriminator
)

Jump to

Keyboard shortcuts

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