Documentation
¶
Index ¶
- Variables
- func CreateDocument(docContents []byte, cfg Configuration) (libopenapi.Document, error)
- func CreateOperationID(method, path, initial string) (string, error)
- func FormatCode(src string) (string, error)
- func IsScaffoldFile(name string) bool
- func LoadDocumentFromContents(contents []byte, basePath ...string) (libopenapi.Document, error)
- func ScaffoldFileName(name string) string
- func UppercaseFirstCharacter(str string) string
- type AdditionalImport
- type Client
- type Configuration
- type Constraints
- type ConstraintsContext
- type Discriminator
- type EnumContext
- type EnumDefinition
- type EnumValue
- type FieldDescriptor
- type FilterConfig
- type FilterParamsConfig
- type GenerateOptions
- type GeneratedCode
- type GoSchema
- func (s GoSchema) ContainsUnions() bool
- func (s GoSchema) Format() string
- func (s GoSchema) GetAdditionalTypeDefs() []TypeDefinition
- func (s GoSchema) IsAnyType() bool
- func (s GoSchema) IsExternalRef() bool
- func (s GoSchema) IsRef() bool
- func (s GoSchema) IsZero() bool
- func (s GoSchema) NeedsValidation() bool
- func (s GoSchema) TypeDecl() string
- func (s GoSchema) TypeDeclWithNullable() string
- func (s GoSchema) ValidateDecl(alias string, validatorVar string) string
- func (s GoSchema) ValidateDeclWithOptions(alias string, validatorVar string, forceSimple bool) string
- type HandlerKind
- type HandlerOptions
- type HandlerValidation
- type MCPExtension
- type MCPServerOptions
- type MiddlewareOptions
- type ModelsPackage
- type OperationDefinition
- func (o OperationDefinition) GetSuccessResponse() string
- func (o OperationDefinition) HasRequestOptions() bool
- func (o OperationDefinition) HeaderTypeName(rcd *ResponseContentDefinition) string
- func (o OperationDefinition) RequiresParamObject() bool
- func (o OperationDefinition) SummaryAsComment() string
- type Output
- type OverlayOptions
- type ParameterDefinition
- func (pd ParameterDefinition) ArraySchema() *GoSchema
- func (pd ParameterDefinition) Explode() bool
- func (pd ParameterDefinition) GoName() string
- func (pd ParameterDefinition) GoVariableName() string
- func (pd ParameterDefinition) IsJson() bool
- func (pd ParameterDefinition) IsPassThrough() bool
- func (pd ParameterDefinition) IsPointerType() bool
- func (pd ParameterDefinition) IsStyled() bool
- func (pd ParameterDefinition) TypeDef() string
- type ParameterDefinitions
- type ParameterEncoding
- type ParseContext
- type ParseOptions
- type Parser
- type Property
- type RequestBodyDefinition
- type RequestBodyEncoding
- type RequestParametersDefinition
- type ResponseContentDefinition
- type ResponseDefinition
- func (r ResponseDefinition) EnvelopeResponses() []*ResponseContentDefinition
- func (r ResponseDefinition) HasLegacyHeaders(rcd *ResponseContentDefinition) bool
- func (r ResponseDefinition) HasStream() bool
- func (r ResponseDefinition) LegacyBodyField(rcd *ResponseContentDefinition) string
- func (r ResponseDefinition) PrimaryStream() *StreamResponseDefinition
- func (r ResponseDefinition) StreamAt(status int) *StreamResponseDefinition
- func (r ResponseDefinition) StreamFor(rcd *ResponseContentDefinition) *StreamResponseDefinition
- type ScaffoldOutput
- type SchemaDescriptor
- type ServerOptions
- type ServiceOptions
- type SpecLocation
- type StreamResponseDefinition
- type TplOperationsContext
- type TplTypeContext
- type TypeDefinition
- func (t TypeDefinition) GetErrorConstructor(errTypes map[string]string, typeSchemaMap map[string]GoSchema) string
- func (t TypeDefinition) GetErrorResponse(errTypes map[string]string, alias string, typeSchemaMap map[string]GoSchema) string
- func (t TypeDefinition) IsAlias() bool
- func (t TypeDefinition) IsOptional() bool
- type TypeTracker
- func (r *TypeTracker) AsMap() map[string]*TypeDefinition
- func (r *TypeTracker) Exists(name string) bool
- func (r *TypeTracker) LookupByName(name string) (*TypeDefinition, bool)
- func (r *TypeTracker) LookupByRef(ref string) (string, bool)
- func (r *TypeTracker) MarkNeedsErrorMethod(name string)
- func (r *TypeTracker) NeedsErrorMethod(name string) bool
- func (r *TypeTracker) Size() int
- type UnionElement
- type ValidationOptions
Constants ¶
This section is empty.
Variables ¶
var ( ErrOperationNameEmpty = errors.New("operation name cannot be an empty string") ErrRequestPathEmpty = errors.New("request path cannot be an empty string") ErrMergingSchemasWithDifferentUniqueItems = errors.New("merging two schemas with different UniqueItems") ErrMergingSchemasWithDifferentExclusiveMin = errors.New("merging two schemas with different ExclusiveMin") ErrMergingSchemasWithDifferentExclusiveMax = errors.New("merging two schemas with different ExclusiveMax") ErrMergingSchemasWithDifferentNullable = errors.New("merging two schemas with different Nullable") ErrMergingSchemasWithDifferentReadOnly = errors.New("merging two schemas with different ReadOnly") ErrMergingSchemasWithDifferentWriteOnly = errors.New("merging two schemas with different WriteOnly") ErrTransitiveMergingAllOfSchema1 = errors.New("error transitive merging AllOf on schema 1") ErrTransitiveMergingAllOfSchema2 = errors.New("error transitive merging AllOf on schema 2") ErrMergingSchemasWithDifferentDefaults = errors.New("merging two sets of defaults is undefined") ErrMergingSchemasWithDifferentFormats = errors.New("can not merge incompatible formats") ErrMergingSchemasWithDifferentDiscriminators = errors.New("merging two schemas with discriminators is not supported") ErrMergingSchemasWithAdditionalProperties = errors.New("merging two schemas with additional properties, this is unhandled") ErrAmbiguousDiscriminatorMapping = errors.New("ambiguous discriminator.mapping: please replace inlined object with $ref") ErrDiscriminatorNotAllMapped = errors.New("discriminator: not all schemas were mapped") ErrEmptySchema = errors.New("empty schema") ErrEmptyReferencePath = errors.New("empty reference path") ErrHandlerKindRequired = errors.New("handler kind is required") ErrHandlerKindUnsupported = errors.New("unsupported handler kind") ErrServerHandlerPackageRequired = errors.New("server handler-package is required when server generation is enabled") ErrServerRequiresService = errors.New("server generation requires service generation: add 'service: {}' to handler config") ErrInvalidAdditionalTag = errors.New("invalid additional tag name: must not be empty or contain spaces, quotes, or colons") ErrModelsPackageRequiresModelsFalse = errors.New("generate.handler.models-package requires generate.models: false") ErrModelsPackagePathRequired = errors.New("generate.handler.models-package.path is required") ErrConflictingPackageAlias = errors.New("generate.handler.handler-package-alias and the deprecated models-package-alias are both set to different values") )
var TemplateFunctions = template.FuncMap{ "genTypeName": nameNormalizer, "lcFirst": lowercaseFirstCharacter, "ucFirst": uppercaseFirstCharacter, "caps": strings.ToUpper, "lower": strings.ToLower, "snake": strcase.ToSnake, "toGoComment": stringToGoCommentWithPrefix, "ternary": ternary, "join": join, "fst": fst, "hasPrefix": strings.HasPrefix, "hasSuffix": strings.HasSuffix, "contains": strings.Contains, "str": str, "dict": dict, "slice": func() []any { return []any{} }, "escapeGoString": escapeGoString, "append": func(slice []any, val any) []any { return append(slice, val) }, "filterOmitEmpty": filterOmitEmpty, "deref": derefBool, "replace": strings.ReplaceAll, "modelType": func(s string) string { return s }, "modelsPrefix": func() string { return "" }, }
TemplateFunctions is passed to the template engine, and we can call each function here by keyName from the template code.
Functions ¶
func CreateDocument ¶
func CreateDocument(docContents []byte, cfg Configuration) (libopenapi.Document, error)
func CreateOperationID ¶ added in v3.75.2
CreateOperationID generates a unique operation ID based on the HTTP method and path. If the initial value is provided, it will be used. The resulting operation ID is a camel-cased string.
func FormatCode ¶
FormatCode formats the provided Go code by optimizing imports and running gofmt.
func IsScaffoldFile ¶ added in v3.67.0
IsScaffoldFile returns true if the file name indicates a scaffold file.
func LoadDocumentFromContents ¶
func LoadDocumentFromContents(contents []byte, basePath ...string) (libopenapi.Document, error)
LoadDocumentFromContents creates a libopenapi Document from raw bytes. An optional basePath can be provided to resolve relative $ref file references. If provided, basePath should be an absolute path to the directory containing the spec file.
func ScaffoldFileName ¶ added in v3.67.0
ScaffoldFileName returns the actual file name without the scaffold prefix.
func UppercaseFirstCharacter ¶
UppercaseFirstCharacter Uppercases the first character in a string. This assumes UTF-8, so we have to be careful with unicode, don't treat it as a byte array.
Types ¶
type AdditionalImport ¶
type Configuration ¶
type Configuration struct {
PackageName string `yaml:"package"`
CopyrightHeader string `yaml:"copyright-header"`
SkipPrune bool `yaml:"skip-prune"`
Output *Output `yaml:"output"`
Generate *GenerateOptions `yaml:"generate"`
Filter FilterConfig `yaml:"filter,omitempty"`
Overlay *OverlayOptions `yaml:"overlay,omitempty"`
AdditionalImports []AdditionalImport `yaml:"additional-imports,omitempty"`
ErrorMapping map[string]string `yaml:"error-mapping,omitempty"`
Client *Client `yaml:"client,omitempty"`
UserTemplates map[string]string `yaml:"user-templates,omitempty"`
UserContext map[string]any `yaml:"user-context,omitempty"`
// BasePath is the directory used to resolve relative $ref file references.
// When set, external file references like './common.yaml#/...' will be resolved
// relative to this directory. Typically set to the directory containing the spec file.
BasePath string `yaml:"base-path,omitempty"`
}
Configuration defines code generation customizations. PackageName to generate the code under. CopyrightHeader is the header to add to the generated code. Use without //. SkipPrune indicates whether to skip pruning unused components on the generated code. Output specifies the output options for the generated code.
Filter is the configuration for filtering the paths and operations to be parsed.
AdditionalImports defines any additional Go imports to add to the generated code. ErrorMapping is the configuration for mapping the OpenAPI error responses to Go types.
The key is the spec error type name and the value is the dotted json path to the string result.
UserTemplates is the map of user-provided templates overriding the default ones. UserContext is the map of user-provided context values to be used in templates user overrides.
func NewDefaultConfiguration ¶
func NewDefaultConfiguration() Configuration
NewDefaultConfiguration creates a new default Configuration.
func (Configuration) Merge
deprecated
func (o Configuration) Merge(other Configuration) Configuration
Merge combines two configurations, with the receiver (o) taking priority. Empty fields in o are filled with values from other. This operation is not commutative: a.Merge(b) != b.Merge(a).
Deprecated: Use WithDefaults() instead for clearer intent.
func (Configuration) OverwriteWith ¶
func (o Configuration) OverwriteWith(other Configuration) Configuration
OverwriteWith overwrites fields in the configuration with non-empty values from other. The parameter takes priority - non-empty fields from other overwrite the receiver.
func (Configuration) WithDefaults ¶
func (o Configuration) WithDefaults() Configuration
WithDefaults fills empty fields in the configuration with sensible defaults. The receiver takes priority - only empty/nil fields are filled with defaults from NewDefaultConfiguration().
type Constraints ¶
type Constraints struct {
Required *bool
Nullable *bool
ReadOnly *bool
WriteOnly *bool
MinLength *int64
MaxLength *int64
Pattern *string
Min *float64
Max *float64
MinItems *int64
MaxItems *int64
MinProperties *int64
MaxProperties *int64
ValidationTags []string
// RequiredKey is set for an object property listed in required: its key is written even when
// nil, as null. Required only drives the validator tag, which some types drop. readOnly and
// writeOnly properties don't count, as each is left out of one direction.
RequiredKey bool
}
func (Constraints) Count ¶
func (c Constraints) Count() int
Count returns the number of validation constraints. This is useful for determining which schema is "stricter" when deduplicating union elements.
func (Constraints) IsEqual ¶
func (c Constraints) IsEqual(other Constraints) bool
type ConstraintsContext ¶
type ConstraintsContext struct {
// contains filtered or unexported fields
}
type Discriminator ¶
type Discriminator struct {
// maps discriminator value to go type
Mapping map[string]string
// JSON property name that holds the discriminator
Property string
}
func (*Discriminator) JSONTag ¶
func (d *Discriminator) JSONTag() string
func (*Discriminator) PropertyName ¶
func (d *Discriminator) PropertyName() string
type EnumContext ¶
type EnumContext struct {
Enums []EnumDefinition
Imports []string
Config Configuration
WithHeader bool
TypeTracker *TypeTracker
}
type EnumDefinition ¶
type EnumDefinition struct {
Name string
ValueWrapper string
PrefixTypeName bool
Schema GoSchema
Values []EnumValue
SpecLocation SpecLocation
}
EnumDefinition holds type information for enum Schema is the scheme of a type which has a list of enum values, eg, the "container" of the enum. Name is the name of the enum's type, usually aliased from something. EnumDefinition represents an enum type. ValueWrapper wraps the value. It's used to conditionally apply quotes around strings. PrefixTypeName determines if the enum value is prefixed with its TypeName. Values contains the final constant names mapped to their values (computed in filterOutEnums). SpecLocation indicates where in the OpenAPI spec this enum was defined.
type FieldDescriptor ¶
type FieldDescriptor struct {
Required bool // Is the schema required? If not, we'll pass by pointer
GoType string // The Go type needed to represent the json type.
GoName string // The Go compatible type name for the type
JsonName string // The json type name for the type
IsRef bool // Is this schema a reference to predefined object?
}
type FilterConfig ¶
type FilterConfig struct {
Include FilterParamsConfig `yaml:"include"`
Exclude FilterParamsConfig `yaml:"exclude"`
}
FilterConfig is the configuration for filtering the paths and operations to be parsed.
func (FilterConfig) IsEmpty ¶
func (o FilterConfig) IsEmpty() bool
IsEmpty returns true if the filter is empty.
type FilterParamsConfig ¶
type FilterParamsConfig struct {
Paths []string `yaml:"paths"`
Tags []string `yaml:"tags"`
OperationIDs []string `yaml:"operation-ids"`
Webhooks []string `yaml:"webhooks"`
SchemaProperties map[string][]string `yaml:"schema-properties"`
Extensions []string `yaml:"extensions"`
}
FilterParamsConfig is the configuration for filtering the paths to be parsed.
func (FilterParamsConfig) IsEmpty ¶
func (o FilterParamsConfig) IsEmpty() bool
IsEmpty returns true if the filter is empty.
type GenerateOptions ¶
type GenerateOptions struct {
// Client specifies whether to generate the classic client - one method
// per operation that returns the picked 2xx body type directly (e.g.
// `func (c *Client) UploadDocument(...) (*DocumentStored, error)`).
// Use this when callers only need the response body and the operation
// has a single documented success status. Headers and non-picked 2xx
// bodies are not exposed by this style; for that, use
// ClientWithResponse instead, or both together.
//
// Combinations with ClientWithResponse:
// - client: true, client-with-response: false → classic only
// - client: false, client-with-response: true → envelope only
// - client: true, client-with-response: true → both styles, combined
// into a single ClientInterface
//
// Defaults to false.
Client bool `yaml:"client"`
// ClientWithResponse specifies whether to generate `<Op>WithResponse`
// sibling functions that return a typed envelope: one `JSON<status>`
// field per documented response, one `Headers<status>` typed struct per
// status that declares headers, plus `HTTPResponse *http.Response` for
// raw access (undocumented headers, status string, etc.). Use this when
// an operation has multiple 2xx statuses with different bodies (e.g.
// 201 sync + 202 queued), or when callers need typed access to headers
// like Location or Retry-After.
//
// Additive to Client: when both flags are true, the generated
// ClientInterface lists both `<Op>` and `<Op>WithResponse` methods so a
// single mock or test double covers both shapes.
//
// Defaults to false.
ClientWithResponse bool `yaml:"client-with-response"`
// ClientStreaming adds a `<Op>Stream` sibling for every operation with a
// sequential success response (SSE, NDJSON), returning a live
// `runtime.Stream[T]`. Non-streaming methods keep their media type and
// signatures, so an operation offering both `application/json` and
// `text/event-stream` exposes both shapes.
//
// Off by default: the siblings add methods to the generated client
// interface, which would break hand-written mocks on upgrade.
ClientStreaming bool `yaml:"client-streaming"`
// Models specifies whether to generate model types. Defaults to true.
// Set to false when models are generated in a separate package.
Models *bool `yaml:"models,omitempty"`
// Handler specifies options for handler/server code generation.
// If nil, no handler code is generated.
Handler *HandlerOptions `yaml:"handler,omitempty"`
// MCPServer specifies options for MCP (Model Context Protocol) server generation.
// If set, generates MCP tools that wrap the generated client for AI assistant integration.
// Requires client generation to be enabled.
MCPServer *MCPServerOptions `yaml:"mcp-server,omitempty"`
// OmitDescription specifies whether to omit schema description from the spec in the generated code. Defaults to false.
OmitDescription bool `yaml:"omit-description"`
// DefaultIntType specifies the default integer type to use. Defaults to "int".
DefaultIntType string `yaml:"default-int-type"`
// AlwaysPrefixEnumValues specifies whether to always prefix enum values with the schema name. Defaults to true.
AlwaysPrefixEnumValues bool `yaml:"always-prefix-enum-values"`
// AdditionalTags specifies additional struct tags to emit on generated fields,
// mirroring the json tag value. For example, ["yaml"] emits yaml:"field_name,omitempty"
// alongside the json tag. Per-property x-oapi-codegen-extra-tags take priority.
AdditionalTags []string `yaml:"additional-tags"`
// Validation specifies options for Validate() method generation.
Validation ValidationOptions `yaml:"validation"`
}
func (GenerateOptions) Validate ¶ added in v3.74.7
func (o GenerateOptions) Validate() error
Validate returns an error if any generate options are invalid.
type GeneratedCode ¶
GeneratedCode is a map of file names to generated code content. Scaffold files (service, middleware, server/main) are prefixed with "scaffold:" in the key.
func Generate ¶
func Generate(docContents []byte, cfg Configuration) (GeneratedCode, error)
Generate creates Go code from an OpenAPI document and a configuration in single file output.
func (GeneratedCode) GetCombined ¶
func (g GeneratedCode) GetCombined() string
GetCombined returns the combined single-file output (the "all" key).
type GoSchema ¶
type GoSchema struct {
GoType string
RefType string
ArrayType *GoSchema
EnumValues map[string]string
Properties []Property
HasAdditionalProperties bool
AdditionalPropertiesType *GoSchema
AdditionalTypes []TypeDefinition
SkipOptionalPointer bool
Description string
Constraints Constraints
UnionElements []UnionElement
Discriminator *Discriminator
// True if this schema is a struct wrapper around a union (embedded Either or union field)
IsUnionWrapper bool
// True if this union was generated from an if/then/else schema.
// Uses runtime.Conditional instead of runtime.Either.
IsConditional bool
DefineViaAlias bool
IsPrimitiveAlias bool
OpenAPISchema *base.Schema
}
GoSchema describes an OpenAPI schema, with lots of helper fields to use in the templating engine. GoType is the Go type that represents the schema. RefType is the type name of the schema, if it has one. ArrayType is the schema of the array element, if it's an array. EnumValues is a map of enum values. Properties is a list of fields for an object. HasAdditionalProperties is true if the object has additional properties. AdditionalPropertiesType is the type of additional properties. AdditionalTypes is a list of auxiliary types that may be needed. SkipOptionalPointer is true if the type doesn't need a * in front when it's optional. Description is the description of the element. Constraints is a struct that holds constraints for the schema. UnionElements is a list of possible elements in a oneOf/anyOf union. Discriminator describes which value is stored in a union. DefineViaAlias is true if the schema should be declared via alias.
func GenerateGoSchema ¶
func GenerateGoSchema(schemaProxy *base.SchemaProxy, options ParseOptions) (GoSchema, error)
func (GoSchema) ContainsUnions ¶
ContainsUnions returns true if this schema or any of its nested schemas contain union types. This is used to determine if we can use simple validate.Struct() or need custom validation logic.
func (GoSchema) Format ¶ added in v3.67.0
Format returns the OpenAPI format of the schema (e.g., "uuid", "date-time", "date"). Returns empty string if no format is specified.
func (GoSchema) GetAdditionalTypeDefs ¶
func (s GoSchema) GetAdditionalTypeDefs() []TypeDefinition
func (GoSchema) IsAnyType ¶
IsAnyType returns true if the schema represents the 'any' type or an array of 'any'. These types don't need validation methods since they accept any value.
func (GoSchema) IsExternalRef ¶
func (GoSchema) NeedsValidation ¶
NeedsValidation returns true if this schema represents a type that might have a Validate() method. This includes: - Types with RefType set (references to other types, inline types) - Component references (GoType is set but not a primitive type and not a primitive alias) - Struct types (has properties) - Union types (has union elements) - Types with validation constraints
func (GoSchema) TypeDeclWithNullable ¶ added in v3.66.1
TypeDeclWithNullable returns the type declaration with a pointer prefix if the schema is explicitly nullable (via nullable: true or type includes "null"). This is used for additionalProperties value types where we need to represent null values.
func (GoSchema) ValidateDecl ¶
ValidateDecl generates the body of the Validate() method for this schema. It returns the Go code that should appear inside the Validate() method. The alias parameter is the receiver variable name (e.g., "p" for "func (p Person) Validate()"). The validatorVar parameter is the name of the validator variable to use (e.g., "bodyTypesValidate").
func (GoSchema) ValidateDeclWithOptions ¶
func (s GoSchema) ValidateDeclWithOptions(alias string, validatorVar string, forceSimple bool) string
ValidateDeclWithOptions generates the body of the Validate() method for this schema with options. The forceSimple parameter forces the use of simple validation (validate.Struct()) even for complex types.
type HandlerKind ¶ added in v3.67.0
type HandlerKind string
HandlerKind specifies the router/framework to generate handler code for.
const ( HandlerKindBeego HandlerKind = "beego" HandlerKindChi HandlerKind = "chi" HandlerKindEcho HandlerKind = "echo" HandlerKindEchoV5 HandlerKind = "echo-v5" HandlerKindFastHTTP HandlerKind = "fasthttp" HandlerKindFiber HandlerKind = "fiber" HandlerKindGin HandlerKind = "gin" HandlerKindGoFrame HandlerKind = "goframe" HandlerKindGoZero HandlerKind = "go-zero" HandlerKindGorillaMux HandlerKind = "gorilla-mux" HandlerKindHertz HandlerKind = "hertz" HandlerKindIris HandlerKind = "iris" HandlerKindKratos HandlerKind = "kratos" HandlerKindStdHTTP HandlerKind = "std-http" )
func (HandlerKind) IsValid ¶ added in v3.67.0
func (k HandlerKind) IsValid() bool
IsValid returns true if the handler kind is a supported value.
type HandlerOptions ¶ added in v3.67.0
type HandlerOptions struct {
// Name is the name of the service interface. Defaults to "Service".
Name string `yaml:"name"`
// Kind specifies the router/framework to generate for. Defaults to "chi".
// Supported values: "chi"
Kind HandlerKind `yaml:"kind"`
// Validation specifies options for request/response validation in handlers.
Validation HandlerValidation `yaml:"validation"`
// ModelsPackage specifies the package that model types live in, when they
// are generated separately from the handler (generate.models: false) and
// into a different package. Model type references in the generated
// handler (request/response types, path/query/header/body params) are
// qualified with its alias, and its import is added automatically.
//
// Requires generate.models: false, and both generation runs must be
// given the same spec, filters, and error-mapping.
ModelsPackage *ModelsPackage `yaml:"models-package"`
// HandlerPackageAlias is the package alias used to reference the
// generated handler code from the service scaffold (service.go), when
// the scaffold is generated into its own package via
// generate.handler.output. Example: "server" produces
// "server.ServiceInterface" in service.go.
//
// This does not affect model type references - use ModelsPackage for
// that. It replaces the misleadingly named ModelsPackageAlias.
HandlerPackageAlias string `yaml:"handler-package-alias"`
// ModelsPackageAlias is the package alias used to reference the
// generated handler code from the service scaffold.
//
// Deprecated: use HandlerPackageAlias. Despite the name, this was never
// the package models live in - it's the package the generated handler
// itself is in, as seen from service.go. Kept only as a fallback: if
// HandlerPackageAlias is unset, its value is used.
ModelsPackageAlias string `yaml:"models-package-alias"`
// MultipartMaxMemory is the maximum memory in MB for multipart form parsing.
// Defaults to 32MB (matching Go stdlib). Files exceeding this are stored in temp files.
MultipartMaxMemory int `yaml:"multipart-max-memory"`
// Output specifies output for scaffolded handler files (service.go, middleware.go).
// Falls back to root output if nil.
Output *ScaffoldOutput `yaml:"output"`
// Service specifies options for generating service.go scaffold.
// If nil, no service scaffold is generated.
Service *ServiceOptions `yaml:"service"`
// Middleware specifies options for generating middleware.go.
// If nil, no middleware is generated.
Middleware *MiddlewareOptions `yaml:"middleware"`
// Server specifies options for generating a runnable server main.go.
// If nil, no server is generated.
Server *ServerOptions `yaml:"server"`
}
HandlerOptions specifies options for handler/server code generation.
func (HandlerOptions) ResolveScaffoldOutput ¶ added in v3.67.0
func (o HandlerOptions) ResolveScaffoldOutput(rootOutput *Output) ScaffoldOutput
ResolveScaffoldOutput returns the output config for scaffold files (service.go, middleware.go). Uses handler.output if set, otherwise falls back to root output.
func (HandlerOptions) ResolveServerOutput ¶ added in v3.67.0
func (o HandlerOptions) ResolveServerOutput() ScaffoldOutput
ResolveServerOutput returns the output config for server/main.go. Uses server.directory if set, otherwise defaults to "server". Package is always "main" for server.
func (HandlerOptions) Validate ¶ added in v3.67.0
func (o HandlerOptions) Validate() error
Validate returns an error if the handler options are invalid.
type HandlerValidation ¶ added in v3.67.0
type HandlerValidation struct {
// Request enables validation of incoming requests. Defaults to false.
Request bool `yaml:"request"`
// Response enables validation of outgoing responses. Defaults to false.
// Useful for contract testing.
Response bool `yaml:"response"`
}
HandlerValidation specifies validation options for handlers.
type MCPExtension ¶ added in v3.70.0
type MCPExtension struct {
// Skip excludes this operation from MCP tool generation.
// nil means not set (use default behavior), true means skip, false means include.
Skip *bool `json:"skip,omitempty" yaml:"skip,omitempty"`
// Name overrides the MCP tool name (default: operationId)
Name string `json:"name,omitempty" yaml:"name,omitempty"`
// Description overrides the MCP tool description (default: operation summary)
Description string `json:"description,omitempty" yaml:"description,omitempty"`
}
MCPExtension configures MCP tool generation for an operation.
func (*MCPExtension) ShouldSkip ¶ added in v3.70.0
func (e *MCPExtension) ShouldSkip(defaultSkip bool) bool
ShouldSkip returns whether this operation should be skipped based on the extension and the default-skip configuration.
type MCPServerOptions ¶ added in v3.70.0
type MCPServerOptions struct {
// DefaultSkip specifies whether operations are skipped by default.
// If true, operations are excluded unless x-mcp.skip is explicitly false.
// If false (default), operations are included unless x-mcp.skip is true.
DefaultSkip bool `yaml:"default-skip"`
}
MCPServerOptions specifies options for MCP (Model Context Protocol) server generation. MCP servers expose API operations as tools that AI assistants (Claude, Cursor, etc.) can invoke. The generated code wraps the generated client to make real API calls.
type MiddlewareOptions ¶ added in v3.67.0
type MiddlewareOptions struct {
}
MiddlewareOptions specifies options for generating middleware.go. Currently empty but allows for future extensibility.
type ModelsPackage ¶ added in v3.75.20
type ModelsPackage struct {
// Path is the Go import path of the models package. Required.
Path string `yaml:"path"`
// Alias is the identifier used to qualify model type references in the
// generated handler. Defaults to the last path segment of Path.
Alias string `yaml:"alias,omitempty"`
}
ModelsPackage specifies the package that model types are generated into, for handler code that is generated separately and needs to reference them.
type OperationDefinition ¶
type OperationDefinition struct {
ID string
Summary string
Description string
Method string
Path string
PathParams *TypeDefinition
Header *RequestParametersDefinition
Query *RequestParametersDefinition
TypeDefinitions []TypeDefinition
// TODO: check if can be removed
BodyRequired bool
Body *RequestBodyDefinition
Response ResponseDefinition
// MCP contains x-mcp extension configuration for MCP tool generation
MCP *MCPExtension
// WithResponseTypeName is the name of the envelope wrapper struct emitted
// when generate.client-with-response is true (e.g. "UploadDocumentResp").
// Empty when the feature is disabled.
WithResponseTypeName string
// StreamMethodName is the streaming sibling's name (e.g. "GetEventsStream"),
// empty when the feature is off or the operation has no sequential
// response. Disambiguated via the TypeTracker, because "<ID>Stream"
// collides readily.
StreamMethodName string
// HeaderTypeNames maps each documented status code to the name of the
// per-status typed header struct emitted alongside the envelope (e.g.
// 201 -> "UploadDocumentResp201Headers"). Only populated for statuses
// that declare at least one header in the spec. A range or `default` the
// envelope used to expose at its stand-in code keeps its old name here,
// as a deprecated alias; HeaderTypeName returns any response's current name.
HeaderTypeNames map[int]string
// contains filtered or unexported fields
}
OperationDefinition describes an Operation. ID The operation_id description from Swagger, used to generate function names. Summary string from OpenAPI spec, used to generate a comment. Description string from OpenAPI spec. Method The HTTP method for this operation. Path The path for this operation. PathParams Parameters in the path Header HTTP headers. Query Query TypeDefinitions These are all the types we need to define for this operation. BodyRequired Whether the body is required for this operation.
func (OperationDefinition) GetSuccessResponse ¶
func (o OperationDefinition) GetSuccessResponse() string
func (OperationDefinition) HasRequestOptions ¶
func (o OperationDefinition) HasRequestOptions() bool
func (OperationDefinition) HeaderTypeName ¶ added in v3.76.1
func (o OperationDefinition) HeaderTypeName(rcd *ResponseContentDefinition) string
HeaderTypeName returns the name of the typed header struct the envelope declares for rcd, a response of this operation that documents headers.
func (OperationDefinition) RequiresParamObject ¶
func (o OperationDefinition) RequiresParamObject() bool
RequiresParamObject indicates If we have parameters other than path parameters, they're bundled into an object. Returns true if we have any of those. This is used from the template engine.
func (OperationDefinition) SummaryAsComment ¶
func (o OperationDefinition) SummaryAsComment() string
SummaryAsComment returns the Operations summary as a multi line comment
type OverlayOptions ¶ added in v3.68.0
type OverlayOptions struct {
// Sources is a list of overlay files to apply to the OpenAPI spec.
// Each source can be a file path or URL. Overlays are applied in order.
Sources []string `yaml:"sources"`
}
OverlayOptions specifies OpenAPI Overlay files to apply to the spec before generation. See https://spec.openapis.org/overlay/v1.0.0.html for the Overlay specification.
type ParameterDefinition ¶
type ParameterDefinition struct {
ParamName string
In string
Required bool
Spec *v3high.Parameter
Schema GoSchema
// contains filtered or unexported fields
}
ParameterDefinition is a struct that represents a parameter in an operation. Name is the original json parameter name, eg param_name In is where the parameter is defined - path, header, cookie, query Required is whether the parameter is required Spec is the parsed openapi3.Parameter object GoSchema is the GoSchema object
func (ParameterDefinition) ArraySchema ¶ added in v3.76.1
func (pd ParameterDefinition) ArraySchema() *GoSchema
ArraySchema returns the schema of the slice type the parameter is declared with, or nil if it isn't one. For a named type, such as a referenced component parameter or schema, it is that type's schema.
func (ParameterDefinition) Explode ¶
func (pd ParameterDefinition) Explode() bool
func (ParameterDefinition) GoName ¶
func (pd ParameterDefinition) GoName() string
func (ParameterDefinition) GoVariableName ¶
func (pd ParameterDefinition) GoVariableName() string
func (ParameterDefinition) IsJson ¶
func (pd ParameterDefinition) IsJson() bool
func (ParameterDefinition) IsPassThrough ¶
func (pd ParameterDefinition) IsPassThrough() bool
func (ParameterDefinition) IsPointerType ¶ added in v3.67.0
func (pd ParameterDefinition) IsPointerType() bool
IsPointerType returns true if this parameter's field in the generated struct is a pointer. This matches the logic used in generateParamsTypes() when creating Property objects.
func (ParameterDefinition) IsStyled ¶
func (pd ParameterDefinition) IsStyled() bool
func (ParameterDefinition) TypeDef ¶
func (pd ParameterDefinition) TypeDef() string
TypeDef is here as an adapter after a large refactoring so that I don't have to update all the templates. It returns the type definition for a parameter, without the leading '*' for optional ones.
type ParameterDefinitions ¶
type ParameterDefinitions []ParameterDefinition
func (ParameterDefinitions) FindByName ¶
func (p ParameterDefinitions) FindByName(name string) *ParameterDefinition
type ParameterEncoding ¶
ParameterEncoding describes the encoding options for a request body. @see https://spec.openapis.org/oas/v3.1.0#style-examples
type ParseContext ¶
type ParseContext struct {
Operations []OperationDefinition
TypeDefinitions map[SpecLocation][]TypeDefinition
Enums []EnumDefinition
UnionTypes []TypeDefinition
Imports []string
ResponseErrors []string
TypeTracker *TypeTracker
}
ParseContext holds the OpenAPI models.
func CreateParseContext ¶
func CreateParseContext(docContents []byte, cfg Configuration) (*ParseContext, []error)
CreateParseContext creates a ParseContext from an OpenAPI contents and a ParseConfig.
func CreateParseContextFromDocument ¶
func CreateParseContextFromDocument(doc libopenapi.Document, cfg Configuration) (*ParseContext, error)
func CreateParseContextFromModel ¶ added in v3.71.2
func CreateParseContextFromModel(model *v3high.Document, cfg Configuration) (*ParseContext, error)
CreateParseContextFromModel creates a ParseContext from an already-built OpenAPI v3 model. This is useful when the model has been modified in-place, and you want to avoid rebuilding it from the document.
type ParseOptions ¶
type ParseOptions struct {
OmitDescription bool
DefaultIntType string
AlwaysPrefixEnumValues bool
AdditionalTags []string
SkipValidation bool
// ClientStreaming gates sequential-response detection. Off means no
// per-frame item types and an empty ResponseDefinition.Streams, so output
// is bit-for-bit what it was before streaming support existed.
ClientStreaming bool
// ClientWithResponse resolves the `default` response next to explicit
// error codes, which only the envelope client consumes. Off means no type
// generated for it there, so output is unchanged without the envelope.
ClientWithResponse bool
// ErrorMapping maps response type names to the field that should be used
// for the Error() method. When a response type has error mapping configured,
// it cannot be an alias (aliases don't support methods).
ErrorMapping map[string]string
// contains filtered or unexported fields
}
func (ParseOptions) WithPath ¶
func (o ParseOptions) WithPath(path []string) ParseOptions
func (ParseOptions) WithReference ¶
func (o ParseOptions) WithReference(reference string) ParseOptions
func (ParseOptions) WithSpecLocation ¶
func (o ParseOptions) WithSpecLocation(specLocation SpecLocation) ParseOptions
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser uses the provided ParseContext to generate Go code for the API.
func NewParser ¶
func NewParser(cfg Configuration, ctx *ParseContext) (*Parser, error)
NewParser creates a new Parser with the provided ParseConfig and ParseContext.
func (*Parser) Parse ¶
func (p *Parser) Parse() (GeneratedCode, error)
Parse generates Go code for the API using the provided ParseContext. It returns a map of generated code for each type of definition.
type Property ¶
type Property struct {
GoName string
Description string
JsonFieldName string
Schema GoSchema
Extensions map[string]any
Deprecated bool
Constraints Constraints
SensitiveData *runtime.SensitiveDataConfig
ParentType string // Name of the parent type (for detecting recursive references)
}
func (Property) GoVariableName ¶ added in v3.67.0
GoVariableName returns a safe Go variable name for this property. It handles Go keywords by prefixing with "p" and numbers by prefixing with "n". It also avoids reserved template variable names.
func (Property) IsFile ¶ added in v3.67.0
IsFile returns true if this property is a file type (format: binary).
func (Property) IsPointerType ¶
IsPointerType returns true if this property's Go type is a pointer.
type RequestBodyDefinition ¶
type RequestBodyDefinition struct {
Name string
Required bool
Schema GoSchema
NameTag string
ContentType string
Default bool
Encoding map[string]RequestBodyEncoding
}
RequestBodyDefinition describes a request body. Name is the name of the body. Required is whether the body is required. GoSchema is the GoSchema object describing the body. NameTag is the tag used to generate the type name, i.e. JSON, in which case we will produce "JSONBody". ContentType is the content type of the body. Default is whether this is the default body type. Encoding is the encoding options for formdata.
func (RequestBodyDefinition) IsOptional ¶
func (r RequestBodyDefinition) IsOptional() bool
func (RequestBodyDefinition) TypeDef ¶
func (r RequestBodyDefinition) TypeDef(opID string) TypeDefinition
TypeDef returns the Go type definition for a request body
type RequestBodyEncoding ¶
RequestBodyEncoding describes the encoding options for a request body. @see https://spec.openapis.org/oas/v3.1.0#fixed-fields-12
type RequestParametersDefinition ¶
type RequestParametersDefinition struct {
Name string
Encoding map[string]ParameterEncoding
Params []ParameterDefinition
TypeDef TypeDefinition
}
type ResponseContentDefinition ¶
type ResponseContentDefinition struct {
Schema GoSchema
ContentType string
NameTag string
ResponseName string
Description string
Ref string
IsSuccess bool
// StatusCode is the documented status code. For a range or `default` it
// is the stand-in code handler generation uses: 200 for `2XX`, 400 for
// both `4XX` and `5XX`, 200 or 500 for `default`. The envelope client
// matches StatusRange and IsDefault instead.
StatusCode int
// StatusRange is the class digit of a range such as `4XX` (4), or zero
// when the response documents an exact status code.
StatusRange int
// IsDefault is true for the `default` response.
IsDefault bool
Headers map[string]GoSchema
// IsRaw is true for unsupported content types (XML, form-urlencoded, etc.)
// that require the user to handle marshaling manually.
IsRaw bool
// IsStream is true when the media type the primary method selected is
// sequential. It does not change the primary method's shape; it lets
// callers that cannot stream (the MCP tool template) refuse instead of
// blocking forever.
IsStream bool
// contains filtered or unexported fields
}
ResponseContentDefinition describes Operation response. GoSchema is the schema describing this content. ContentType is the content type corresponding to the body, eg, application/json. NameTag is the tag for the type name, such as JSON, in which case we will produce "Response200JSONContent". ResponseName is the name of the response. Description is the description of the response. Ref is the reference to the response. IsSuccess is true if the response is a success response.
func (ResponseContentDefinition) StatusName ¶ added in v3.76.1
func (r ResponseContentDefinition) StatusName() string
StatusName names the response in the envelope client's field and type names: the status code ("404"), the range ("4XX"), or "Default".
type ResponseDefinition ¶
type ResponseDefinition struct {
SuccessStatusCode int
Success *ResponseContentDefinition
Error *ResponseContentDefinition
All map[int]*ResponseContentDefinition
// Successes lists every 2xx response documented under an exact status
// code, in ascending order. Drives `client-with-response` envelope
// generation, which needs a deterministic per-status iteration.
Successes []*ResponseContentDefinition
// Errors lists every non-2xx response documented under an exact status
// code, in ascending order. Same motivation as Successes - the envelope
// populates `JSON404`/`JSON500` fields per documented status.
Errors []*ResponseContentDefinition
// StatusRanges lists the responses documented under a range such as
// `4XX`, in ascending order. The envelope client matches them only after
// every exact code, so an explicit `404` takes precedence over `4XX`.
StatusRanges []*ResponseContentDefinition
// Default is the `default` response, which the envelope client matches
// last: it covers every status nothing more specific documents. Next to
// explicit error codes it is only resolved when ParseOptions.ClientWithResponse
// is set, because nothing else consumes it there.
Default *ResponseContentDefinition
// Streams lists every sequential media type documented on a success
// response, in ascending status order. Populated independently of which
// media type the primary method selected, so an operation offering both
// `application/json` and `text/event-stream` appears here without
// displacing the JSON response.
Streams []*StreamResponseDefinition
}
ResponseDefinition describes a response.
func (ResponseDefinition) EnvelopeResponses ¶ added in v3.76.1
func (r ResponseDefinition) EnvelopeResponses() []*ResponseContentDefinition
EnvelopeResponses returns every response the envelope client matches, in the order it tries them: exact codes, then ranges, then `default`.
func (ResponseDefinition) HasLegacyHeaders ¶ added in v3.76.1
func (r ResponseDefinition) HasLegacyHeaders(rcd *ResponseContentDefinition) bool
HasLegacyHeaders reports whether a range or `default` keeps the headers field and type the envelope declared under its stand-in code, such as Headers500 for `default`, as deprecated aliases. As with LegacyBodyField, only the response All holds at that code had them, and an exact code there documenting headers owns the names now.
func (ResponseDefinition) HasStream ¶ added in v3.75.15
func (r ResponseDefinition) HasStream() bool
HasStream reports whether streaming siblings can be generated.
func (ResponseDefinition) LegacyBodyField ¶ added in v3.76.1
func (r ResponseDefinition) LegacyBodyField(rcd *ResponseContentDefinition) string
LegacyBodyField returns the name the envelope gave a range's body field before ranges were matched by class, such as JSON400 for an inline `4XX`, so it stays as a deprecated alias of the current field. It is "" when there was none - only the range All holds at its stand-in code had one - or when an exact code documented there owns that name now.
func (ResponseDefinition) PrimaryStream ¶ added in v3.75.15
func (r ResponseDefinition) PrimaryStream() *StreamResponseDefinition
PrimaryStream returns the sequential response at the lowest success status, whose item type and media type the streaming sibling uses.
func (ResponseDefinition) StreamAt ¶ added in v3.75.15
func (r ResponseDefinition) StreamAt(status int) *StreamResponseDefinition
StreamAt returns the sequential response documented at a status, or nil.
func (ResponseDefinition) StreamFor ¶ added in v3.76.1
func (r ResponseDefinition) StreamFor(rcd *ResponseContentDefinition) *StreamResponseDefinition
StreamFor returns the sequential response streamed in place of rcd's body, or nil. A range sharing its stand-in code with an exact status, such as `2XX` next to `200`, shares the stream too; only the response All holds at that code owns it, so the envelope declares the field once.
type ScaffoldOutput ¶ added in v3.67.0
type ScaffoldOutput struct {
// Directory is the output directory, relative to the spec/config file location.
Directory string `yaml:"directory"`
// Package is the package name for the generated file.
Package string `yaml:"package"`
// Overwrite forces regeneration of scaffold-once files (e.g., service.go, middleware.go).
// Normally these files are only generated if they don't exist. Defaults to false.
Overwrite bool `yaml:"overwrite"`
}
ScaffoldOutput specifies output options for scaffolded files. Scaffold files are always generated as separate files (not merged).
type SchemaDescriptor ¶
type SchemaDescriptor struct {
Fields []FieldDescriptor
HasAdditionalProperties bool
AdditionalPropertiesType string
}
SchemaDescriptor describes a GoSchema, a type definition.
type ServerOptions ¶ added in v3.67.0
type ServerOptions struct {
// Directory is the output directory for server/main.go.
// Defaults to "server".
Directory string `yaml:"directory"`
// Port is the port the server listens on. Defaults to 8080.
Port int `yaml:"port"`
// Timeout is the request timeout in seconds. Defaults to 30.
Timeout int `yaml:"timeout"`
// HandlerPackage is the full import path of the handler package.
// Required when server generation is enabled.
HandlerPackage string `yaml:"handler-package"`
}
ServerOptions specifies options for generating a runnable server main.go.
func (ServerOptions) Validate ¶ added in v3.67.0
func (o ServerOptions) Validate() error
Validate returns an error if the server options are invalid.
func (ServerOptions) WithDefaults ¶ added in v3.67.0
func (o ServerOptions) WithDefaults() ServerOptions
WithDefaults returns a copy of ServerOptions with default values applied.
type ServiceOptions ¶ added in v3.72.0
type ServiceOptions struct {
}
ServiceOptions specifies options for generating service.go scaffold. Currently empty but allows for future extensibility.
type SpecLocation ¶
type SpecLocation string
const ( SpecLocationPath SpecLocation = "path" SpecLocationQuery SpecLocation = "query" SpecLocationHeader SpecLocation = "header" SpecLocationBody SpecLocation = "body" SpecLocationResponse SpecLocation = "response" SpecLocationSchema SpecLocation = "schema" SpecLocationUnion SpecLocation = "union" SpecLocationWebhook SpecLocation = "webhook" )
type StreamResponseDefinition ¶ added in v3.75.15
type StreamResponseDefinition struct {
StatusCode int
ContentType string
// Framing is "sse" or "lines".
Framing string
// ItemName is the Go type of one frame, e.g. "Event", or "[]byte" when
// there is no per-item schema that can be JSON-decoded.
ItemName string
}
StreamResponseDefinition describes one sequential response. Kept separate from ResponseContentDefinition so the primary method keeps its own media type and Go types; only the streaming siblings read this.
type TplOperationsContext ¶
type TplOperationsContext struct {
Operations []OperationDefinition
Imports []string
Config Configuration
WithHeader bool
ServerOptions *ServerOptions
PackageName string
// ErrorConstructors holds the error types that have a generated New<Type>(message string) constructor.
ErrorConstructors map[string]bool
}
TplOperationsContext is the context passed to templates to generate client code.
type TplTypeContext ¶
type TplTypeContext struct {
Types []TypeDefinition
// Map of type names to schemas for cross-referencing
TypeSchemaMap map[string]GoSchema
Imports []string
SpecLocation string
Config Configuration
WithHeader bool
ResponseErrors map[string]bool
TypeTracker *TypeTracker
}
TplTypeContext is the context passed to templates to generate code for type definitions.
type TypeDefinition ¶
type TypeDefinition struct {
Name string
JsonName string
Schema GoSchema
SpecLocation SpecLocation
NeedsMarshaler bool
HasSensitiveData bool
}
TypeDefinition describes a Go type definition in generated code. Name is the name of the type in the schema, eg, type <...> Person. JsonName is the name of the corresponding JSON description, as it will sometimes differ due to invalid characters. Schema is the GoSchema object used to populate the type description. SpecLocation indicates where in the OpenAPI spec this type was defined. NeedsMarshaler indicates whether this type needs a custom marshaler/unmarshaler. HasSensitiveData indicates whether this type has any properties marked as sensitive.
func (TypeDefinition) GetErrorConstructor ¶ added in v3.71.0
func (t TypeDefinition) GetErrorConstructor(errTypes map[string]string, typeSchemaMap map[string]GoSchema) string
GetErrorConstructor generates a Go constructor function for an error type. It creates nested struct literals based on the error-mapping path. If no error-mapping is configured, it returns a simple constructor.
func (TypeDefinition) GetErrorResponse ¶
func (t TypeDefinition) GetErrorResponse(errTypes map[string]string, alias string, typeSchemaMap map[string]GoSchema) string
GetErrorResponse generates a Go code snippet that returns an error response based on the predefined spec error path. The path supports array access with [] suffix, e.g., "data[].message[]" will access the first element of each array. A path that continues inside a oneOf/anyOf union switches on the decoded variant.
func (TypeDefinition) IsAlias ¶
func (t TypeDefinition) IsAlias() bool
func (TypeDefinition) IsOptional ¶
func (t TypeDefinition) IsOptional() bool
type TypeTracker ¶ added in v3.64.0
type TypeTracker struct {
// contains filtered or unexported fields
}
TypeTracker tracks type definitions and provides lookup by name or reference. It handles name conflicts by generating unique names and maintains a mapping from original OpenAPI references to Go type names.
func (*TypeTracker) AsMap ¶ added in v3.64.0
func (r *TypeTracker) AsMap() map[string]*TypeDefinition
AsMap returns the internal map of type definitions.
func (*TypeTracker) Exists ¶ added in v3.64.0
func (r *TypeTracker) Exists(name string) bool
Exists checks if a type with the given name already exists.
func (*TypeTracker) LookupByName ¶ added in v3.64.0
func (r *TypeTracker) LookupByName(name string) (*TypeDefinition, bool)
LookupByName returns the TypeDefinition pointer for the given Go type name.
func (*TypeTracker) LookupByRef ¶ added in v3.64.0
func (r *TypeTracker) LookupByRef(ref string) (string, bool)
LookupByRef returns the Go type name for the given OpenAPI reference path.
func (*TypeTracker) MarkNeedsErrorMethod ¶ added in v3.67.0
func (r *TypeTracker) MarkNeedsErrorMethod(name string)
MarkNeedsErrorMethod marks a type as needing an Error() method. If the type is an alias, it follows the alias chain to find the actual non-alias type that should get the Error() method. Types that are 'any' or '[]any' are skipped since methods can't be added to them.
func (*TypeTracker) NeedsErrorMethod ¶ added in v3.67.0
func (r *TypeTracker) NeedsErrorMethod(name string) bool
NeedsErrorMethod returns true if the type needs an Error() method.
func (*TypeTracker) Size ¶ added in v3.64.0
func (r *TypeTracker) Size() int
Size returns the number of registered types.
type UnionElement ¶
type UnionElement struct {
// TypeName is the Go type name (e.g., "User", "string", "int")
TypeName string
// Schema contains the full schema including constraints (minLength, minimum, etc.)
Schema GoSchema
}
UnionElement describes a union element with its type and schema (including constraints).
func (UnionElement) Method ¶
func (u UnionElement) Method() string
Method generates union method name for template functions `As/From`.
func (UnionElement) String ¶
func (u UnionElement) String() string
String returns the type name for backward compatibility with templates
type ValidationOptions ¶
type ValidationOptions struct {
// Skip specifies whether to skip Validation method generation. Defaults to false.
Skip bool `yaml:"skip"`
// Simple specifies whether to use the simple validation approach. Defaults to false.
// Simple validation uses validate.Struct() for all types, whereas complex validation generates custom Validate() methods.
Simple bool `yaml:"simple"`
// Response specifies whether to generate Validate() methods for response types.
// Useful for contract testing to ensure responses match the OpenAPI spec. Defaults to false.
Response bool `yaml:"response"`
}
Source Files
¶
- codegen.go
- configuration.go
- errors.go
- extensions.go
- filter.go
- naming.go
- openapi_provider.go
- operations.go
- overlay.go
- parser.go
- parser_functions.go
- parser_models_package.go
- prune.go
- schema.go
- schema_constraints.go
- schema_enums.go
- schema_imports.go
- schema_merge.go
- schema_oapi.go
- schema_object.go
- schema_property.go
- schema_union.go
- schema_validation.go
- streaming.go
- type_tracker.go
- typedef.go
- typedef_components.go
- typedef_errors.go
- typedef_parameters.go
- typedef_payloads.go
- typedef_responses.go
- util.go