codegen

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package codegen generates Go code from parsed OpenAPI specs.

Package codegen provides extension handling for OpenAPI x- properties.

Index

Constants

View Source
const (
	ServerTypeStdHTTP = "std-http"
	ServerTypeChi     = "chi"
	ServerTypeEcho    = "echo"
	ServerTypeEchoV4  = "echo/v4"
	ServerTypeGin     = "gin"
	ServerTypeGorilla = "gorilla"
	ServerTypeFiber   = "fiber"
	ServerTypeIris    = "iris"
)

ServerType constants for supported server frameworks.

View Source
const (
	// ExtTypeOverride specifies an external type to use instead of generating one.
	// Format: "TypeName" or "TypeName;import/path" or "TypeName;alias import/path"
	ExtTypeOverride = "x-oapi-codegen-type-override"

	// ExtNameOverride overrides the generated field name.
	ExtNameOverride = "x-oapi-codegen-name-override"

	// ExtTypeNameOverride overrides the generated type name.
	ExtTypeNameOverride = "x-oapi-codegen-type-name-override"

	// ExtSkipOptionalPointer skips pointer wrapping for optional fields.
	ExtSkipOptionalPointer = "x-oapi-codegen-skip-optional-pointer"

	// ExtJSONIgnore excludes the field from JSON marshaling (json:"-").
	ExtJSONIgnore = "x-oapi-codegen-json-ignore"

	// ExtOmitEmpty explicitly controls the omitempty JSON tag.
	ExtOmitEmpty = "x-oapi-codegen-omitempty"

	// ExtOmitZero adds omitzero to the JSON tag (Go 1.24+ encoding/json/v2).
	ExtOmitZero = "x-oapi-codegen-omitzero"

	// ExtEnumVarNames overrides the generated enum constant names.
	ExtEnumVarNames = "x-oapi-codegen-enum-varnames"

	// ExtDeprecatedReason provides a deprecation reason for documentation.
	ExtDeprecatedReason = "x-oapi-codegen-deprecated-reason"

	// ExtOrder controls field ordering in generated structs.
	ExtOrder = "x-oapi-codegen-order"
)

Extension names - new naming convention with x-oapi-codegen- prefix

Variables

View Source
var DefaultTypeMapping = TypeMapping{
	Integer: FormatMapping{
		Default: SimpleTypeSpec{Type: "int"},
		Formats: map[string]SimpleTypeSpec{
			"int":    {Type: "int"},
			"int8":   {Type: "int8"},
			"int16":  {Type: "int16"},
			"int32":  {Type: "int32"},
			"int64":  {Type: "int64"},
			"uint":   {Type: "uint"},
			"uint8":  {Type: "uint8"},
			"uint16": {Type: "uint16"},
			"uint32": {Type: "uint32"},
			"uint64": {Type: "uint64"},
		},
	},
	Number: FormatMapping{
		Default: SimpleTypeSpec{Type: "float32"},
		Formats: map[string]SimpleTypeSpec{
			"float":  {Type: "float32"},
			"double": {Type: "float64"},
		},
	},
	Boolean: FormatMapping{
		Default: SimpleTypeSpec{Type: "bool"},
	},
	String: FormatMapping{
		Default: SimpleTypeSpec{Type: "string"},
		Formats: map[string]SimpleTypeSpec{
			"byte":      {Type: "[]byte"},
			"email":     {Type: "Email", Template: "email.tmpl"},
			"date":      {Type: "Date", Template: "date.tmpl"},
			"date-time": {Type: "time.Time", Import: "time"},
			"json":      {Type: "json.RawMessage", Import: "encoding/json"},
			"uuid":      {Type: "UUID", Template: "uuid.tmpl"},
			"binary":    {Type: "File", Template: "file.tmpl"},
		},
	},
}

DefaultTypeMapping provides the default OpenAPI type/format to Go type mappings.

Functions

func ComputeBodyNameTag

func ComputeBodyNameTag(contentType string) string

ComputeBodyNameTag returns the name tag for a content type.

func ComputeSchemaNames

func ComputeSchemaNames(schemas []*SchemaDescriptor, converter *NameConverter, contentTypeNamer *ContentTypeShortNamer)

ComputeSchemaNames assigns StableName and ShortName to each schema descriptor. StableName is deterministic from the path; ShortName is a friendly alias. If a schema has a TypeNameOverride extension, that takes precedence over computed names.

func DefaultContentTypeShortNames

func DefaultContentTypeShortNames() map[string][]string

DefaultContentTypeShortNames returns the default content type to short name mappings. The defaults match the patterns in DefaultContentTypes().

func DefaultContentTypes

func DefaultContentTypes() []string

DefaultContentTypes returns the default list of content type patterns. These match common JSON and YAML media types.

func DefaultParamExplode

func DefaultParamExplode(location string) bool

DefaultParamExplode returns the default explode value for a parameter location.

func DefaultParamStyle

func DefaultParamStyle(location string) string

DefaultParamStyle returns the default style for a parameter location.

func FormatTagsMap

func FormatTagsMap(tags map[string]string) string

FormatTagsMap formats a tag map into a struct tag string. Tags are sorted alphabetically by name for deterministic output.

func Generate

func Generate(doc libopenapi.Document, specData []byte, cfg Configuration) (string, error)

Generate produces Go code from the parsed OpenAPI document. specData is the raw spec bytes used to embed the spec in the generated code.

func GenerateAdditionalPropertiesCode

func GenerateAdditionalPropertiesCode(typeName string, fields []StructField, addPropsType string) (string, error)

GenerateAdditionalPropertiesCode generates Get/Set + MarshalJSON/UnmarshalJSON for structs with additionalProperties.

func GenerateApplyDefaultsCode

func GenerateApplyDefaultsCode(typeName string, fields []StructField) (string, bool, error)

GenerateApplyDefaultsCode generates the ApplyDefaults method for a struct. Returns the generated code and whether the reflect package is needed.

func GenerateEnumFromInfo

func GenerateEnumFromInfo(info *EnumInfo) string

GenerateEnumFromInfo generates an enum type with const values using pre-computed EnumInfo. The EnumInfo contains sanitized names and the prefix decision from collision detection.

func GenerateStruct

func GenerateStruct(name string, fields []StructField, doc string, tagGen *StructTagGenerator) string

GenerateStruct generates a struct type definition.

func GenerateStructWithAdditionalProps

func GenerateStructWithAdditionalProps(name string, fields []StructField, addPropsType string, doc string, tagGen *StructTagGenerator) string

GenerateStructWithAdditionalProps generates a struct with AdditionalProperties field and custom marshal/unmarshal methods.

func GenerateTypeAlias

func GenerateTypeAlias(name, targetType, doc string) string

GenerateTypeAlias generates a type alias definition.

func GenerateUnionCode

func GenerateUnionCode(cfg UnionTypeConfig) (string, error)

GenerateUnionCode generates all code for a union type using the union template.

func IsGoKeyword

func IsGoKeyword(s string) bool

IsGoKeyword returns true if s is a Go keyword.

func IsMediaTypeJSON

func IsMediaTypeJSON(contentType string) bool

IsMediaTypeJSON returns true if the content type is a JSON media type.

func LowercaseFirstCharacter

func LowercaseFirstCharacter(s string) string

LowercaseFirstCharacter lowercases only the first character of a string. Example: "UserName" -> "userName"

func MediaTypeToCamelCase

func MediaTypeToCamelCase(mediaType string) string

MediaTypeToCamelCase converts a media type to a CamelCase identifier.

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase converts a string to CamelCase (PascalCase). It treats hyphens, underscores, spaces, and other non-alphanumeric characters as word separators. Example: "user-name" -> "UserName", "user_id" -> "UserId"

func ToGoIdentifier

func ToGoIdentifier(s string) string

ToGoIdentifier converts a string to a valid Go identifier. It converts to CamelCase, handles leading digits, and avoids Go keywords.

func UppercaseFirstCharacter

func UppercaseFirstCharacter(s string) string

UppercaseFirstCharacter uppercases only the first character of a string. Example: "userName" -> "UserName"

func ValidateParamStyle

func ValidateParamStyle(style, location string) error

ValidateParamStyle validates that a style is supported for a location. Returns an error if the combination is invalid.

Types

type AllOfMergeError

type AllOfMergeError struct {
	SchemaName   string
	PropertyName string
	Type1        string
	Type2        string
}

AllOfMergeError represents a conflict when merging allOf schemas.

func (AllOfMergeError) Error

func (e AllOfMergeError) Error() string

type ClientGenerator

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

ClientGenerator generates client code from operation descriptors.

func NewClientGenerator

func NewClientGenerator(schemaIndex map[string]*SchemaDescriptor, generateSimple bool, modelsPackage *ModelsPackage, rp RuntimePrefixes, typeMapping TypeMapping) (*ClientGenerator, error)

NewClientGenerator creates a new client generator. modelsPackage can be nil if models are in the same package. rp holds the package prefixes for runtime sub-packages; all empty when embedded.

func (*ClientGenerator) GenerateBase

func (g *ClientGenerator) GenerateBase() (string, error)

GenerateBase generates the base client types and helpers.

func (*ClientGenerator) GenerateClient

func (g *ClientGenerator) GenerateClient(ops []*OperationDescriptor) (string, error)

GenerateClient generates the complete client code.

func (*ClientGenerator) GenerateInterface

func (g *ClientGenerator) GenerateInterface(data SenderTemplateData) (string, error)

GenerateInterface generates the ClientInterface.

func (*ClientGenerator) GenerateMethods

func (g *ClientGenerator) GenerateMethods(data SenderTemplateData) (string, error)

GenerateMethods generates the Client methods.

func (*ClientGenerator) GenerateParamTypes

func (g *ClientGenerator) GenerateParamTypes(ops []*OperationDescriptor) (string, error)

GenerateParamTypes generates the parameter struct types.

func (*ClientGenerator) GenerateRequestBodyTypes

func (g *ClientGenerator) GenerateRequestBodyTypes(ops []*OperationDescriptor) string

GenerateRequestBodyTypes generates type aliases for request bodies.

func (*ClientGenerator) GenerateRequestBuilders

func (g *ClientGenerator) GenerateRequestBuilders(data SenderTemplateData) (string, error)

GenerateRequestBuilders generates the request builder functions.

func (*ClientGenerator) GenerateSimple

func (g *ClientGenerator) GenerateSimple(data SenderTemplateData) (string, error)

GenerateSimple generates the SimpleClient with typed responses.

type CodeBuilder

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

CodeBuilder helps construct Go code fragments.

func NewCodeBuilder

func NewCodeBuilder() *CodeBuilder

NewCodeBuilder creates a new code builder.

func (*CodeBuilder) BlankLine

func (b *CodeBuilder) BlankLine()

BlankLine writes an empty line.

func (*CodeBuilder) Dedent

func (b *CodeBuilder) Dedent()

Dedent decreases indentation.

func (*CodeBuilder) Indent

func (b *CodeBuilder) Indent()

Indent increases indentation.

func (*CodeBuilder) Line

func (b *CodeBuilder) Line(format string, args ...any)

Line writes a line with current indentation.

func (*CodeBuilder) Raw

func (b *CodeBuilder) Raw(s string)

Raw writes raw text without indentation or newline.

func (*CodeBuilder) String

func (b *CodeBuilder) String() string

String returns the built code.

type CodegenContext

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

CodegenContext is a centralized tracker for imports needed during code generation. Code at any depth can call its registration methods; the final output assembly queries it to collect all required imports.

func NewCodegenContext

func NewCodegenContext() *CodegenContext

NewCodegenContext creates a new CodegenContext.

func (*CodegenContext) AddImport

func (c *CodegenContext) AddImport(path string)

AddImport records an import path needed by the generated code.

func (*CodegenContext) AddImportAlias

func (c *CodegenContext) AddImportAlias(path, alias string)

AddImportAlias records an import path with an alias.

func (*CodegenContext) AddImports

func (c *CodegenContext) AddImports(imports map[string]string)

AddImports adds multiple imports from a map[path]alias.

func (*CodegenContext) AddJSONImport

func (c *CodegenContext) AddJSONImport()

AddJSONImport adds encoding/json import.

func (*CodegenContext) AddJSONImports

func (c *CodegenContext) AddJSONImports()

AddJSONImports adds encoding/json and fmt imports.

func (*CodegenContext) AddTemplateImports

func (c *CodegenContext) AddTemplateImports(imports []templates.Import)

AddTemplateImports adds all imports declared by the given template import slices.

func (*CodegenContext) HasRuntimePackage

func (c *CodegenContext) HasRuntimePackage() bool

HasRuntimePackage returns true when an external runtime package is configured.

func (*CodegenContext) Imports

func (c *CodegenContext) Imports() map[string]string

Imports returns the collected imports as a map[path]alias.

func (*CodegenContext) RuntimeHelpersPrefix

func (c *CodegenContext) RuntimeHelpersPrefix() string

RuntimeHelpersPrefix returns the helpers sub-package prefix (e.g., "helpers.").

func (*CodegenContext) RuntimeParamsPrefix

func (c *CodegenContext) RuntimeParamsPrefix() string

RuntimeParamsPrefix returns the params sub-package prefix (e.g., "params.").

func (*CodegenContext) RuntimeTypesPrefix

func (c *CodegenContext) RuntimeTypesPrefix() string

RuntimeTypesPrefix returns the types sub-package prefix (e.g., "types.").

func (*CodegenContext) SetRuntimePrefixes

func (c *CodegenContext) SetRuntimePrefixes(params, types, helpers string)

SetRuntimePrefixes sets the package prefixes for the three runtime sub-packages. When non-empty, generated code references runtime helpers via these prefixes (e.g., "params.", "types.", "helpers.") instead of embedding them.

type Configuration

type Configuration struct {
	// PackageName which will be used in all generated files
	PackageName string `yaml:"package"`
	// Output specifies the output file path
	Output string `yaml:"output"`
	// Generation controls which parts of the code are generated
	Generation GenerationOptions `yaml:"generation,omitempty"`
	// OutputOptions controls filtering of operations and schemas
	OutputOptions OutputOptions `yaml:"output-options,omitempty"`
	// TypeMapping allows customizing OpenAPI type/format to Go type mappings
	TypeMapping TypeMapping `yaml:"type-mapping,omitempty"`
	// NameMangling configures how OpenAPI names are converted to Go identifiers
	NameMangling NameMangling `yaml:"name-mangling,omitempty"`
	// NameSubstitutions allows direct overrides of generated names
	NameSubstitutions NameSubstitutions `yaml:"name-substitutions,omitempty"`
	// ImportMapping maps external spec file paths to Go package import paths.
	// The value is either a bare import path or "alias importpath".
	// Examples:
	//   "../common/api.yaml": "github.com/org/project/common"         # alias auto-generated via hash
	//   "../common/api.yaml": "common github.com/org/project/common"  # explicit alias "common"
	// Use "-" as the value to indicate types should be in the current package.
	ImportMapping map[string]string `yaml:"import-mapping,omitempty"`
	// ContentTypes is a list of regexp patterns for media types to generate models for.
	// Only request/response bodies with matching content types will have types generated.
	// Defaults to common JSON and YAML types if not specified.
	ContentTypes []string `yaml:"content-types,omitempty"`
	// ContentTypeShortNames maps short names to lists of content type regex patterns.
	// Example: {"JSON": ["^application/json$", "^application/.*\\+json$"]}
	// These are used when generating response/request type names like "FindPetsJSONResponse".
	ContentTypeShortNames map[string][]string `yaml:"content-type-short-names,omitempty"`
	// StructTags configures how struct tags are generated for fields.
	// By default, only json tags are generated.
	StructTags StructTagsConfig `yaml:"struct-tags,omitempty"`
}

func (*Configuration) ApplyDefaults

func (c *Configuration) ApplyDefaults()

ApplyDefaults merges user configuration on top of default values.

type ContentTypeMatcher

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

ContentTypeMatcher checks if content types match configured patterns.

func NewContentTypeMatcher

func NewContentTypeMatcher(patterns []string) *ContentTypeMatcher

NewContentTypeMatcher creates a matcher from a list of regexp patterns. Invalid patterns are silently ignored.

func (*ContentTypeMatcher) Matches

func (m *ContentTypeMatcher) Matches(contentType string) bool

Matches returns true if the content type matches any of the configured patterns.

type ContentTypeShortNamer

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

ContentTypeShortNamer resolves content types to short names for use in type names.

func NewContentTypeShortNamer

func NewContentTypeShortNamer(mappings map[string][]string) *ContentTypeShortNamer

NewContentTypeShortNamer creates a short namer from configuration. The mappings map short names (e.g., "JSON") to lists of regexp patterns.

func (*ContentTypeShortNamer) ShortName

func (n *ContentTypeShortNamer) ShortName(contentType string) string

ShortName returns the short name for a content type, or a fallback derived from the content type.

type DiscriminatorInfo

type DiscriminatorInfo struct {
	// PropertyName is the JSON property used as the discriminator (e.g., "petType").
	PropertyName string

	// Mapping maps discriminator values to $ref paths.
	// For explicit mappings, keys are the values from the spec's discriminator.mapping.
	// For implicit mappings, keys are inferred from $ref schema names.
	Mapping map[string]string

	// IsExplicit is true when the spec includes a discriminator.mapping section.
	IsExplicit bool
}

DiscriminatorInfo holds discriminator metadata extracted from the OpenAPI spec.

type EnumInfo

type EnumInfo struct {
	// TypeName is the Go type name for the enum (e.g., "Color", "Status").
	TypeName string
	// BaseType is the Go base type (e.g., "string", "int").
	BaseType string
	// Values are the raw enum values from the spec.
	Values []string
	// CustomNames are user-provided constant names from x-oapi-codegen-enum-var-names.
	// May be nil or shorter than Values.
	CustomNames []string
	// Doc is the enum's documentation string.
	Doc string
	// SchemaPath is the key used to look up this EnumInfo (schema path string).
	SchemaPath string

	// PrefixTypeName indicates whether constant names should be prefixed with the type name.
	// Set by resolveEnumCollisions when collisions are detected.
	PrefixTypeName bool
	// SanitizedNames are the computed constant name suffixes (without type prefix).
	// Populated by computeEnumConstantNames.
	SanitizedNames []string
}

EnumInfo holds all the information needed to generate an enum's constant block. It is populated during the pre-pass phase of code generation.

type Extensions

type Extensions struct {
	TypeOverride        *TypeOverride // External type to use
	NameOverride        string        // Override field name
	TypeNameOverride    string        // Override generated type name
	SkipOptionalPointer *bool         // Skip pointer for optional fields
	JSONIgnore          *bool         // Exclude from JSON
	OmitEmpty           *bool         // Control omitempty
	OmitZero            *bool         // Control omitzero
	EnumVarNames        []string      // Override enum constant names
	DeprecatedReason    string        // Deprecation reason
	Order               *int          // Field ordering
}

Extensions holds parsed extension values for a schema or property.

func ParseExtensions

func ParseExtensions(extensions *orderedmap.Map[string, *yaml.Node], path string) (*Extensions, error)

ParseExtensions extracts extension values from a schema's extensions map. It supports both new (x-oapi-codegen-*) and legacy (x-go-*) extension names, logging deprecation warnings for legacy names.

type ExternalImport

type ExternalImport struct {
	Alias string // Short alias for use in generated code (e.g., "ext_a1b2c3")
	Path  string // Full import path (e.g., "github.com/org/project/common")
}

ExternalImport represents an external package import with its alias.

type FormatMapping

type FormatMapping struct {
	Default SimpleTypeSpec            `yaml:"default"`
	Formats map[string]SimpleTypeSpec `yaml:"formats,omitempty"`
}

FormatMapping defines the default Go type and format-specific overrides.

type GenerationOptions

type GenerationOptions struct {
	// Server specifies which server framework to generate code for.
	// Supported values: "std-http"
	// Empty string (default) means no server code is generated.
	Server string `yaml:"server,omitempty"`

	// Client enables generation of the HTTP client.
	// When true, generates a base Client that returns *http.Response.
	Client bool `yaml:"client,omitempty"`

	// SimpleClient enables generation of the SimpleClient wrapper.
	// SimpleClient wraps the base Client with typed responses for
	// operations that have unambiguous response types.
	// Requires Client to also be enabled.
	SimpleClient bool `yaml:"simple-client,omitempty"`

	// WebhookInitiator enables generation of webhook initiator code (sends webhook requests).
	// Generates a framework-agnostic client that takes the full target URL per-call.
	WebhookInitiator bool `yaml:"webhook-initiator,omitempty"`

	// WebhookReceiver enables generation of webhook receiver code (receives webhook requests).
	// Generates framework-specific handler functions. Requires Server to be set.
	WebhookReceiver bool `yaml:"webhook-receiver,omitempty"`

	// CallbackInitiator enables generation of callback initiator code (sends callback requests).
	// Generates a framework-agnostic client that takes the full target URL per-call.
	CallbackInitiator bool `yaml:"callback-initiator,omitempty"`

	// CallbackReceiver enables generation of callback receiver code (receives callback requests).
	// Generates framework-specific handler functions. Requires Server to be set.
	CallbackReceiver bool `yaml:"callback-receiver,omitempty"`

	// ModelsPackage specifies an external package containing the model types.
	// When set, models are NOT generated locally - instead, generated code
	// imports and references types from this package.
	// Example: {path: "github.com/org/project/models"}
	ModelsPackage *ModelsPackage `yaml:"models-package,omitempty"`

	// RuntimePackage specifies an external package containing runtime helpers
	// (Date, Nullable, param style/bind functions, marshalForm, etc.).
	// When set, these helpers are NOT embedded in the generated output —
	// instead, generated code imports and references them from this package.
	// Generate the runtime package with --generate-runtime or GenerateRuntime().
	RuntimePackage *RuntimePackageConfig `yaml:"runtime-package,omitempty"`
}

GenerationOptions controls which parts of the code are generated.

type ImportResolver

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

ImportResolver resolves external references to Go package imports.

func NewImportResolver

func NewImportResolver(importMapping map[string]string) (*ImportResolver, error)

NewImportResolver creates an ImportResolver from the configuration's import mapping. Each mapping value is either a bare import path (alias is auto-generated via hash) or "alias importpath" (explicit alias). The special value "-" means current package.

func (*ImportResolver) AllImports

func (r *ImportResolver) AllImports() []ExternalImport

AllImports returns all external imports sorted by alias.

func (*ImportResolver) Resolve

func (r *ImportResolver) Resolve(specPath string) *ExternalImport

Resolve looks up an external spec file path and returns its import info. Returns nil if the path is not in the mapping.

type InitiatorGenerator

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

InitiatorGenerator generates initiator (sender) code from operation descriptors. It is parameterized by prefix to support both webhooks and callbacks.

func NewInitiatorGenerator

func NewInitiatorGenerator(prefix string, schemaIndex map[string]*SchemaDescriptor, generateSimple bool, modelsPackage *ModelsPackage, rp RuntimePrefixes, typeMapping TypeMapping) (*InitiatorGenerator, error)

NewInitiatorGenerator creates a new initiator generator. rp holds the package prefixes for runtime sub-packages; all empty when embedded.

func (*InitiatorGenerator) GenerateBase

func (g *InitiatorGenerator) GenerateBase(ops []*OperationDescriptor) (string, error)

GenerateBase generates the base initiator types and helpers.

func (*InitiatorGenerator) GenerateInitiator

func (g *InitiatorGenerator) GenerateInitiator(ops []*OperationDescriptor) (string, error)

GenerateInitiator generates the complete initiator code.

func (*InitiatorGenerator) GenerateInterface

func (g *InitiatorGenerator) GenerateInterface(data SenderTemplateData) (string, error)

GenerateInterface generates the InitiatorInterface.

func (*InitiatorGenerator) GenerateMethods

func (g *InitiatorGenerator) GenerateMethods(data SenderTemplateData) (string, error)

GenerateMethods generates the Initiator methods.

func (*InitiatorGenerator) GenerateParamTypes

func (g *InitiatorGenerator) GenerateParamTypes(ops []*OperationDescriptor) (string, error)

GenerateParamTypes generates the parameter struct types.

func (*InitiatorGenerator) GenerateRequestBodyTypes

func (g *InitiatorGenerator) GenerateRequestBodyTypes(ops []*OperationDescriptor) string

GenerateRequestBodyTypes generates type aliases for request bodies.

func (*InitiatorGenerator) GenerateRequestBuilders

func (g *InitiatorGenerator) GenerateRequestBuilders(data SenderTemplateData) (string, error)

GenerateRequestBuilders generates the request builder functions.

func (*InitiatorGenerator) GenerateSimple

func (g *InitiatorGenerator) GenerateSimple(data SenderTemplateData) (string, error)

GenerateSimple generates the SimpleInitiator with typed responses.

type ModelsPackage

type ModelsPackage struct {
	// Path is the import path for the models package (e.g., "github.com/org/project/models")
	Path string `yaml:"path"`
	// Alias is an optional import alias. If empty, the last segment of the path is used.
	Alias string `yaml:"alias,omitempty"`
}

ModelsPackage specifies an external package containing the model types.

func (*ModelsPackage) Name

func (m *ModelsPackage) Name() string

Name returns the package name/alias to use for qualifying types. Returns the Alias if set, otherwise derives from the Path.

func (*ModelsPackage) Prefix

func (m *ModelsPackage) Prefix() string

Prefix returns the package prefix for qualifying types (e.g., "models."). Returns empty string if models are in the same package.

type NameConverter

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

NameConverter handles converting OpenAPI names to Go identifiers.

func NewNameConverter

func NewNameConverter(mangling NameMangling, substitutions NameSubstitutions) *NameConverter

NewNameConverter creates a NameConverter with the given configuration.

func (*NameConverter) ToEnumValueName

func (c *NameConverter) ToEnumValueName(value string, baseType string) string

ToEnumValueName converts a raw enum value to a valid Go identifier. For integer enums (baseType is int, int32, int64, etc.), numeric values get the configured NumericPrefix, negative values get "Minus" prefix. For string enums, the value is processed through the full NameConverter pipeline.

func (*NameConverter) ToPropertyName

func (c *NameConverter) ToPropertyName(name string) string

ToPropertyName converts an OpenAPI property name to a Go field name.

func (*NameConverter) ToTypeName

func (c *NameConverter) ToTypeName(name string) string

ToTypeName converts an OpenAPI schema name to a Go type name.

func (*NameConverter) ToTypeNamePart

func (c *NameConverter) ToTypeNamePart(name string) string

ToTypeNamePart converts a name to a type name component that will be joined with others. Unlike ToTypeName, it doesn't add a numeric prefix since the result won't be the start of an identifier.

func (*NameConverter) ToVariableName

func (c *NameConverter) ToVariableName(name string) string

ToVariableName converts an OpenAPI name to a Go variable name (unexported).

type NameMangling

type NameMangling struct {
	// CharacterSubstitutions maps characters to their word replacements.
	// Used when these characters appear at the start of a name.
	// Example: '$' -> "DollarSign", '-' -> "Minus"
	CharacterSubstitutions map[string]string `yaml:"character-substitutions,omitempty"`

	// WordSeparators is a string of characters that mark word boundaries.
	// When encountered, the next letter is capitalized.
	// Example: "-_. " means "foo-bar" becomes "FooBar"
	WordSeparators string `yaml:"word-separators,omitempty"`

	// NumericPrefix is prepended when a name starts with a digit.
	// Example: "N" means "123foo" becomes "N123foo"
	NumericPrefix string `yaml:"numeric-prefix,omitempty"`

	// KeywordPrefix is prepended when a name conflicts with a Go keyword.
	// Example: "_" means "type" becomes "_type"
	KeywordPrefix string `yaml:"keyword-prefix,omitempty"`

	// Initialisms is a list of words that should be all-uppercase.
	// Example: ["ID", "HTTP", "URL"] means "userId" becomes "UserID"
	Initialisms []string `yaml:"initialisms,omitempty"`
}

NameMangling configures how OpenAPI names are converted to valid Go identifiers.

func DefaultNameMangling

func DefaultNameMangling() NameMangling

DefaultNameMangling returns sensible defaults for name mangling.

func (NameMangling) Merge

func (n NameMangling) Merge(user NameMangling) NameMangling

Merge returns a new NameMangling with user values overlaid on defaults. Non-zero user values override defaults.

type NameSubstitutions

type NameSubstitutions struct {
	// TypeNames maps generated type names to user-preferred names.
	// Example: {"MyGeneratedType": "MyPreferredName"}
	TypeNames map[string]string `yaml:"type-names,omitempty"`

	// PropertyNames maps generated property/field names to user-preferred names.
	// Example: {"GeneratedField": "PreferredField"}
	PropertyNames map[string]string `yaml:"property-names,omitempty"`
}

NameSubstitutions holds direct name overrides for generated identifiers.

type OperationDescriptor

type OperationDescriptor struct {
	OperationID   string // Normalized operation ID for function names
	GoOperationID string // Go-safe identifier (handles leading digits, keywords)
	Method        string // HTTP method: GET, POST, PUT, DELETE, etc.
	Path          string // Original path: /users/{id}
	Summary       string // For generating comments
	Description   string // Longer description

	// Source indicates where this operation was defined (path, webhook, or callback)
	Source       OperationSource
	WebhookName  string // Webhook name (for Source=webhook)
	CallbackName string // Callback key (for Source=callback)
	ParentOpID   string // Parent operation ID (for Source=callback)

	PathParams   []*ParameterDescriptor
	QueryParams  []*ParameterDescriptor
	HeaderParams []*ParameterDescriptor
	CookieParams []*ParameterDescriptor

	Bodies    []*RequestBodyDescriptor
	Responses []*ResponseDescriptor

	Security []SecurityRequirement

	// Precomputed for templates
	HasBody        bool   // Has at least one request body
	HasParams      bool   // Has non-path params (needs Params struct)
	ParamsTypeName string // "{OperationID}Params"

	// Reference to the underlying spec
	Spec *v3.Operation
}

OperationDescriptor describes a single API operation from an OpenAPI spec.

func FilterOperations

func FilterOperations(ops []*OperationDescriptor, opts OutputOptions) []*OperationDescriptor

FilterOperations applies all operation filters (tags, operation IDs) from OutputOptions.

func FilterOperationsByOperationID

func FilterOperationsByOperationID(ops []*OperationDescriptor, opts OutputOptions) []*OperationDescriptor

FilterOperationsByOperationID filters operations based on include/exclude operation ID lists. Exclude is applied first, then include.

func FilterOperationsByTag

func FilterOperationsByTag(ops []*OperationDescriptor, opts OutputOptions) []*OperationDescriptor

FilterOperationsByTag filters operations based on include/exclude tag lists. Exclude is applied first, then include.

func GatherCallbackOperations

func GatherCallbackOperations(doc *v3.Document, ctx *CodegenContext, contentTypeMatcher *ContentTypeMatcher, typeMapping TypeMapping) ([]*OperationDescriptor, error)

GatherCallbackOperations traverses an OpenAPI document and collects operations from callbacks.

func GatherOperations

func GatherOperations(doc *v3.Document, ctx *CodegenContext, contentTypeMatcher *ContentTypeMatcher, typeMapping TypeMapping) ([]*OperationDescriptor, error)

GatherOperations traverses an OpenAPI document and collects all operations. contentTypeMatcher determines which content types get typed request body methods. typeMapping is used to resolve parameter schema types consistently with the type generator.

func GatherWebhookOperations

func GatherWebhookOperations(doc *v3.Document, ctx *CodegenContext, contentTypeMatcher *ContentTypeMatcher, typeMapping TypeMapping) ([]*OperationDescriptor, error)

GatherWebhookOperations traverses an OpenAPI document and collects operations from webhooks.

func (*OperationDescriptor) AllParams

func (o *OperationDescriptor) AllParams() []*ParameterDescriptor

AllParams returns all parameters including path params.

func (*OperationDescriptor) DefaultBody

func (o *OperationDescriptor) DefaultBody() *RequestBodyDescriptor

DefaultBody returns the default request body (typically application/json), or nil.

func (*OperationDescriptor) DefaultTypedBody

func (o *OperationDescriptor) DefaultTypedBody() *RequestBodyDescriptor

DefaultTypedBody returns the first request body with GenerateTyped=true, preferring the default body. Returns nil if no typed body exists.

func (*OperationDescriptor) HasTypedBody

func (o *OperationDescriptor) HasTypedBody() bool

HasTypedBody returns true if at least one request body has GenerateTyped=true.

func (*OperationDescriptor) Params

Params returns all non-path parameters (query, header, cookie). These are bundled into a Params struct.

func (*OperationDescriptor) SummaryAsComment

func (o *OperationDescriptor) SummaryAsComment() string

SummaryAsComment returns the summary formatted as a Go comment.

type OperationSource

type OperationSource string

OperationSource indicates where an operation was defined in the spec.

const (
	OperationSourcePath     OperationSource = "path"
	OperationSourceWebhook  OperationSource = "webhook"
	OperationSourceCallback OperationSource = "callback"
)

type Output

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

Output collects generated Go code and formats it.

func NewOutput

func NewOutput(packageName string) *Output

NewOutput creates a new output collector.

func (*Output) AddImport

func (o *Output) AddImport(path, alias string)

AddImport adds an import path with optional alias.

func (*Output) AddImports

func (o *Output) AddImports(imports map[string]string)

AddImports adds multiple imports from a map.

func (*Output) AddType

func (o *Output) AddType(code string)

AddType adds a type definition to the output.

func (*Output) Format

func (o *Output) Format() (string, error)

Format returns the formatted Go source code with imports organized.

func (*Output) String

func (o *Output) String() string

String generates the complete Go source file.

type OutputOptions

type OutputOptions struct {
	// IncludeTags only includes operations tagged with one of these tags. Ignored when empty.
	IncludeTags []string `yaml:"include-tags,omitempty"`
	// ExcludeTags excludes operations tagged with one of these tags. Ignored when empty.
	ExcludeTags []string `yaml:"exclude-tags,omitempty"`
	// IncludeOperationIDs only includes operations with one of these operation IDs. Ignored when empty.
	IncludeOperationIDs []string `yaml:"include-operation-ids,omitempty"`
	// ExcludeOperationIDs excludes operations with one of these operation IDs. Ignored when empty.
	ExcludeOperationIDs []string `yaml:"exclude-operation-ids,omitempty"`
	// ExcludeSchemas excludes schemas with the given names from generation. Ignored when empty.
	ExcludeSchemas []string `yaml:"exclude-schemas,omitempty"`
	// PruneUnreferencedSchemas removes component schemas that are not $ref'd by any other
	// gathered schema. When combined with tag/operation filtering, this effectively removes
	// schemas that are only used by excluded operations.
	PruneUnreferencedSchemas bool `yaml:"prune-unreferenced-schemas,omitempty"`
	// AlwaysPrefixEnumValues forces all enum constants to be prefixed with the type name,
	// regardless of whether cross-enum collisions are detected.
	// When false (default), enum constants are only prefixed when needed to avoid collisions.
	AlwaysPrefixEnumValues bool `yaml:"always-prefix-enum-values,omitempty"`
}

OutputOptions controls filtering of which operations and schemas are included in generation.

type ParameterDescriptor

type ParameterDescriptor struct {
	Name     string // Original name from spec (e.g., "user_id")
	GoName   string // Go-safe name for struct fields (e.g., "UserId")
	Location string // "path", "query", "header", "cookie"
	Required bool

	// Serialization style
	Style   string // "simple", "form", "label", "matrix", etc.
	Explode bool

	// Type information
	Schema   *SchemaDescriptor
	TypeDecl string // Go type declaration (e.g., "string", "[]int", "*MyType")

	// Encoding modes
	IsStyled      bool // Uses style/explode serialization (most common)
	IsPassThrough bool // No styling, just pass the string through
	IsJSON        bool // Parameter uses JSON content encoding

	Spec *v3.Parameter
}

ParameterDescriptor describes a parameter in any location.

func (*ParameterDescriptor) AllowReserved

func (p *ParameterDescriptor) AllowReserved() bool

AllowReserved returns whether this parameter's value may contain RFC 3986 reserved characters without percent-encoding.

func (*ParameterDescriptor) GoVariableName

func (p *ParameterDescriptor) GoVariableName() string

GoVariableName returns a Go-safe variable name for this parameter. Used for local variables in generated code.

func (*ParameterDescriptor) HasOptionalPointer

func (p *ParameterDescriptor) HasOptionalPointer() bool

HasOptionalPointer returns true if this parameter should be a pointer (optional parameters that aren't required).

func (*ParameterDescriptor) SchemaFormat

func (p *ParameterDescriptor) SchemaFormat() string

SchemaFormat returns the OpenAPI format string for this parameter's schema (e.g., "int32", "date-time"), or empty string if unavailable.

func (*ParameterDescriptor) SchemaType

func (p *ParameterDescriptor) SchemaType() string

SchemaType returns the first OpenAPI type string for this parameter's schema (e.g., "string", "integer", "array", "object"), or empty string if unavailable.

type ReceiverGenerator

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

ReceiverGenerator generates receiver code from operation descriptors. It is parameterized by prefix to support both webhooks and callbacks.

func NewReceiverGenerator

func NewReceiverGenerator(prefix string, serverType string, rp RuntimePrefixes) (*ReceiverGenerator, error)

NewReceiverGenerator creates a new receiver generator for the specified server type. rp holds the package prefixes for runtime sub-packages; all empty when embedded.

func (*ReceiverGenerator) GenerateErrors

func (g *ReceiverGenerator) GenerateErrors() (string, error)

GenerateErrors generates error types (shared with server).

func (*ReceiverGenerator) GenerateParamTypes

func (g *ReceiverGenerator) GenerateParamTypes(ops []*OperationDescriptor) (string, error)

GenerateParamTypes generates the parameter struct types.

func (*ReceiverGenerator) GenerateReceiver

func (g *ReceiverGenerator) GenerateReceiver(ops []*OperationDescriptor) (string, error)

GenerateReceiver generates the receiver interface and handler functions.

type ReceiverTemplateData

type ReceiverTemplateData struct {
	Prefix      string                 // "Webhook" or "Callback"
	PrefixLower string                 // "webhook" or "callback"
	Operations  []*OperationDescriptor // Operations to generate for
}

ReceiverTemplateData is passed to receiver templates.

type RequestBodyDescriptor

type RequestBodyDescriptor struct {
	ContentType string // "application/json", "multipart/form-data", etc.
	Required    bool
	Schema      *SchemaDescriptor

	// Precomputed for templates
	NameTag       string // "JSON", "Formdata", "Multipart", "Text", etc.
	GoTypeName    string // "{OperationID}JSONBody", etc.
	FuncSuffix    string // "", "WithJSONBody", "WithFormBody" (empty for default)
	IsDefault     bool   // Is this the default body type?
	IsFormEncoded bool   // Is this application/x-www-form-urlencoded?
	GenerateTyped bool   // Generate typed methods for this body (based on content-types config)

	// Encoding options for form data
	Encoding map[string]RequestBodyEncoding
}

RequestBodyDescriptor describes a request body for a specific content type.

type RequestBodyEncoding

type RequestBodyEncoding struct {
	ContentType string
	Style       string
	Explode     *bool
}

RequestBodyEncoding describes encoding options for a form field.

type ResponseContentDescriptor

type ResponseContentDescriptor struct {
	ContentType string
	Schema      *SchemaDescriptor
	NameTag     string // "JSON", "XML", etc.
	IsJSON      bool
}

ResponseContentDescriptor describes response content for a content type.

type ResponseDescriptor

type ResponseDescriptor struct {
	StatusCode  string // "200", "404", "default", "2XX"
	Description string
	Contents    []*ResponseContentDescriptor
	Headers     []*ResponseHeaderDescriptor
	Ref         string // If this is a reference to a named response
}

ResponseDescriptor describes a response for a status code.

func (*ResponseDescriptor) GoName

func (r *ResponseDescriptor) GoName() string

GoName returns a Go-safe name for this response (e.g., "200" -> "200", "default" -> "Default").

func (*ResponseDescriptor) HasFixedStatusCode

func (r *ResponseDescriptor) HasFixedStatusCode() bool

HasFixedStatusCode returns true if the status code is a specific number (not "default" or "2XX").

type ResponseHeaderDescriptor

type ResponseHeaderDescriptor struct {
	Name     string
	GoName   string
	Required bool
	Schema   *SchemaDescriptor
}

ResponseHeaderDescriptor describes a response header.

type RuntimeOutput

type RuntimeOutput struct {
	Params  string // params sub-package (style/bind functions, helpers)
	Types   string // types sub-package (Date, Email, UUID, File, Nullable)
	Helpers string // helpers sub-package (MarshalForm)
}

RuntimeOutput holds the generated Go source code for each runtime sub-package.

func GenerateRuntime

func GenerateRuntime(baseImportPath string) (*RuntimeOutput, error)

GenerateRuntime produces standalone Go source files for each of the three runtime sub-packages. baseImportPath is the base import path for the runtime module (e.g., "github.com/org/project/runtime"). The params sub-package imports the types sub-package for Date references.

type RuntimePackageConfig

type RuntimePackageConfig struct {
	// Path is the base import path for the runtime package
	// (e.g., "github.com/org/project/runtime").
	// Sub-packages are at Path/types, Path/params, and Path/helpers.
	Path string `yaml:"path"`
}

RuntimePackageConfig specifies an external package containing runtime helpers (Date, Nullable, param style/bind functions, MarshalForm, etc.). The runtime is split into three sub-packages: types, params, and helpers.

func (*RuntimePackageConfig) HelpersImport

func (r *RuntimePackageConfig) HelpersImport() string

HelpersImport returns the import path for the helpers sub-package.

func (*RuntimePackageConfig) ParamsImport

func (r *RuntimePackageConfig) ParamsImport() string

ParamsImport returns the import path for the params sub-package.

func (*RuntimePackageConfig) TypesImport

func (r *RuntimePackageConfig) TypesImport() string

TypesImport returns the import path for the types sub-package.

type RuntimePrefixes

type RuntimePrefixes struct {
	Params  string // "params." or ""
	Types   string // "types." or ""
	Helpers string // "helpers." or ""
}

RuntimePrefixes holds the package-qualifier prefixes for the three runtime sub-packages. When embedded (no runtime), all fields are empty strings.

func (RuntimePrefixes) FuncMap

func (rp RuntimePrefixes) FuncMap() template.FuncMap

FuncMap returns a template.FuncMap that exposes runtime prefix accessors to templates.

type SchemaContext

type SchemaContext int

SchemaContext identifies what kind of schema this is based on its location.

const (
	ContextUnknown SchemaContext = iota
	ContextComponentSchema
	ContextParameter
	ContextRequestBody
	ContextResponse
	ContextHeader
	ContextCallback
	ContextWebhook
	ContextProperty
	ContextItems
	ContextAllOf
	ContextAnyOf
	ContextOneOf
	ContextAdditionalProperties
)

type SchemaDescriptor

type SchemaDescriptor struct {
	// Path is where this schema appears in the document
	Path SchemaPath

	// Ref is the $ref string if this is a reference (e.g., "#/components/schemas/Pet")
	// Empty if this is an inline schema definition
	Ref string

	// Schema is the underlying schema from libopenapi
	// nil for unresolved external references
	Schema *base.Schema

	// Parent points to the containing schema (nil for top-level schemas)
	Parent *SchemaDescriptor

	// StableName is the deterministic Go type name derived from the full path.
	// This name is stable across spec changes and should be used for type definitions.
	// Example: #/components/schemas/Cat -> CatSchemaComponent
	StableName string

	// ShortName is a friendly alias that may change due to deduplication.
	// Generated as a type alias pointing to StableName.
	ShortName string

	// OperationID is the operationId from the path operation, if this schema
	// comes from a path's request body or response. Used for friendlier naming.
	OperationID string

	// ContentType is the media type (e.g., "application/json") if this schema
	// comes from a request body or response content. Used for naming.
	ContentType string

	// Extensions holds parsed x- extension values for this schema.
	// These control code generation behavior (type overrides, field names, etc.)
	Extensions *Extensions

	// Discriminator holds discriminator info if this schema has oneOf/anyOf
	// with a discriminator. nil when no discriminator is present.
	Discriminator *DiscriminatorInfo

	// Recursive structure:
	Properties      map[string]*SchemaDescriptor
	Items           *SchemaDescriptor
	AllOf           []*SchemaDescriptor
	AnyOf           []*SchemaDescriptor
	OneOf           []*SchemaDescriptor
	AdditionalProps *SchemaDescriptor
}

SchemaDescriptor represents a schema found during the first pass through the spec.

func FilterSchemasByName

func FilterSchemasByName(schemas []*SchemaDescriptor, excludeNames []string) []*SchemaDescriptor

FilterSchemasByName removes schemas whose component name is in the exclude list. Only filters top-level component schemas (path: components/schemas/<name>).

func GatherSchemas

func GatherSchemas(doc *v3.Document, contentTypeMatcher *ContentTypeMatcher, outputOpts OutputOptions) ([]*SchemaDescriptor, error)

GatherSchemas traverses an OpenAPI document and collects all schemas into a list. When outputOpts contains operation filters (include/exclude tags or operation IDs), schemas from excluded operations are not gathered.

func PruneUnreferencedSchemas

func PruneUnreferencedSchemas(schemas []*SchemaDescriptor) []*SchemaDescriptor

PruneUnreferencedSchemas removes component schemas that are not $ref'd by any other gathered schema. This walks the entire schema descriptor tree, collects all $ref paths, and removes component schemas whose path doesn't appear in that set. Non-component schemas (inline path schemas, etc.) are always kept.

func (*SchemaDescriptor) IsComponentSchema

func (d *SchemaDescriptor) IsComponentSchema() bool

IsComponentSchema returns true if this schema is defined in #/components/schemas

func (*SchemaDescriptor) IsExternalReference

func (d *SchemaDescriptor) IsExternalReference() bool

IsExternalReference returns true if this is a reference to an external file. External refs have the format: file.yaml#/path/to/schema

func (*SchemaDescriptor) IsReference

func (d *SchemaDescriptor) IsReference() bool

IsReference returns true if this schema is a $ref to another schema

func (*SchemaDescriptor) IsTopLevelComponentSchema

func (d *SchemaDescriptor) IsTopLevelComponentSchema() bool

IsTopLevelComponentSchema returns true if this schema is a direct child of #/components/schemas (i.e., #/components/schemas/Foo, not #/components/schemas/Foo/properties/bar).

func (*SchemaDescriptor) ParseExternalRef

func (d *SchemaDescriptor) ParseExternalRef() (filePath, internalPath string)

ParseExternalRef splits an external reference into its file path and internal path. For "common/api.yaml#/components/schemas/Pet", returns ("common/api.yaml", "#/components/schemas/Pet"). Returns empty strings if not an external ref.

type SchemaKind

type SchemaKind int

SchemaKind represents the kind of schema for code generation.

const (
	KindStruct SchemaKind = iota
	KindMap
	KindAlias
	KindEnum
	KindAllOf
	KindAnyOf
	KindOneOf
	KindReference
)

func GetSchemaKind

func GetSchemaKind(desc *SchemaDescriptor) SchemaKind

GetSchemaKind determines what kind of Go type to generate for a schema.

type SchemaPath

type SchemaPath []string

SchemaPath represents the location of a schema in the OpenAPI document. Used for deriving type names and disambiguating collisions. Example: ["components", "schemas", "Pet", "properties", "address"]

func (SchemaPath) Append

func (p SchemaPath) Append(elements ...string) SchemaPath

Append returns a new SchemaPath with the given elements appended. This creates a fresh slice to avoid aliasing issues with append.

func (SchemaPath) ContainsProperties

func (p SchemaPath) ContainsProperties() bool

ContainsProperties returns true if this path contains "properties" anywhere. This indicates it's an inline property schema rather than a component schema.

func (SchemaPath) String

func (p SchemaPath) String() string

String returns the path as a JSON pointer-style string.

type SecurityRequirement

type SecurityRequirement struct {
	Name   string   // Security scheme name
	Scopes []string // Required scopes (for OAuth2)
}

SecurityRequirement describes a security requirement for an operation.

type SenderTemplateData

type SenderTemplateData struct {
	IsClient    bool                   // true for client, false for initiator
	Prefix      string                 // "" for client, "Webhook"/"Callback" for initiator
	PrefixLower string                 // "" for client, "webhook"/"callback" for initiator
	TypeName    string                 // "Client" or "WebhookInitiator"
	Receiver    string                 // "c" or "p"
	OptionType  string                 // "ClientOption" or "WebhookInitiatorOption"
	ErrorType   string                 // "ClientHttpError" or "WebhookHttpError"
	SimpleType  string                 // "SimpleClient" or "SimpleWebhookInitiator"
	Operations  []*OperationDescriptor // Operations to generate for
}

SenderTemplateData is the unified template data for client and initiator templates. Templates use {{if .IsClient}} to branch on the few points where they diverge.

type ServerGenerator

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

ServerGenerator generates server code from operation descriptors.

func NewServerGenerator

func NewServerGenerator(serverType string, rp RuntimePrefixes) (*ServerGenerator, error)

NewServerGenerator creates a new server generator for the specified server type. rp holds the package prefixes for runtime sub-packages; all empty when embedded.

func (*ServerGenerator) GenerateErrors

func (g *ServerGenerator) GenerateErrors() (string, error)

GenerateErrors generates the error types.

func (*ServerGenerator) GenerateHandler

func (g *ServerGenerator) GenerateHandler(ops []*OperationDescriptor) (string, error)

GenerateHandler generates the HTTP handler and routing code.

func (*ServerGenerator) GenerateInterface

func (g *ServerGenerator) GenerateInterface(ops []*OperationDescriptor) (string, error)

GenerateInterface generates the ServerInterface.

func (*ServerGenerator) GenerateParamTypes

func (g *ServerGenerator) GenerateParamTypes(ops []*OperationDescriptor) (string, error)

GenerateParamTypes generates the parameter struct types.

func (*ServerGenerator) GenerateServer

func (g *ServerGenerator) GenerateServer(ops []*OperationDescriptor) (string, error)

GenerateServer generates all server code components. Returns empty string if no server type was configured.

func (*ServerGenerator) GenerateWrapper

func (g *ServerGenerator) GenerateWrapper(ops []*OperationDescriptor) (string, error)

GenerateWrapper generates the ServerInterfaceWrapper.

type SimpleTypeSpec

type SimpleTypeSpec struct {
	Type     string `yaml:"type"`
	Import   string `yaml:"import,omitempty"`
	Template string `yaml:"template,omitempty"`
}

SimpleTypeSpec is used to define the Go typename of a simple type like an int or a string, along with the import required to use it.

type StructField

type StructField struct {
	Name            string // Go field name
	Type            string // Go type expression
	JSONName        string // Original JSON property name
	Required        bool   // Is this field required in the schema
	Nullable        bool   // Is this field nullable (type includes "null")
	Pointer         bool   // Should this be a pointer type
	OmitEmpty       bool   // Include omitempty in json tag
	OmitZero        bool   // Include omitzero in json tag (Go 1.24+)
	JSONIgnore      bool   // Use json:"-" tag to exclude from marshaling
	Doc             string // Field documentation
	Default         string // Go literal for default value (empty if no default)
	IsStruct        bool   // True if this field is a struct type (for recursive ApplyDefaults)
	IsExternal      bool   // True if this field references an external type (ApplyDefaults via reflection)
	IsNullableAlias bool   // True if type is a type alias to Nullable[T] (don't wrap or pointer)
	Order           *int   // Optional field ordering (lower values come first)
}

StructField represents a field in a generated Go struct.

type StructTagGenerator

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

StructTagGenerator generates struct tags from templates.

func NewStructTagGenerator

func NewStructTagGenerator(config StructTagsConfig) *StructTagGenerator

NewStructTagGenerator creates a generator from the configuration. Invalid templates are silently skipped.

func (*StructTagGenerator) GenerateTags

func (g *StructTagGenerator) GenerateTags(info StructTagInfo) string

GenerateTags generates the complete struct tag string for a field. Returns a string like `json:"name,omitempty" yaml:"name,omitempty"`.

func (*StructTagGenerator) GenerateTagsMap

func (g *StructTagGenerator) GenerateTagsMap(info StructTagInfo) map[string]string

GenerateTagsMap generates tags as a map for cases where we need to add extra tags. Returns a map of tag name -> tag value (without quotes).

type StructTagInfo

type StructTagInfo struct {
	// FieldName is the JSON/YAML field name (from the OpenAPI property name)
	FieldName string
	// IsOptional is true if the field is optional (not required)
	IsOptional bool
}

StructTagInfo contains the data available to struct tag templates. Extension-driven concerns (omitzero, json-ignore, omitempty overrides) are applied as post-processing in generateFieldTag, not exposed here.

type StructTagTemplate

type StructTagTemplate struct {
	// Name is the tag name (e.g., "json", "yaml", "form")
	Name string `yaml:"name"`
	// Template is a Go text/template that produces the tag value.
	// Available fields: .FieldName, .IsOptional
	// Example: `{{ .FieldName }}{{if .IsOptional}},omitempty{{end}}`
	Template string `yaml:"template"`
}

StructTagTemplate defines a single struct tag with a name and template.

type StructTagsConfig

type StructTagsConfig struct {
	// Tags is the list of tags to generate for struct fields.
	// Order is preserved in the generated output.
	Tags []StructTagTemplate `yaml:"tags,omitempty"`
}

StructTagsConfig configures struct tag generation.

func DefaultStructTagsConfig

func DefaultStructTagsConfig() StructTagsConfig

DefaultStructTagsConfig returns the default struct tag configuration. By default, json and form tags are generated. Extension-driven concerns (omitzero, json-ignore, omitempty overrides) are handled by post-processing in generateFieldTag, not in the templates.

func (StructTagsConfig) Merge

Merge merges user config on top of this config by name. User entries override matching defaults; new entries are appended.

type TypeGenerator

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

TypeGenerator converts OpenAPI schemas to Go type expressions. It tracks required imports and handles recursive type references.

func NewTypeGenerator

func NewTypeGenerator(typeMapping TypeMapping, converter *NameConverter, importResolver *ImportResolver, tagGenerator *StructTagGenerator, ctx *CodegenContext) *TypeGenerator

NewTypeGenerator creates a TypeGenerator with the given configuration.

func (*TypeGenerator) AddImport

func (g *TypeGenerator) AddImport(path string)

AddImport records an import path needed by the generated code.

func (*TypeGenerator) AddImportAlias

func (g *TypeGenerator) AddImportAlias(path, alias string)

AddImportAlias records an import path with an alias.

func (*TypeGenerator) AddJSONImport

func (g *TypeGenerator) AddJSONImport()

AddJSONImport adds encoding/json import (used by marshal/unmarshal code).

func (*TypeGenerator) AddJSONImports

func (g *TypeGenerator) AddJSONImports()

AddJSONImports adds encoding/json and fmt imports (used by oneOf marshal/unmarshal code).

func (*TypeGenerator) AdditionalPropertiesType

func (g *TypeGenerator) AdditionalPropertiesType(desc *SchemaDescriptor) string

AdditionalPropertiesType returns the Go type for the additionalProperties.

func (*TypeGenerator) GenerateStructFields

func (g *TypeGenerator) GenerateStructFields(desc *SchemaDescriptor) []StructField

GenerateStructFields creates the list of struct fields for an object schema.

func (*TypeGenerator) GoTypeExpr

func (g *TypeGenerator) GoTypeExpr(desc *SchemaDescriptor) string

GoTypeExpr returns the Go type expression for a schema descriptor. This handles references by looking up the target schema's name, and inline schemas by generating the appropriate Go type.

func (*TypeGenerator) HasAdditionalProperties

func (g *TypeGenerator) HasAdditionalProperties(desc *SchemaDescriptor) bool

HasAdditionalProperties returns true if the schema has explicit additionalProperties.

func (*TypeGenerator) Imports

func (g *TypeGenerator) Imports() map[string]string

Imports returns the collected imports as a map[path]alias.

func (*TypeGenerator) IndexSchemas

func (g *TypeGenerator) IndexSchemas(schemas []*SchemaDescriptor)

IndexSchemas builds a lookup table from JSON pointer to schema descriptor. This is called before generation to enable $ref resolution.

func (*TypeGenerator) TagGenerator

func (g *TypeGenerator) TagGenerator() *StructTagGenerator

TagGenerator returns the struct tag generator.

type TypeMapping

type TypeMapping struct {
	Integer FormatMapping `yaml:"integer,omitempty"`
	Number  FormatMapping `yaml:"number,omitempty"`
	Boolean FormatMapping `yaml:"boolean,omitempty"`
	String  FormatMapping `yaml:"string,omitempty"`
}

TypeMapping defines the mapping from OpenAPI types to Go types.

func (TypeMapping) Merge

func (base TypeMapping) Merge(user TypeMapping) TypeMapping

Merge returns a new TypeMapping with user overrides applied on top of base.

type TypeOverride

type TypeOverride struct {
	TypeName    string // The Go type name (e.g., "uuid.UUID")
	ImportPath  string // Import path (e.g., "github.com/google/uuid")
	ImportAlias string // Optional import alias (e.g., "foo" for `import foo "..."`)
}

TypeOverride represents an external type override with optional import.

type UnionMember

type UnionMember struct {
	TypeName            string   // Go type name (e.g., "Cat")
	MethodName          string   // Suffix for As/From/Merge methods (e.g., "Cat")
	Index               int      // Position in anyOf/oneOf array
	HasApplyDefaults    bool     // Whether this type has an ApplyDefaults method
	DiscriminatorValues []string // Discriminator mapping keys for this variant (empty if unmapped)
}

UnionMember represents a member of a union type (anyOf/oneOf).

type UnionTypeConfig

type UnionTypeConfig struct {
	TypeName      string
	Members       []UnionMember
	IsOneOf       bool
	Doc           string
	FixedFields   []StructField
	Discriminator *DiscriminatorInfo
	TagGen        *StructTagGenerator
	HelperPrefix  string         // e.g., "oapiCodegenHelpersPkg." or "" for embedded
	Converter     *NameConverter // for converting JSON property names to Go field names
}

UnionTypeConfig holds all information needed to generate a union type.

Directories

Path Synopsis
Package dce implements dead code elimination for generated Go source files.
Package dce implements dead code elimination for generated Go source files.
Package runtime contains the source-of-truth Go source files for the oapi-codegen runtime helpers.
Package runtime contains the source-of-truth Go source files for the oapi-codegen runtime helpers.
Package runtimeextract reads Go source files from the embedded runtime FS and extracts code bodies for inlining into generated output or assembling into standalone runtime packages.
Package runtimeextract reads Go source files from the embedded runtime FS and extracts code bodies for inlining into generated output or assembling into standalone runtime packages.
test
callbacks
Package callbacks tests callback initiator and receiver code generation.
Package callbacks tests callback initiator and receiver code generation.
components/all_of
Package all_of tests allOf schema composition including inheritance chains, required field merging, and nested allOf with additional properties.
Package all_of tests allOf schema composition including inheritance chains, required field merging, and nested allOf with additional properties.
components/allof_with_properties/additional_properties
Package additional_properties tests allOf composition where members have additionalProperties: true.
Package additional_properties tests allOf composition where members have additionalProperties: true.
components/allof_with_properties/additional_properties_merge
Package additional_properties_merge tests all combinations of allOf merging with different additionalProperties configurations (true, false, typed, default).
Package additional_properties_merge tests all combinations of allOf merging with different additionalProperties configurations (true, false, typed, default).
components/allof_with_properties/format
Package format tests allOf used to apply format constraints (uuid, date) to a base string type.
Package format tests allOf used to apply format constraints (uuid, date) to a base string type.
components/allof_with_properties/same_level
Package same_level tests that properties defined at the same level as allOf are included in the generated type, not ignored.
Package same_level tests that properties defined at the same level as allOf are included in the generated type, not ignored.
components/any_of_enums
Package any_of_enums tests that enum types are generated for properties inside anyOf member schemas.
Package any_of_enums tests that enum types are generated for properties inside anyOf member schemas.
components/any_of_inline
Package any_of_inline tests inline anyOf schema composition with response schemas containing multiple object variants.
Package any_of_inline tests inline anyOf schema composition with response schemas containing multiple object variants.
components/any_of_single_ref
Package any_of_single_ref tests anyOf with a single $ref — should generate a typed property, not interface{}.
Package any_of_single_ref tests anyOf with a single $ref — should generate a typed property, not interface{}.
components/composition
Package composition tests complex component schemas including additionalProperties, oneOf/anyOf patterns, enums, readOnly/writeOnly, and x-go-name.
Package composition tests complex component schemas including additionalProperties, oneOf/anyOf patterns, enums, readOnly/writeOnly, and x-go-name.
components/default_values
Package default_values tests default value handling in generated types.
Package default_values tests default value handling in generated types.
components/enums/illegal_names
Package illegal_names tests enum constant generation with edge cases.
Package illegal_names tests enum constant generation with edge cases.
components/nested_aggregate
Package nested_aggregate tests complex nesting of allOf, anyOf, and oneOf: arrays of anyOf, objects with anyOf/oneOf properties, allOf containing oneOf, oneOf with nested allOf and field preservation, and composition with enums.
Package nested_aggregate tests complex nesting of allOf, anyOf, and oneOf: arrays of anyOf, objects with anyOf/oneOf properties, allOf containing oneOf, oneOf with nested allOf and field preservation, and composition with enums.
components/nullable
Package nullable tests nullable type generation with required/optional combinations.
Package nullable tests nullable type generation with required/optional combinations.
components/objects
Package objects tests object schemas with additionalProperties configurations.
Package objects tests object schemas with additionalProperties configurations.
components/one_of_discriminator_multi_mapping
Package one_of_discriminator_multi_mapping tests oneOf with a discriminator having multiple mapping entries pointing to the same schema.
Package one_of_discriminator_multi_mapping tests oneOf with a discriminator having multiple mapping entries pointing to the same schema.
components/one_of_string_enums
Package one_of_string_enums tests oneOf with single-value string enum variants (undefined, registered, pending, active).
Package one_of_string_enums tests oneOf with single-value string enum variants (undefined, registered, pending, active).
components/primitives/aliased_date
Package aliased_date tests aliased date-format types.
Package aliased_date tests aliased date-format types.
components/primitives/untyped_properties
Package untyped_properties tests properties with no type field.
Package untyped_properties tests properties with no type field.
components/recursive
Package recursive tests that recursive types are handled properly.
Package recursive tests that recursive types are handled properly.
components/recursive_all_of
Package recursive_all_of tests recursive allOf self-references in schema definitions without causing a stack overflow.
Package recursive_all_of tests recursive allOf self-references in schema definitions without causing a stack overflow.
components/recursive_one_of
Package recursive_one_of tests recursive/circular oneOf schema references (FilterPredicate pattern).
Package recursive_one_of tests recursive/circular oneOf schema references (FilterPredicate pattern).
components/schemas
Package schemas tests comprehensive schema generation including generic objects, nullable properties, custom formats, extra-tags, deprecated fields, and x-go-type-name.
Package schemas tests comprehensive schema generation including generic objects, nullable properties, custom formats, extra-tags, deprecated fields, and x-go-type-name.
extensions/x_go_type/enum_override
Package enum_override tests x-go-type-name on enum types.
Package enum_override tests x-go-type-name on enum types.
extensions/x_go_type/object_override
Package object_override tests x-go-type-name on nested object types.
Package object_override tests x-go-type-name on nested object types.
extensions/x_go_type/skip_pointer
Package skip_pointer tests x-go-type with skip-optional-pointer and x-go-type-import.
Package skip_pointer tests x-go-type with skip-optional-pointer and x-go-type-import.
extensions/x_order
Package x_order tests field ordering via x-order extension.
Package x_order tests field ordering via x-order extension.
external_ref/imports
Package imports tests external dependencies with import resolution.
Package imports tests external dependencies with import resolution.
external_ref/multi_package_response
Package multi_package_response tests multi-package response schemas.
Package multi_package_response tests multi-package response schemas.
external_ref/multi_spec
Package multi_spec tests multi-spec cross-package imports.
Package multi_spec tests multi-spec cross-package imports.
external_ref/overlays
Package overlays tests spec overlays and external refs.
Package overlays tests spec overlays and external refs.
external_ref/removed_ref
Package removed_ref tests external reference filtering.
Package removed_ref tests external reference filtering.
external_ref/response_refs
Package response_refs tests external response refs across specs.
Package response_refs tests external response refs across specs.
name_conflict_resolution
Package name_conflict_resolution tests comprehensive type name collision resolution.
Package name_conflict_resolution tests comprehensive type name collision resolution.
name_conflict_resolution/head_digit_op_id
Package head_digit_op_id tests operation IDs starting with digits.
Package head_digit_op_id tests operation IDs starting with digits.
name_conflict_resolution/inline_identifiers
Package inline_identifiers tests that inline schemas generate valid Go identifiers.
Package inline_identifiers tests that inline schemas generate valid Go identifiers.
name_conflict_resolution/underscore_mapping
Package underscore_mapping tests underscore field name mapping.
Package underscore_mapping tests underscore field name mapping.
output_options/name_normalizer
Package name_normalizer tests name normalization behavior.
Package name_normalizer tests name normalization behavior.
output_options/skip_optional_pointer/arrays
Package arrays tests skip-optional-pointer with arrays and additionalProperties.
Package arrays tests skip-optional-pointer with arrays and additionalProperties.
output_options/skip_optional_pointer/containers
Package containers tests skip-optional-pointer on container types.
Package containers tests skip-optional-pointer on container types.
output_options/skip_prune
Package skip_prune tests skip-prune configuration for unreferenced schemas.
Package skip_prune tests skip-prune configuration for unreferenced schemas.
parameters/all_styles
Package all_styles tests parameter type generation across all locations and styles.
Package all_styles tests parameter type generation across all locations and styles.
parameters/any_of
Package any_of tests anyOf and oneOf types used in query parameters, including complex object schemas and primitive type unions.
Package any_of tests anyOf and oneOf types used in query parameters, including complex object schemas and primitive type unions.
parameters/encoding
Package encoding tests path parameter escaping and special characters.
Package encoding tests path parameter escaping and special characters.
parameters/precedence
Package precedence tests operation-level parameters overriding path-level parameters.
Package precedence tests operation-level parameters overriding path-level parameters.
parameters/roundtrip/client
Package client contains the generated client for the parameter roundtrip test.
Package client contains the generated client for the parameter roundtrip test.
parameters/roundtrip/stdhttp
Package stdhttp contains the std-http server for the parameter roundtrip test.
Package stdhttp contains the std-http server for the parameter roundtrip test.
request_response/content_types/custom_json
Package custom_json tests custom JSON content types (application/test+json).
Package custom_json tests custom JSON content types (application/test+json).
request_response/content_types/custom_schema
Package custom_schema tests custom content-type schema handling.
Package custom_schema tests custom content-type schema handling.
request_response/content_types/multiple
Package multiple tests multiple content types in responses.
Package multiple tests multiple content types in responses.
webhooks
Package webhooks tests webhook initiator and receiver code generation.
Package webhooks tests webhook initiator and receiver code generation.

Jump to

Keyboard shortcuts

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