codegen

package
v0.0.0-...-da2a1ef Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: Apache-2.0 Imports: 19 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 ComputeBindFunc ¶

func ComputeBindFunc(style string, explode bool) string

ComputeBindFunc returns the bind function name for a parameter.

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 ComputeStyleFunc ¶

func ComputeStyleFunc(style string, explode bool) string

ComputeStyleFunc returns the style function name for a parameter.

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 GenerateApplyDefaults ¶

func GenerateApplyDefaults(name string, fields []StructField) (string, bool)

GenerateApplyDefaults generates an ApplyDefaults method for a struct. It sets default values for fields that are nil and have defaults defined, and recursively calls ApplyDefaults on nested struct fields. For external types, it uses reflection to check for ApplyDefaults since we cannot know at code generation time whether the external type has the method. Always generates the method (even if empty) so it can be called uniformly. 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 GenerateMixedPropertiesMarshal ¶

func GenerateMixedPropertiesMarshal(name string, fields []StructField) string

GenerateMixedPropertiesMarshal generates MarshalJSON for structs with additionalProperties.

func GenerateMixedPropertiesUnmarshal ¶

func GenerateMixedPropertiesUnmarshal(name string, fields []StructField, addPropsType string) string

GenerateMixedPropertiesUnmarshal generates UnmarshalJSON for structs with additionalProperties.

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 GenerateUnionApplyDefaults ¶

func GenerateUnionApplyDefaults(name string, members []UnionMember) string

GenerateUnionApplyDefaults generates ApplyDefaults for a union type. It recurses into non-nil members that have ApplyDefaults.

func GenerateUnionMarshalAnyOf ¶

func GenerateUnionMarshalAnyOf(name string, members []UnionMember) string

GenerateUnionMarshalAnyOf generates MarshalJSON for an anyOf type.

func GenerateUnionMarshalOneOf ¶

func GenerateUnionMarshalOneOf(name string, members []UnionMember) string

GenerateUnionMarshalOneOf generates MarshalJSON for a oneOf type.

func GenerateUnionType ¶

func GenerateUnionType(name string, members []UnionMember, isOneOf bool, doc string) string

GenerateUnionType generates a union struct for anyOf/oneOf with marshal/unmarshal.

func GenerateUnionUnmarshalAnyOf ¶

func GenerateUnionUnmarshalAnyOf(name string, members []UnionMember) string

GenerateUnionUnmarshalAnyOf generates UnmarshalJSON for an anyOf type.

func GenerateUnionUnmarshalOneOf ¶

func GenerateUnionUnmarshalOneOf(name string, members []UnionMember) string

GenerateUnionUnmarshalOneOf generates UnmarshalJSON for a oneOf type.

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, helpers, param functions, and custom type templates needed during code generation. Code at any depth can call its registration methods; the final output assembly queries it to emit exactly what was requested.

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) GetRequiredParamImports ¶

func (c *CodegenContext) GetRequiredParamImports() []templates.Import

GetRequiredParamImports returns all imports needed for used param functions.

func (*CodegenContext) GetRequiredParamTemplates ¶

func (c *CodegenContext) GetRequiredParamTemplates() []templates.ParamTemplate

GetRequiredParamTemplates returns the list of param templates needed, with the helpers template first if any params are used.

func (*CodegenContext) HasAnyParams ¶

func (c *CodegenContext) HasAnyParams() bool

HasAnyParams returns true if any param functions are needed.

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) NeedCustomType ¶

func (c *CodegenContext) NeedCustomType(name string)

NeedCustomType records that a custom type template is needed (e.g., "nullable", "Date").

func (*CodegenContext) NeedFormHelper ¶

func (c *CodegenContext) NeedFormHelper(ops []*OperationDescriptor)

NeedFormHelper is a convenience method that checks operations for form-encoded bodies and registers the "marshal_form" helper if any are found.

func (*CodegenContext) NeedHelper ¶

func (c *CodegenContext) NeedHelper(name string)

NeedHelper records that a helper template is needed (e.g., "marshal_form").

func (*CodegenContext) NeedParam ¶

func (c *CodegenContext) NeedParam(style string, explode bool)

NeedParam records that a param style/explode combination is needed. It records both the style (serialization) and bind (deserialization) keys.

func (*CodegenContext) RequiredCustomTypes ¶

func (c *CodegenContext) RequiredCustomTypes() []string

RequiredCustomTypes returns the sorted list of custom type template names needed.

func (*CodegenContext) RequiredHelpers ¶

func (c *CodegenContext) RequiredHelpers() []string

RequiredHelpers returns the sorted list of helper template names needed.

func (*CodegenContext) RequiredParams ¶

func (c *CodegenContext) RequiredParams() []string

RequiredParams returns the sorted list of param style keys needed.

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 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")

	// Precomputed function names for templates
	StyleFunc string // "StyleSimpleParam", "StyleFormExplodeParam", etc.
	BindFunc  string // "BindSimpleParam", "BindFormExplodeParam", etc.

	// 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) 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).

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

	// 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
	// GoFieldName is the Go struct field name
	GoFieldName string
	// IsOptional is true if the field is optional (not required)
	IsOptional bool
	// IsNullable is true if the field can be null
	IsNullable bool
	// IsPointer is true if the Go type is a pointer
	IsPointer bool
	// OmitEmpty is true if the omitempty tag option should be used
	// (derived from IsOptional but can be overridden via extensions)
	OmitEmpty bool
	// OmitZero is true if the omitzero tag option should be used (Go 1.24+)
	OmitZero bool
	// JSONIgnore is true if the field should be excluded from JSON (json:"-")
	JSONIgnore bool
}

StructTagInfo contains the data available to struct tag templates.

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, .GoFieldName, .IsOptional, .IsNullable, .IsPointer
	// 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.

func (StructTagsConfig) Merge ¶

Merge merges user config on top of this config. If user specifies any tags, they completely replace the defaults.

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) AddNullableTemplate ¶

func (g *TypeGenerator) AddNullableTemplate()

AddNullableTemplate adds the nullable type template to the output.

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 {
	FieldName        string // Go field name
	TypeName         string // Go type name
	Index            int    // Position in anyOf/oneOf array
	HasApplyDefaults bool   // Whether this type has an ApplyDefaults method
}

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

Directories ¶

Path Synopsis
test/helpers/genhelpers command
genhelpers generates Go files from helper and param templates.
genhelpers generates Go files from helper and param templates.
test/types/gentypes command
gentypes generates Go type files from templates.
gentypes generates Go type files from templates.
test
name_conflict_resolution
Package name_conflict_resolution tests comprehensive type name collision resolution.
Package name_conflict_resolution tests comprehensive type name collision resolution.
previous_version/all_of
Package all_of tests allOf schema composition from the V2 test suite.
Package all_of tests allOf schema composition from the V2 test suite.
previous_version/any_of/inline
Package inline tests inline anyOf schema composition from the V2 test suite.
Package inline tests inline anyOf schema composition from the V2 test suite.
previous_version/any_of/param
Package param tests anyOf/oneOf in parameters from the V2 test suite.
Package param tests anyOf/oneOf in parameters from the V2 test suite.
previous_version/components
Package components tests complex component schemas from the V2 test suite.
Package components tests complex component schemas from the V2 test suite.
previous_version/extensions/x_order
Package x_order tests x-order field ordering extension from the V2 test suite.
Package x_order tests x-order field ordering extension from the V2 test suite.
previous_version/issues/issue_1029
Package issue_1029 tests that oneOf with multiple single-value string enums generates valid code.
Package issue_1029 tests that oneOf with multiple single-value string enums generates valid code.
previous_version/issues/issue_1039
Package issue_1039 tests nullable type generation.
Package issue_1039 tests nullable type generation.
previous_version/issues/issue_1087
Package issue_1087 tests external dependencies with import resolution.
Package issue_1087 tests external dependencies with import resolution.
previous_version/issues/issue_1087/deps
Package deps provides external dependency types for issue 1087.
Package deps provides external dependency types for issue 1087.
previous_version/issues/issue_1093
Package issue_1093 tests multi-spec cross-package imports.
Package issue_1093 tests multi-spec cross-package imports.
previous_version/issues/issue_1127
Package issue_1127 tests multiple content types.
Package issue_1127 tests multiple content types.
previous_version/issues/issue_1168
Package issue_1168 tests additionalProperties: true.
Package issue_1168 tests additionalProperties: true.
previous_version/issues/issue_1180
Package issue_1180 tests parameter style handling.
Package issue_1180 tests parameter style handling.
previous_version/issues/issue_1182
Package issue_1182 tests external response refs across specs.
Package issue_1182 tests external response refs across specs.
previous_version/issues/issue_1189
Package issue_1189 tests anyOf/allOf/oneOf composition.
Package issue_1189 tests anyOf/allOf/oneOf composition.
previous_version/issues/issue_1208_1209
Package issue_1208_1209 tests multiple JSON content types.
Package issue_1208_1209 tests multiple JSON content types.
previous_version/issues/issue_1212
Package issue_1212 tests multi-package response schemas.
Package issue_1212 tests multi-package response schemas.
previous_version/issues/issue_1219
Package issue_1219 tests additionalProperties merge with allOf.
Package issue_1219 tests additionalProperties merge with allOf.
previous_version/issues/issue_1298
Package issue_1298 tests custom content-type schemas.
Package issue_1298 tests custom content-type schemas.
previous_version/issues/issue_1397
Package issue_1397 tests basic type generation with x-go-type-name.
Package issue_1397 tests basic type generation with x-go-type-name.
previous_version/issues/issue_1429
Package issue_1429 tests that enums inside anyOf members are generated.
Package issue_1429 tests that enums inside anyOf members are generated.
previous_version/issues/issue_1496
Package issue_1496 tests that inline schemas generate valid Go identifiers.
Package issue_1496 tests that inline schemas generate valid Go identifiers.
previous_version/issues/issue_1561
Package issue_1561 tests skip-optional-pointer on containers.
Package issue_1561 tests skip-optional-pointer on containers.
previous_version/issues/issue_1710
Package issue_1710 tests that fields are not lost in nested allOf oneOf structures.
Package issue_1710 tests that fields are not lost in nested allOf oneOf structures.
previous_version/issues/issue_1767
Package issue_1767 tests underscore field name mapping.
Package issue_1767 tests underscore field name mapping.
previous_version/issues/issue_1825
Package issue_1825 tests overlay and external refs.
Package issue_1825 tests overlay and external refs.
previous_version/issues/issue_193
Package issue_193 tests allOf with additionalProperties merging.
Package issue_193 tests allOf with additionalProperties merging.
previous_version/issues/issue_1957
Package issue_1957 tests x-go-type with skip-optional-pointer.
Package issue_1957 tests x-go-type with skip-optional-pointer.
previous_version/issues/issue_2031
Package issue_2031 tests skip-optional-pointer with arrays.
Package issue_2031 tests skip-optional-pointer with arrays.
previous_version/issues/issue_2102
Package issue_2102 tests that properties defined at the same level as allOf are included.
Package issue_2102 tests that properties defined at the same level as allOf are included.
previous_version/issues/issue_240
Package issue_240 tests models with no type field.
Package issue_240 tests models with no type field.
previous_version/issues/issue_312
Package issue_312 tests proper escaping of paths with special characters.
Package issue_312 tests proper escaping of paths with special characters.
previous_version/issues/issue_502
Package issue_502 tests that anyOf with only one ref generates the referenced type.
Package issue_502 tests that anyOf with only one ref generates the referenced type.
previous_version/issues/issue_52
Package issue_52 tests that recursive types are handled properly.
Package issue_52 tests that recursive types are handled properly.
previous_version/issues/issue_579
Package issue_579 tests aliased types with date format.
Package issue_579 tests aliased types with date format.
previous_version/issues/issue_609
Package issue_609 tests optional field with no type info.
Package issue_609 tests optional field with no type info.
previous_version/issues/issue_697
Package issue_697 tests that properties alongside allOf are included.
Package issue_697 tests that properties alongside allOf are included.
previous_version/issues/issue_775
Package issue_775 tests that allOf with format specification works correctly.
Package issue_775 tests that allOf with format specification works correctly.
previous_version/issues/issue_832
Package issue_832 tests x-go-type-name override for enum types.
Package issue_832 tests x-go-type-name override for enum types.
previous_version/issues/issue_936
Package issue_936 tests recursive/circular schema references.
Package issue_936 tests recursive/circular schema references.
previous_version/issues/issue_head_digit_operation_id
Package issue_head_digit_operation_id tests operation IDs starting with digits.
Package issue_head_digit_operation_id tests operation IDs starting with digits.
previous_version/issues/issue_illegal_enum_names
Package issue_illegal_enum_names tests enum constant generation with edge cases.
Package issue_illegal_enum_names tests enum constant generation with edge cases.
previous_version/issues/issue_removed_external_ref
Package issue_removed_external_ref tests external ref filtering.
Package issue_removed_external_ref tests external ref filtering.
previous_version/outputoptions/name_normalizer
Package name_normalizer tests name normalization from the V2 test suite.
Package name_normalizer tests name normalization from the V2 test suite.
previous_version/parameters
Package parameters tests parameter type generation from the V2 test suite.
Package parameters tests parameter type generation from the V2 test suite.
previous_version/schemas
Package schemas tests comprehensive schema generation from the V2 test suite.
Package schemas tests comprehensive schema generation from the V2 test suite.

Jump to

Keyboard shortcuts

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