codegen

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 44 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Copyright 2019 DeepMap, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2019 DeepMap, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2019 DeepMap, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

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: "OpenAPIEmail"},
			"date":      {Type: "OpenAPIDate"},
			"date-time": {Type: "time.Time", Import: "time"},
			"duration":  {Type: "OpenAPIDuration"},
			"json":      {Type: "json.RawMessage", Import: "encoding/json"},
			"uuid":      {Type: "uuid.UUID", Import: "github.com/google/uuid"},
			"binary":    {Type: "OpenAPIFile"},
		},
	},
}

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

NameNormalizers contains the valid options for `NameNormalizerFunction`s that `oapi-codegen` supports.

If you are calling `oapi-codegen` as a library, this allows you to specify your own normalisation types before generating code.

View Source
var TemplateFunctions = template.FuncMap{
	"dict":                       dict,
	"formBind":                   formBind,
	"formEncode":                 formEncode,
	"genParamArgs":               genParamArgs,
	"genParamNames":              genParamNames,
	"genPathString":              GenPathString,
	"swaggerUriToStdHttpUri":     SwaggerUriToStdHttpUri,
	"lcFirst":                    LowercaseFirstCharacter,
	"ucFirst":                    UppercaseFirstCharacter,
	"ucFirstWithPkgName":         UppercaseFirstCharacterWithPkgName,
	"camelCase":                  ToCamelCase,
	"genResponsePayload":         genResponsePayload,
	"genResponseTypeName":        genResponseTypeName,
	"genResponseUnmarshal":       genResponseUnmarshal,
	"getConditionOfResponseName": getConditionOfResponseName,
	"responsesWithHeaders":       responsesWithHeaders,
	"getResponseTypeDefinitions": getResponseTypeDefinitions,
	"lower":                      strings.ToLower,
	"title":                      titleCaser.String,
	"stripNewLines":              stripNewLines,
	"sanitizeGoIdentity":         SanitizeGoIdentity,
	"schemaNameToTypeName":       SchemaNameToTypeName,
	"toGoString":                 StringToGoString,
	"toGoComment":                StringWithTypeNameToGoComment,
	"withoutPkgName":             withoutPkgName,
	"httpMethodConstant":         httpMethodConstant,
}

TemplateFunctions is passed to the template engine, and we can call each function here by keyName from the template code.

Functions

func DeprecationComment

func DeprecationComment(reason string) string

func EscapePathElements

func EscapePathElements(path string) string

EscapePathElements breaks apart a path, and looks at each element. If it's not a path parameter, eg, {param}, it will URL-escape the element.

func GenFieldsFromProperties

func GenFieldsFromProperties(props []Property) []string

GenFieldsFromProperties produce corresponding field names with JSON annotations, given a list of schema descriptors

func GenPathString

func GenPathString(uri, paramVarName string) string

GenPathString constructs a Go expression that builds the given URI by concatenating its literal segments with the path-parameter variables named <paramVarName>0 through <paramVarName>N. Literal segments are quoted with strconv.Quote so that characters which are significant in Go source, such as quotes, backslashes and percent signs, survive into the generated code unchanged.

func GenStructFromSchema

func GenStructFromSchema(schema Schema) string

func Generate

func Generate(spec *model.Document, opts Configuration) (string, error)

Generate uses the Go templating engine to generate all of our server wrappers from the descriptions we've built up above from the schema objects. opts defines

func GenerateAdditionalPropertyBoilerplate

func GenerateAdditionalPropertyBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)

GenerateAdditionalPropertyBoilerplate generates all the glue code which provides the API for interacting with additional properties and JSON-ification

func GenerateBodyDefinitions

func GenerateBodyDefinitions(operationID string, bodyOrRef *model.RequestBodyRef, pathItemRef string) ([]RequestBodyDefinition, []TypeDefinition, error)

GenerateBodyDefinitions turns the Swagger body definitions into a list of our body definitions which will be used for code generation.

pathItemRef is the path item's $ref (if any). When non-empty and pointing at an external file, the body type that would otherwise be hoisted locally is replaced by a reference to the imported package's same-named type — the imported package already declares it (with any As/From/Merge methods), so redeclaring locally would just produce an awkward duplicate with package-qualified union elements.

func GenerateCallbackInitiator

func GenerateCallbackInitiator(t *template.Template, callbackOps []OperationDefinition) (string, error)

GenerateCallbackInitiator generates the CallbackInitiator -- the client-side analog for OpenAPI callbacks. Structurally identical to GenerateWebhookInitiator but takes the callback OperationDefinitions gathered via CallbackOperationDefinitions, which walk paths/operations/ callbacks rather than spec.Webhooks.

func GenerateClient

func GenerateClient(t *template.Template, ops []OperationDefinition) (string, error)

GenerateClient generates the client for the operations.

func GenerateClientWithResponses

func GenerateClientWithResponses(t *template.Template, ops []OperationDefinition) (string, error)

GenerateClientWithResponses generates a client which extends the basic client which does response unmarshaling.

func GenerateEnums

func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)

func GenerateFormatTypes

func GenerateFormatTypes(t *template.Template) (string, error)

GenerateFormatTypes declares the formatTypes that schemas resolved to while generating, in formatTypes order.

func GenerateImports

func GenerateImports(t *template.Template, externalImports []string, packageName string, versionOverride *string) (string, error)

GenerateImports generates our import statements and package definition.

func GenerateServer

func GenerateServer(t *template.Template, operations []OperationDefinition) (string, error)

GenerateServer generates the server: each operation's request and response objects, the ServerInterface, the net/http handler that routes requests to it, and the operations' security requirements.

func GenerateServerResponses

func GenerateServerResponses(t *template.Template, responses []ResponseDefinition) (string, error)

GenerateServerResponses generates the server's response types for the spec's reusable responses.

func GenerateStdHTTPReceiver

func GenerateStdHTTPReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)

GenerateStdHTTPReceiver renders the merged stdhttp receiver template (used for both webhook and callback receivers). The caller selects between them by passing prefix "Webhook" or "Callback" along with the matching OperationDefinitions. The template emits a {Prefix}Receiver interface plus per-operation {Op}{Prefix}Handler factories with query/header parameter binding inline (matching the param-binding machinery used by the path-server middleware).

func GenerateTemplates

func GenerateTemplates(templates []string, t *template.Template, ops any) (string, error)

GenerateTemplates used to generate templates

func GenerateTemplatesIntoBuffer

func GenerateTemplatesIntoBuffer(buf *bytes.Buffer, templates []string, t *template.Template, ops any) error

GenerateTemplatesIntoBuffer executes the named templates against ops and writes the results to buf, separating consecutive templates with a newline. Rendering into a caller-owned buffer lets a caller compose several passes — e.g. feeding spec-ordered operations to the registration template while the rest of a server uses the pipeline's default order (issue #1887).

func GenerateTypes

func GenerateTypes(t *template.Template, types []TypeDefinition) (string, error)

GenerateTypes passes a bunch of types to the template engine, and buffers its output into a string.

func GenerateTypesForOperations

func GenerateTypesForOperations(t *template.Template, ops []OperationDefinition) (string, error)

GenerateTypesForOperations generates code for all types produced within operations

func GenerateUnionAndAdditionalProopertiesBoilerplate

func GenerateUnionAndAdditionalProopertiesBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)

func GenerateUnionBoilerplate

func GenerateUnionBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)

func GenerateWebhookInitiator

func GenerateWebhookInitiator(t *template.Template, webhookOps []OperationDefinition) (string, error)

GenerateWebhookInitiator generates the WebhookInitiator -- the client-side analog for OpenAPI 3.1 webhooks. It mirrors the path Client (struct + options + per-method calls + request builders) but takes the target URL per-call instead of from a stored Server field. The caller passes only the webhook OperationDefinitions (gathered via WebhookOperationDefinitions); path operations are emitted by the regular Client templates.

func GetParametersImports

func GetParametersImports(params map[string]*model.ParameterRef) (map[string]goImport, error)

func GetRequestBodiesImports

func GetRequestBodiesImports(bodies map[string]*model.RequestBodyRef) (map[string]goImport, error)

func GetResponsesImports

func GetResponsesImports(responses map[string]*model.ResponseRef) (map[string]goImport, error)

func GetSchemaImports

func GetSchemaImports(schemas map[string]*model.SchemaRef, excludeSchemas []string) (map[string]goImport, error)

func GetTypeDefinitionsImports

func GetTypeDefinitionsImports(swagger *model.Document, excludeSchemas []string) (map[string]goImport, error)

func GetUserTemplateText

func GetUserTemplateText(inputData string) (template string, err error)

GetUserTemplateText attempts to retrieve the template text from a passed in URL or file path when inputData is more than one line. This function will attempt to load a file first, and if it fails, will try to get the data from the remote endpoint. The timeout for remote download file is 30 seconds.

func GoSchemaImports

func GoSchemaImports(schemas ...*model.SchemaRef) (map[string]goImport, error)

func IsGoIdentity

func IsGoIdentity(str string) bool

IsGoIdentity checks if the given string can be used as an identity in the generated code like a type name or constant name.

See https://golang.org/ref/spec#Identifiers

func IsGoKeyword

func IsGoKeyword(str string) bool

IsGoKeyword returns whether the given string is a go keyword

func IsGoTypeReference

func IsGoTypeReference(ref string) bool

IsGoTypeReference takes a $ref value and checks if it has link to go type. #/components/schemas/Foo -> true ./local/file.yml#/components/parameters/Bar -> true ./local/file.yml -> false IsGoTypeReference can be used to check whether RefPathToGoType($ref) is possible.

func IsPredeclaredGoIdentifier

func IsPredeclaredGoIdentifier(str string) bool

IsPredeclaredGoIdentifier returns whether the given string is a predefined go identifier.

See https://golang.org/ref/spec#Predeclared_identifiers

func IsValidGoIdentity

func IsValidGoIdentity(str string) bool

IsValidGoIdentity checks if the given string can be used as a name of variable, constant, or type.

func IsWholeDocumentReference

func IsWholeDocumentReference(ref string) bool

IsWholeDocumentReference takes a $ref value and checks if it is whole document reference. #/components/schemas/Foo -> false ./local/file.yml#/components/parameters/Bar -> false ./local/file.yml -> true http://deepmap.com/schemas/document.json -> true http://deepmap.com/schemas/document.json#/Foo -> false

func LoadTemplates

func LoadTemplates(src embed.FS, t *template.Template) error

LoadTemplates loads all of our template files into a text/template. The path of template is relative to the templates directory.

func LowercaseFirstCharacter

func LowercaseFirstCharacter(str string) string

LowercaseFirstCharacter Lowercases 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.

func LowercaseFirstCharacters

func LowercaseFirstCharacters(str string) string

Lowercase the first upper characters in a string for case of abbreviation. This assumes UTF-8, so we have to be careful with unicode, don't treat it as a byte array.

func OperationImports

func OperationImports(ops []OperationDefinition) (map[string]goImport, error)

func OperationSchemaImports

func OperationSchemaImports(s *Schema) (map[string]goImport, error)

func OrderedParamsFromUri

func OrderedParamsFromUri(uri string) []string

OrderedParamsFromUri returns the argument names, in order, in a given URI string, so for /path/{param1}/{.param2*}/{?param3}, it would return param1, param2, param3

func ParseGoImportExtension

func ParseGoImportExtension(v *model.SchemaRef) (*goImport, error)

func PathToTypeName

func PathToTypeName(path []string) string

PathToTypeName converts a path, like Object/field1/nestedField into a go type name.

func RefPathToGoType

func RefPathToGoType(refPath string) (string, error)

RefPathToGoType takes a $ref value and converts it to a Go typename. #/components/schemas/Foo -> Foo #/components/parameters/Bar -> Bar #/components/responses/Baz -> Baz Remote components (document.json#/Foo) are supported if they present in --import-mapping URL components (http://deepmap.com/schemas/document.json#/Foo) are supported if they present in --import-mapping Remote and URL also support standard local paths even though the spec doesn't mention them.

func RefPathToObjName

func RefPathToObjName(refPath string) string

RefPathToObjName returns the name of referenced object without changes.

#/components/schemas/Foo -> Foo
#/components/parameters/Bar -> Bar
#/components/responses/baz_baz -> baz_baz
document.json#/Foo -> Foo
http://deepmap.com/schemas/document.json#/objObj -> objObj

Does not check refPath correctness.

func ResolveNames

func ResolveNames(schemas []*GatheredSchema) map[string]string

ResolveNames takes the gathered schemas and assigns unique Go type names to each. It returns a map from the schema's path string to the resolved Go type name.

func SanitizeCode

func SanitizeCode(goCode string) string

SanitizeCode runs sanitizers across the generated Go code to ensure the generated code will be able to compile.

func SanitizeEnumNames

func SanitizeEnumNames(enumNames, enumValues []string) map[string]string

SanitizeEnumNames fixes illegal chars in the enum names and removes duplicates

func SanitizeGoIdentifier

func SanitizeGoIdentifier(str string) string

SanitizeGoIdentifier replaces illegal runes in the given string so that it is a valid Go identifier. Unlike SanitizeGoIdentity, it does not prefix reserved keywords or predeclared identifiers. This is useful for contexts where the name must be a valid identifier but is not used as a Go symbol (e.g. net/http ServeMux wildcard names).

func SanitizeGoIdentity

func SanitizeGoIdentity(str string) string

SanitizeGoIdentity deletes and replaces the illegal runes in the given string to use the string as a valid identity. It also prefixes reserved keywords and predeclared identifiers with an underscore.

func SchemaHasAdditionalProperties

func SchemaHasAdditionalProperties(schema *model.Schema) bool

According to the spec, additionalProperties may be true, false, or a schema. If not present, true is implied. If it's a schema, true is implied. If it's false, no additional properties are allowed. We're going to act a little differently, in that if you want additionalProperties code to be generated, you must specify an additionalProperties type If additionalProperties it true/false, this field will be non-nil.

func SchemaNameToTypeName

func SchemaNameToTypeName(name string) string

SchemaNameToTypeName converts a Schema name to a valid Go type name. It converts to camel case, and makes sure the name is valid in Go

func SetGlobalStateSpec

func SetGlobalStateSpec(spec *model.Document)

func SortedMapKeys

func SortedMapKeys[T any](m map[string]T) []string

SortedMapKeys takes a map with keys of type string and returns a slice of those keys sorted lexicographically.

func SortedSchemaKeys

func SortedSchemaKeys(dict map[string]*model.SchemaRef) []string

SortedSchemaKeys returns the keys of the given SchemaRef dictionary in sorted order, since Golang scrambles dictionary keys. This isn't a generic key sort, because we support an extension to grant specific orders to schemas to help control output ordering.

func StringToGoComment

func StringToGoComment(in string) string

StringToGoComment renders a possible multi-line string as a valid Go-Comment. Each line is prefixed as a comment.

func StringToGoString

func StringToGoString(in string) string

StringToGoString takes an arbitrary string and converts it to a valid Go string literal, including the quotes. For instance, `foo "bar"` would be converted to `"foo \"bar\""`.

strconv.Quote escapes backslashes, newlines and other control characters too, so untrusted spec text cannot break out of the generated string literal.

func StringWithTypeNameToGoComment

func StringWithTypeNameToGoComment(in, typeName string) string

StringWithTypeNameToGoComment renders a possible multi-line string as a valid Go-Comment, including the name of the type being referenced. Each line is prefixed as a comment.

func SwaggerUriToStdHttpUri

func SwaggerUriToStdHttpUri(uri string) string

SwaggerUriToStdHttpUri converts a swagger style path URI with parameters to a net/http ServeMux compatible path URI. Parameter names are sanitized to be valid Go identifiers, as required by ServeMux wildcard segments. A parameter that shares its segment with literal text, such as "{Sid}.json", is widened to a wildcard occupying the whole segment; the handler checks the literal text and strips it before binding. Valid input parameters are:

{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}

func ToCamelCase

func ToCamelCase(str string) string

ToCamelCase will convert query-arg style strings to CamelCase. We will use `., -, +, :, ;, _, ~, ' ', (, ), {, }, [, ]` as valid delimiters for words. So, "word.word-word+word:word;word_word~word word(word)word{word}[word]" would be converted to WordWordWordWordWordWordWordWordWordWordWordWordWord

func ToCamelCaseWithDigits

func ToCamelCaseWithDigits(s string) string

ToCamelCaseWithDigits function will convert query-arg style strings to CamelCase. We will use `., -, +, :, ;, _, ~, ' ', (, ), {, }, [, ]` as valid delimiters for words. The difference of ToCamelCase that letter after a number becomes capitalized. So, "word.word-word+word:word;word_word~word word(word)word{word}[word]3word" would be converted to WordWordWordWordWordWordWordWordWordWordWordWordWord3Word

func ToCamelCaseWithInitialism

func ToCamelCaseWithInitialism(str string) string

func ToCamelCaseWithInitialisms

func ToCamelCaseWithInitialisms(s string) string

ToCamelCaseWithInitialisms function will convert query-arg style strings to CamelCase with initialisms in uppercase. So, httpOperationId would be converted to HTTPOperationID

func TypeDefinitionsEquivalent

func TypeDefinitionsEquivalent(t1, t2 TypeDefinition) bool

TypeDefinitionsEquivalent checks for equality between two type definitions, but not every field is considered. We only want to know if they are fundamentally the same type.

func UppercaseFirstCharacter

func UppercaseFirstCharacter(str string) string

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.

func UppercaseFirstCharacterWithPkgName

func UppercaseFirstCharacterWithPkgName(str string) string

Uppercase the first character in a identifier with pkg name. This assumes UTF-8, so we have to be careful with unicode, don't treat it as a byte array.

func ValidateOpenAPIVersion

func ValidateOpenAPIVersion(spec *model.Document) error

ValidateOpenAPIVersion rejects a document that isn't OpenAPI 3: an OpenAPI 2.0 (Swagger) document, which loads as an OpenAPI 3 document with nothing in it that generation understands, or one that declares another version. Without it, such a document fails partway through generation, on whichever part of it first differs from OpenAPI 3. A document that declares no version is taken to be OpenAPI 3, as a file of shared definitions often is.

func ValidateSpec

func ValidateSpec(spec *model.Document) error

ValidateSpec walks a loaded OpenAPI document and rejects values that cannot be represented in the generated Go source.

oapi-codegen copies many spec strings verbatim into the code it emits: parameter names, property names, media types and enum values become Go string literals and struct-tag contents; the `x-go-name`/`x-go-type`/`x-go-type-name` extensions become Go identifiers and type expressions. A value containing a quote, a backtick or a control character (such as a newline) would produce Go that does not compile. Catching that here turns an obscure compiler error on generated code into a clear message that points at the offending part of the spec.

It is meant to run after any overlay has been applied and after tag/operation filtering and component pruning, so only values that will actually be emitted are checked. `$ref`s are not followed: every ref resolves to a component that is validated at its own definition, and the contents of external documents are never copied into the generated output, so they cannot affect it.

func ValidateStdHTTPPath

func ValidateStdHTTPPath(path string) error

ValidateStdHTTPPath reports whether one OpenAPI path can be rewritten into a ServeMux pattern. A parameter may share its segment with literal text; adjacent parameters in one segment cannot, because nothing marks where one ends and the next begins.

func ValidateStdHTTPPaths

func ValidateStdHTTPPaths(spec *model.Document) error

ValidateStdHTTPPaths validates every path in the document for ServeMux. Paths whose operations have all been removed (e.g. by tag or operation-id filtering) emit no routes, so they are skipped.

A mixed segment is widened to a whole-segment wildcard. Two operations that then register as the same pattern, or whose widened patterns overlap, are rejected here: ServeMux would panic when the handler is constructed. Overlaps between paths that were already legal ServeMux patterns are left alone, matching generation from before mixed segments were accepted.

Types

type AdditionalImport

type AdditionalImport struct {
	Alias   string `yaml:"alias,omitempty"`
	Package string `yaml:"package"`
}

type ClientMethodVariant

type ClientMethodVariant struct {
	// Suffix is appended to the OperationId to form the method name and its
	// request-builder name: "" or "WithBody" for the generic variant,
	// "WithJSONBody" etc. for a typed-body variant.
	Suffix string

	// ArgsDecl is the parameter-declaration fragment that follows the leading
	// ctx/server parameter, with a leading comma when non-empty, e.g.
	// ", id string, params *FooParams, contentType string, body io.Reader".
	ArgsDecl string

	// CallArgs is the argument fragment passed when a method forwards to
	// another function (the request builder, or the wrapped client method),
	// with a leading comma when non-empty, e.g. ", id, params, contentType, body".
	CallArgs string

	// InterfaceComment / MethodComment are the fully rendered Godoc comments
	// (including any deprecation notice) for the ClientInterface declaration and
	// the *Client method implementation respectively. The interface form places
	// a blank "//" line before the deprecation notice; the implementation form
	// does not -- matching the historical output of both sites.
	InterfaceComment string
	MethodComment    string

	// WithResponseInterfaceComment / WithResponseMethodComment are the analogous
	// comments for the ClientWithResponsesInterface declaration and the
	// *ClientWithResponses method implementation.
	WithResponseInterfaceComment string
	WithResponseMethodComment    string
}

ClientMethodVariant is a precomputed view of one generated client method. Every operation yields a generic variant (the bodyless method, or the "WithBody" method taking an io.Reader when the operation has a request body) followed by one typed-body variant per request body that RequestBodyDefinition.IsSupportedByClient reports.

All naming, signature, and comment decisions are made here in Go so that client.tmpl and client-with-responses.tmpl can render linearly, without the repeated `{{if .HasBody}}WithBody{{end}}` suffix dance and four-fragment signature assembly the templates previously carried at every declaration, implementation, and call site.

type Configuration

type Configuration struct {
	// PackageName to generate the code under
	PackageName string `yaml:"package"`
	// Generate specifies which supported output formats to generate
	Generate GenerateOptions `yaml:"generate,omitempty"`
	// OutputOptions are used to modify the output code in some way.
	OutputOptions OutputOptions `yaml:"output-options,omitempty"`
	// ImportMapping specifies the golang package path for each external reference
	ImportMapping map[string]string `yaml:"import-mapping,omitempty"`
	// AdditionalImports defines any additional Go imports to add to the generated code
	AdditionalImports []AdditionalImport `yaml:"additional-imports,omitempty"`
	// NoVCSVersionOverride allows overriding the version of the application for cases where no Version Control System (VCS) is available when building, for instance when using a Nix derivation.
	// See documentation for how to use it in examples/no-vcs-version-override/README.md
	NoVCSVersionOverride *string `yaml:"-"`
}

Configuration defines code generation customizations

func (Configuration) UpdateDefaults

func (o Configuration) UpdateDefaults() Configuration

UpdateDefaults sets reasonable default values for unset fields in Configuration

func (Configuration) Validate

func (o Configuration) Validate() error

Validate checks whether Configuration represent a valid configuration

func (Configuration) Warnings

func (o Configuration) Warnings() map[string]string

Warnings returns informational diagnostics about cross-field configuration combinations that aren't outright errors but are likely to produce generated code that doesn't compile, or that requires the user to know a specific multi-config convention. The warnings are surfaced on stderr by the CLI so the user notices before running `go build`.

type Constants

type Constants struct {
	// EnumDefinitions holds type and value information for all enums
	EnumDefinitions []EnumDefinition
	// SkipEnumValidate suppresses generation of the `Valid()` method on
	// enum types. Mirrors OutputOptions.SkipEnumValidate.
	SkipEnumValidate bool
}

type Discriminator

type Discriminator struct {
	// maps discriminator value to go type
	Mapping map[string]string

	// JSON property name that holds the discriminator
	Property string

	// ValueType is the JSON type of the discriminator property's values:
	// "boolean", "integer" or "number" when the schemas declare one, and ""
	// for the usual string discriminator.
	ValueType string
	// contains filtered or unexported fields
}

func (*Discriminator) IsString

func (d *Discriminator) IsString() bool

IsString reports whether the discriminator's values are JSON strings.

func (*Discriminator) JSONTag

func (d *Discriminator) JSONTag() string

func (*Discriminator) SwitchType

func (d *Discriminator) SwitchType() string

SwitchType returns the Go type ValueByDiscriminator decodes the discriminator into and switches on: int64 or float64 for an integer or number discriminator, and "" when it compares the value's JSON text.

type DiscriminatorCase

type DiscriminatorCase struct {
	// Value is the discriminator value that selects this element, e.g. "GitDiffFile".
	Value string
	// Method is the union element method suffix, e.g. "ExternalRef0GitDiffFile",
	// so the generated call is t.As<Method>().
	Method string
}

DiscriminatorCase is one arm of a union's ValueByDiscriminator() switch: a discriminator value and the As* helper it dispatches to.

type DiscriminatorStamp

type DiscriminatorStamp struct {
	// Value is the discriminator value mapped to this union element.
	Value string
	// Literal is Value written as a JSON and Go literal of the
	// discriminator's type: "cat" for a string discriminator, false for a
	// boolean one (issue #1619).
	Literal string
	// Property is the union struct's own discriminator field, matched by
	// JSON property name, when it declares one; nil when it doesn't.
	Property *Property
	// JSONPatch is the JSON object literal merged into the union data,
	// e.g. {"code":"resource_exists"}. Safe to embed in a backtick string
	// literal: spec validation rejects discriminator property names and
	// mapping keys containing quotes, backticks or control characters.
	JSONPatch string
}

DiscriminatorStamp describes how the generated From*/Merge* union helpers record the discriminator value for one union element.

The value is always merged into the marshaled JSON via JSONPatch, so Discriminator() and ValueByDiscriminator() — which read the union data — see it immediately after From*/Merge*. Stamping at the JSON level stays correct regardless of how the variant declares the property — pointer, named enum type, renamed or absent field, or a type in an imported package — none of which is knowable from the union's side (see issue #2297). When the union struct itself declares the discriminator property, the helpers additionally assign Value to that field: its JSON rendering overwrites the union data in MarshalJSON, so the field is load-bearing.

type EnumDefinition

type EnumDefinition struct {
	// Schema is the scheme of a type which has a list of enum values, eg, the
	// "container" of the enum.
	Schema Schema
	// TypeName is the name of the enum's type, usually aliased from something.
	TypeName string
	// ValueWrapper wraps the value. It's used to conditionally apply quotes
	// around strings.
	ValueWrapper string
	// PrefixTypeName determines if the enum value is prefixed with its TypeName.
	// This is set to true when this enum conflicts with another in terms of
	// TypeNames or when explicitly requested via the
	// `output-options.always-prefix-enum-values` option.
	PrefixTypeName bool
	// contains filtered or unexported fields
}

EnumDefinition holds type information for enum

func (*EnumDefinition) GetValues

func (e *EnumDefinition) GetValues() map[string]string

GetValues generates enum names in a way to minimize global conflicts

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 FormatMapping

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

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

func (FormatMapping) Resolve

func (fm FormatMapping) Resolve(format string) SimpleTypeSpec

Resolve returns the SimpleTypeSpec for a given format string. If the format has a specific mapping, that is returned; otherwise the default is used.

type GatheredSchema

type GatheredSchema struct {
	Path           SchemaPath
	Context        SchemaContext
	Ref            string        // $ref string if this is a reference
	Schema         *model.Schema // The resolved schema value
	OperationID    string        // Enclosing operation's ID, if any
	ContentType    string        // Media type, if from request/response body
	StatusCode     string        // HTTP status code, if from a response
	ParamIndex     int           // Parameter index within an operation
	ComponentName  string        // The component name (e.g., "Bar" for components/schemas/Bar)
	GoNameOverride string        // x-go-name override from the component or its parent container
}

GatheredSchema represents a schema discovered during the gather pass, along with its document location and context metadata.

func GatherSchemas

func GatherSchemas(spec *model.Document, opts Configuration) []*GatheredSchema

GatherSchemas walks the entire OpenAPI spec and collects all schemas that will need Go type names. This is the first pass of the multi-pass resolution.

func (*GatheredSchema) FormatPath

func (gs *GatheredSchema) FormatPath() string

FormatPath returns a human-readable representation of the path for debugging.

func (*GatheredSchema) IsComponentSchema

func (gs *GatheredSchema) IsComponentSchema() bool

IsComponentSchema returns true if this schema came from components/schemas.

type GenerateOptions

type GenerateOptions struct {
	// Server specifies whether to generate the net/http server
	Server bool `yaml:"server,omitempty"`
	// Client specifies whether to generate client boilerplate
	Client bool `yaml:"client,omitempty"`
	// Models specifies whether to generate type definitions
	Models bool `yaml:"models,omitempty"`
}

GenerateOptions specifies which supported output formats to generate.

func (GenerateOptions) AnyOperationGenerator

func (g GenerateOptions) AnyOperationGenerator() bool

AnyOperationGenerator returns true if any code generator that emits per-operation Go code (the client or the server) is enabled. Used to detect configurations where operation-derived type references would be emitted without a corresponding declaration.

func (GenerateOptions) Validate

func (oo GenerateOptions) Validate() map[string]string

func (GenerateOptions) Warnings

func (oo GenerateOptions) Warnings() map[string]string

type InitiatorTemplateData

type InitiatorTemplateData struct {
	Prefix      string // "Webhook" or "Callback"
	PrefixLower string // lowercase form of Prefix, for prose
	Operations  []OperationDefinition
}

InitiatorTemplateData is the input to the shared webhook / callback initiator template. Prefix selects between "Webhook" and "Callback" (and the lowercase form for prose), so a single template handles both the OpenAPI 3.1 webhook and OpenAPI callback client-side initiators.

func NewInitiatorTemplateData

func NewInitiatorTemplateData(prefix string, ops []OperationDefinition) (InitiatorTemplateData, error)

NewInitiatorTemplateData builds the template input for the given prefix ("Webhook" or "Callback") and operation list.

Initiator operations must not carry path parameters: the initiator takes an opaque targetURL per call, so there is no route template to substitute into, and the generated request builders accept no path arguments while the initiator methods would forward them (producing uncompilable code). Webhook/CallbackOperationDefinitions reject in:path parameters at extraction time; this check is defense in depth for direct callers of the exported API.

type NameNormalizer

type NameNormalizer func(string) string

NameNormalizer is a function that takes a type name, and returns that type name converted into a different format.

This may be an Operation ID i.e. `retrieveUserRequests` or a Schema name i.e. `BigBlockOfCheese`

NOTE: this must return a string that can be used as a valid Go type name

type NameNormalizerFunction

type NameNormalizerFunction string
const (
	// NameNormalizerFunctionUnset is the default case, where the `name-normalizer` option hasn't been set. This will use the `ToCamelCase` function.
	//
	// See the docs for `NameNormalizerFunctionToCamelCase` for more details.
	NameNormalizerFunctionUnset NameNormalizerFunction = ""
	// NameNormalizerFunctionToCamelCase will use the `ToCamelCase` function.
	//
	// For instance:
	//
	// - `getHttpPet`   => `GetHttpPet`
	// - `OneOf2things` => `OneOf2things`
	NameNormalizerFunctionToCamelCase NameNormalizerFunction = "ToCamelCase"
	// NameNormalizerFunctionToCamelCaseWithDigits will use the `NameNormalizerFunctionToCamelCaseWithDigits` function.
	//
	// For instance:
	//
	// - `getHttpPet`   => `GetHttpPet`
	// - `OneOf2things` => `OneOf2Things`
	NameNormalizerFunctionToCamelCaseWithDigits NameNormalizerFunction = "ToCamelCaseWithDigits"
	// NameNormalizerFunctionToCamelCaseWithInitialisms will use the `NameNormalizerFunctionToCamelCaseWithInitialisms` function.
	//
	// For instance:
	//
	// - `getHttpPet`   => `GetHTTPPet`
	// - `OneOf2things` => `OneOf2things`
	NameNormalizerFunctionToCamelCaseWithInitialisms NameNormalizerFunction = "ToCamelCaseWithInitialisms"
)

type NameNormalizerMap

type NameNormalizerMap map[NameNormalizerFunction]NameNormalizer

func (NameNormalizerMap) Options

func (m NameNormalizerMap) Options() []string

type ObjectCodec

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

ObjectCodec binds and styles an object parameter: an object's properties are key-value pairs, which the style lays out in the value.

type OperationDefinition

type OperationDefinition struct {
	// OperationId is the `operationId` field from the OpenAPI Specification, after going through a `nameNormalizer`, and will be used to generate function names
	OperationId string

	PathParams      []ParameterDefinition // Parameters in the path, eg, /path/:param
	HeaderParams    []ParameterDefinition // Parameters in HTTP headers
	QueryParams     []ParameterDefinition // Parameters in the query, /path?param
	CookieParams    []ParameterDefinition // Parameters in cookies
	TypeDefinitions []TypeDefinition      // These are all the types we need to define for this operation
	BodyRequired    bool
	Bodies          []RequestBodyDefinition // The list of bodies for which to generate handlers.
	Responses       []ResponseDefinition    // The list of responses that can be accepted by handlers.
	Summary         string                  // Summary string from Swagger, used to generate a comment
	Method          string                  // GET, POST, DELETE, etc.
	Path            string                  // The Swagger path for the operation, like /resource/{id}
	// SpecOrder is the source line on which this operation's path is
	// declared in the spec, used to register routes in the order the paths
	// appear in the spec rather than sorted (issue #1887). Zero when the
	// source location is unavailable (e.g. a programmatically-built spec),
	// in which case route registration falls back to the default order.
	SpecOrder   int
	Spec        *model.Operation
	IsAlias     bool   // True when this path is a $ref alias of another path item
	AliasTarget string // When IsAlias is true, this is the OperationId of the canonical operation (for route registration to reference the correct wrapper)
	PathItemRef string // The path item's $ref (if any); used to qualify externally-loaded schemas referenced from this operation's responses
	// SecurityRequirements are the ways a request may satisfy the
	// operation's security, any one of which is enough. Empty when the
	// operation declares no security.
	SecurityRequirements []SecurityRequirementDefinition

	// IsWebhook is true when this OperationDefinition was sourced from
	// spec.Webhooks (OpenAPI 3.1+). Webhook operations have no path
	// template; the target URL is supplied per-call by the initiator.
	IsWebhook bool
	// WebhookName is the spec.Webhooks map key when IsWebhook is true.
	WebhookName string

	// IsCallback is true when this OperationDefinition was sourced from
	// a parent operation's `callbacks:` block (OpenAPI 3.0+). Callback
	// operations have no path template at codegen time; the target URL
	// is the runtime callback URL discovered via the spec's callback
	// expression (typically a field on the parent operation's request
	// body) and is supplied per-call by the initiator.
	IsCallback bool
	// CallbackName is the parent operation's `callbacks:` map key
	// (e.g. "treePlanted") when IsCallback is true.
	CallbackName string
}

OperationDefinition describes an Operation

func CallbackOperationDefinitions

func CallbackOperationDefinitions(swagger *model.Document) ([]OperationDefinition, error)

CallbackOperationDefinitions extracts OpenAPI callback operations from spec.Paths.<path>.<method>.Callbacks into the same OperationDefinition shape used for path operations, so they flow through the same downstream pipeline (body / response generation, type definitions, etc.) but are routed to callback-specific templates.

Callbacks have been part of the OpenAPI spec since 3.0, so this is not gated on version: any spec that declares callbacks gets them generated. The spec shape:

paths:
  /api/plant_tree:
    post:
      operationId: PlantTree
      callbacks:
        treePlanted:                 # the callback map key
          '{$request.body#/url}':    # the runtime URL expression
            post:
              operationId: TreePlanted

Each leaf operation (the inner `post:` above) becomes one OperationDefinition with IsCallback=true and CallbackName set to the outer map key ("treePlanted"). The codegen does not interpret the URL expression itself -- the caller of the generated CallbackInitiator supplies the resolved target URL at runtime (the same way it would for a webhook).

func OperationDefinitions

func OperationDefinitions(swagger *model.Document) ([]OperationDefinition, error)

func WebhookOperationDefinitions

func WebhookOperationDefinitions(swagger *model.Document) ([]OperationDefinition, error)

WebhookOperationDefinitions extracts OpenAPI 3.1+ webhook operations from swagger.Webhooks into the same OperationDefinition shape used for path operations, so they flow through the same downstream pipeline (body / response generation, type definitions, etc.) but are routed to webhook-specific templates.

Webhooks is only populated for OpenAPI 3.1+ documents, so a missing/empty map naturally short-circuits this for 3.0 specs without an explicit version check.

The result mirrors OperationDefinitions in structure, minus the path-alias logic (webhooks have no path template) and the path- parameter extraction (webhooks have no path params).

func (*OperationDefinition) AllParams

func (o *OperationDefinition) AllParams() []ParameterDefinition

AllParams returns all parameters

func (OperationDefinition) ClientMethodVariants

func (o OperationDefinition) ClientMethodVariants() []ClientMethodVariant

ClientMethodVariants returns the precomputed client method variants for this operation: the generic variant first, then one per client-supported request body. It is consumed by client.tmpl and client-with-responses.tmpl.

func (*OperationDefinition) DeprecationComment

func (o *OperationDefinition) DeprecationComment() string

DeprecationComment returns a Go-style deprecation comment if the operation is deprecated, otherwise returns an empty string.

func (OperationDefinition) GenerateFunctionComment

func (o OperationDefinition) GenerateFunctionComment(originalFunctionName string, functionSuffix string, isFunctionWithResponses bool) string

GenerateFunctionComment returns a full Godoc-style multi-line comment with: - the Summary, if present, as the first line of the comment - if not present, an indication of the HTTP call this corresponds with - the Description, if present - whether this function takes a body and a content type

Takes originalFunctionName (the OperationId or the function name being generated for this Operation), a suffix (if necessary) and whether this is being generated for ClientInterface or ClientWithResponsesInterface

func (OperationDefinition) GenericClientVariant

func (o OperationDefinition) GenericClientVariant() ClientMethodVariant

GenericClientVariant returns the generic (bodyless or "WithBody") client method variant, which every operation always has as its first variant. The request-builder template uses it for the New{OperationId}Request{Suffix} signature.

func (*OperationDefinition) GetResponseTypeDefinitions

func (o *OperationDefinition) GetResponseTypeDefinitions() ([]ResponseTypeDefinition, error)

GetResponseTypeDefinitions produces a list of type definitions for a given Operation for the response types which we know how to parse. These will be turned into fields on a response object for automatic deserialization of responses in the generated Client code. See "client-with-responses.tmpl".

func (*OperationDefinition) HandlerName

func (o *OperationDefinition) HandlerName() string

HandlerName returns the OperationId of the server-side handler method that serves the operation. For alias operations this is the canonical operation's ID, since the alias doesn't generate its own handler.

func (*OperationDefinition) HasBody

func (o *OperationDefinition) HasBody() bool

HasBody is called by the template engine to determine whether to generate body marshaling code on the client. This is true for all body types, whether we generate types for them.

func (*OperationDefinition) HasMaskedRequestContentTypes

func (o *OperationDefinition) HasMaskedRequestContentTypes() bool

func (*OperationDefinition) Params

Params returns the list of all parameters except Path parameters. Path parameters are handled differently from the rest, since they're mandatory.

func (OperationDefinition) RequiresParamObject

func (o OperationDefinition) RequiresParamObject() bool

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

func (o OperationDefinition) SecurityRequirementsLiteral() string

SecurityRequirementsLiteral returns the operation's security requirements as a []SecurityRequirement composite literal with the type elided. This is used from the template engine.

func (OperationDefinition) SourceName

func (o OperationDefinition) SourceName() string

SourceName returns WebhookName when IsWebhook, CallbackName when IsCallback, or empty otherwise. Templates use this to label the emitted handler uniformly without branching on which kind of source the operation came from.

func (*OperationDefinition) SummaryAsComment

func (o *OperationDefinition) SummaryAsComment(prefix string) string

SummaryAsComment returns the Operations summary as a Godoc-style multi line comment

type OutputOptions

type OutputOptions struct {
	// Whether to skip go imports on the generated code
	SkipFmt bool `yaml:"skip-fmt,omitempty"`
	// Whether to skip pruning unused components on the generated code
	SkipPrune bool `yaml:"skip-prune,omitempty"`
	// SkipFormatTypes stops the models from declaring the types that string
	// formats map to by default (OpenAPIDate, OpenAPIDuration, OpenAPIEmail
	// and OpenAPIFile). Set it when another generated file in the same
	// package already declares them, so they aren't declared twice.
	SkipFormatTypes bool `yaml:"skip-format-types,omitempty"`
	// When set to true, always prefix enum values with their type name instead of only
	// when typenames would be conflicting.
	AlwaysPrefixEnumValues bool `yaml:"always-prefix-enum-values,omitempty"`
	// AllowUnexportedStructFieldNames makes it possible to output structs that have fields that are unexported.
	//
	// This is expected to be used in conjunction with `x-go-name` and `x-oapi-codegen-only-honour-go-name` to override the resulting output field name, and `x-oapi-codegen-extra-tags` to not produce JSON tags for `encoding/json`, such as:
	//
	//  “`yaml
	//   id:
	//     type: string
	//     x-go-name: accountIdentifier
	//     x-oapi-codegen-extra-tags:
	//       json: "-"
	//     x-oapi-codegen-only-honour-go-name: true
	//   “`
	//
	// NOTE that this can be confusing to users of your OpenAPI specification, who may see a field present and therefore be expecting to see/use it in the request/response, without understanding the nuance of how `oapi-codegen` generates the code.
	AllowUnexportedStructFieldNames bool `yaml:"allow-unexported-struct-field-names,omitempty"`
	// SkipEnumValidate disables the generation of the `Valid()` method on
	// enum types. By default each generated enum type includes a `Valid()
	// bool` method which returns true when the value matches one of the
	// defined constants; set this to true to suppress that method when it
	// conflicts with user-defined methods of the same name.
	SkipEnumValidate bool `yaml:"skip-enum-validate,omitempty"`
	// SkipEnumViaOneOf disables detection of the OpenAPI 3.1 enum-via-oneOf
	// idiom: a schema with `type: string|integer` and `oneOf:` members that
	// each carry `const` + `title` will normally be emitted as a Go enum with
	// named constants. Set this to true to fall through to the standard union
	// generator instead.
	SkipEnumViaOneOf bool `yaml:"skip-enum-via-oneof,omitempty"`
	// LenientUnionAccessors makes a union's As* methods ignore the properties
	// a variant with `additionalProperties: false` doesn't declare, as they
	// do for any other variant. By default such a variant's As* returns an
	// error for a property that neither the variant nor anything else in the
	// union's object declares, so that data of another variant isn't taken
	// for it.
	LenientUnionAccessors bool `yaml:"lenient-union-accessors,omitempty"`
	// Only include operations that have one of these tags. Ignored when empty.
	IncludeTags []string `yaml:"include-tags,omitempty"`
	// Exclude operations that have one of these tags. Ignored when empty.
	ExcludeTags []string `yaml:"exclude-tags,omitempty"`
	// Only include operations that have one of these operation-ids. Ignored when empty.
	IncludeOperationIDs []string `yaml:"include-operation-ids,omitempty"`
	// Exclude operations that have one of these operation-ids. Ignored when empty.
	ExcludeOperationIDs []string `yaml:"exclude-operation-ids,omitempty"`
	// Override built-in templates from user-provided files
	UserTemplates map[string]string `yaml:"user-templates,omitempty"`

	// Exclude from generation schemas with given names. Ignored when empty.
	ExcludeSchemas []string `yaml:"exclude-schemas,omitempty"`
	// The suffix used for responses types
	ResponseTypeSuffix string `yaml:"response-type-suffix,omitempty"`
	// Override the default generated client type with the value
	ClientTypeName string `yaml:"client-type-name,omitempty"`
	// AdditionalInitialisms is a list of additional initialisms to use when generating names.
	// NOTE that this has no effect unless the `name-normalizer` is set to `ToCamelCaseWithInitialisms`
	AdditionalInitialisms []string `yaml:"additional-initialisms,omitempty"`
	// StreamingContentTypes are regex patterns matched against response
	// Content-Type to decide when to generate a flush-per-chunk streaming
	// response path. User-provided patterns are merged with the defaults
	// (text/event-stream, application/jsonl, application/x-ndjson); invalid
	// regexes fail Validate().
	StreamingContentTypes []string `yaml:"streaming-content-types,omitempty"`
	// Whether to generate nullable type for nullable fields
	NullableType bool `yaml:"nullable-type,omitempty"`

	// DisableTypeAliasesForType allows defining which OpenAPI `type`s will explicitly not use type aliases
	// Currently supports:
	//   "array"
	DisableTypeAliasesForType []string `yaml:"disable-type-aliases-for-type"`

	// SkipResponseBodyGetters decides whether to generate getter methods for response bodies.
	SkipResponseBodyGetters bool `yaml:"skip-response-body-getters,omitempty"`

	// NameNormalizer is the method used to normalize Go names and types, for instance converting the text `MyApi` to `MyAPI`. Corresponds with the constants defined for `codegen.NameNormalizerFunction`
	NameNormalizer string `yaml:"name-normalizer,omitempty"`

	// Overlay defines configuration for the OpenAPI Overlay (https://github.com/OAI/Overlay-Specification) to manipulate the OpenAPI specification before generation. This allows modifying the specification without needing to apply changes directly to it, making it easier to keep it up-to-date.
	Overlay OutputOptionsOverlay `yaml:"overlay"`

	// StructTags configures which struct tags are generated on struct fields and how their
	// values are rendered. Each entry is a tag name plus a Go text/template evaluated
	// against the field (see StructTagInfo for the available variables). Entries are
	// merged by name on top of the defaults, so a `json` entry replaces the default json
	// template while new names add tags. Tags render in alphabetical order; a template
	// that renders to the empty string suppresses that tag on that field.
	StructTags StructTagsConfig `yaml:"struct-tags,omitempty"`

	// ClientResponseBytesFunction decides whether to enable the generation of a `Bytes()` method on response objects for `ClientWithResponses`
	ClientResponseBytesFunction bool `yaml:"client-response-bytes-function,omitempty"`

	// SkipClientResponseContentType disables the generation of a `ContentType()` method on response objects for `ClientWithResponses`, which is otherwise generated by default.
	SkipClientResponseContentType bool `yaml:"skip-client-response-content-type,omitempty"`

	// PreferSkipOptionalPointer allows defining at a global level whether to omit the pointer for a type to indicate that the field/type is optional.
	// This is the same as adding `x-go-type-skip-optional-pointer` to each field (manually, or using an OpenAPI Overlay)
	PreferSkipOptionalPointer bool `yaml:"prefer-skip-optional-pointer,omitempty"`

	// PreferSkipOptionalPointerWithOmitzero allows generating the `omitzero` JSON tag types that would have had an optional pointer.
	// This is the same as adding `x-omitzero` to each field (manually, or using an OpenAPI Overlay).
	// A field can set `x-omitzero: false` to disable the `omitzero` JSON tag.
	// NOTE that this must be used alongside `prefer-skip-optional-pointer`, otherwise makes no difference.
	PreferSkipOptionalPointerWithOmitzero bool `yaml:"prefer-skip-optional-pointer-with-omitzero,omitempty"`

	// PreferSkipOptionalPointerOnContainerTypes allows disabling the generation of an "optional pointer" for an optional field that is a container type (such as a slice or a map), which ends up requiring an additional, unnecessary, `... != nil` check
	PreferSkipOptionalPointerOnContainerTypes bool `yaml:"prefer-skip-optional-pointer-on-container-types,omitempty"`

	// ResolveTypeNameCollisions, when set to true, automatically renames
	// types that collide across different OpenAPI component sections
	// (schemas, parameters, requestBodies, responses, headers) by appending
	// a suffix based on the component section (e.g., "Parameter", "Response",
	// "RequestBody"). It also detects collisions between component types and
	// client response wrapper types (e.g., issue #1474). Without this, the
	// codegen will error on duplicate type names, requiring manual resolution
	// via x-go-name.
	ResolveTypeNameCollisions bool `yaml:"resolve-type-name-collisions,omitempty"`

	// GenerateTypesForAnonymousSchemas, when true, causes oapi-codegen to
	// emit a named Go type for every inline schema that would otherwise
	// generate as an anonymous `struct { ... }`. The type's name is derived
	// from the schema path (e.g. `GetRolesIdResponseBody_Data`). Default
	// false. Equivalent to adding `x-go-type-name` to every inline schema;
	// when both are present at the same site, `x-go-type-name` wins.
	//
	// The hoisted named types are declared by the same emission path that
	// `generate.models` controls. In a single-config setup, this flag is
	// only effective when `generate.models: true` is also set in the same
	// config — otherwise the generated client/server code will reference
	// type names that no emission path declares, and `go build` will fail.
	//
	// In a multi-config setup where one config emits `models` and a
	// sibling config emits a client or server framework into the same
	// Go package, the flag must be set consistently across all configs.
	// Mixing the flag (set in one config, omitted in the other) causes
	// references and declarations to disagree on whether to use the
	// hoisted name or the inline struct. The sibling config that does
	// not emit `models` will produce a warning at codegen time noting
	// that it does not declare the hoisted names; you can ignore the
	// warning when the sibling models config will declare them.
	//
	// See https://github.com/oapi-codegen/oapi-codegen/issues/1139
	GenerateTypesForAnonymousSchemas bool `yaml:"generate-types-for-anonymous-schemas,omitempty"`

	// TypeMapping allows customizing OpenAPI type/format to Go type mappings.
	// User-specified mappings are merged on top of the defaults.
	TypeMapping *TypeMapping `yaml:"type-mapping,omitempty"`

	// ContentTypes maps a short name to a list of regex patterns matched
	// against request/response media types. When a media type matches a
	// pattern, the short name is used as the tag in generated type names
	// (e.g. mapping `V1: ['^application/vnd\.mycompany\.v1\+json$']` produces
	// `FindPetsV1RequestBody` instead of the default name derived from the
	// media type), and models are generated for that media type even when it
	// isn't one of the built-in supported types. Wire-level handling
	// (marshaling, binding) is still derived from the media type itself, so
	// renaming e.g. `application/x-www-form-urlencoded` keeps form encoding.
	//
	// Typed fields on client response structs are only generated for media
	// types the client knows how to deserialize (JSON-like, YAML and XML).
	// Mapping any other media type (e.g. `CSV: ['^text/csv$']`) generates
	// models and named request bodies, but client responses for it expose
	// only the raw body.
	//
	// User entries are merged on top of the built-in defaults by key
	// replacement (pattern lists are not merged):
	//
	//   JSON:      ['^application/json$']
	//   Formdata:  ['^application/x-www-form-urlencoded$']
	//   Multipart: ['^multipart/']
	//   Text:      ['^text/plain$']
	//
	// An empty pattern list disables a key, so renaming a built-in means
	// adding the new key and emptying the old one, e.g.
	// `Form: ['^application/x-www-form-urlencoded$']` plus `Formdata: []` —
	// otherwise the media type matches under both short names, which is a
	// generation-time error. Media types that match no pattern keep the
	// remaining built-in behavior (vendored `+json` types get a name derived
	// from the media type; anything else is passed through untyped).
	// NOTE that mapping two media types that appear on the same request or
	// response to the same short name produces colliding type names.
	ContentTypes map[string][]string `yaml:"content-types,omitempty"`
}

OutputOptions are used to modify the output code in some way.

func (OutputOptions) Validate

func (oo OutputOptions) Validate() map[string]string

type OutputOptionsOverlay

type OutputOptionsOverlay struct {
	Path string `yaml:"path"`

	// Strict defines whether the Overlay should be applied in a strict way, highlighting any actions that will not take any effect. This can, however, lead to more work when testing new actions in an Overlay, so can be turned off with this setting.
	// Defaults to true.
	Strict *bool `yaml:"strict,omitempty"`
}

type ParamCodec

type ParamCodec struct {
	// Scalar is the codec of the value, or of an array's elements.
	Scalar *ScalarCodec
	// IsArray reports whether the value is an array of Scalar.
	IsArray bool
	// Object is the codec of an object value, in place of Scalar.
	Object *ObjectCodec
	// contains filtered or unexported fields
}

ParamCodec binds and styles a parameter's value: a scalar, or an array of scalars, in the parameter's location, style and explode.

func (*ParamCodec) BindList

func (c *ParamCodec) BindList(list, dst string) string

BindList returns statements that bind each string of list, an expression of type []string, into the elements of dst, an array, and set err when one can't be.

func (*ParamCodec) BindQuery

func (c *ParamCodec) BindQuery(values, dst string) string

BindQuery returns statements that bind values, the values of the query parameter, of which there is at least one, into dst, and set err when they can't be.

func (*ParamCodec) BindQueryObject

func (c *ParamCodec) BindQueryObject(query, dst string) string

BindQueryObject returns statements that bind the properties of an exploded query object, each a query parameter of its own in query_, into dst, set found_ when one is present, and set err when one can't be bound. An object whose properties aren't known, or that only has additional properties, can't be told apart from the other query parameters, so is never found, as with the runtime library.

func (*ParamCodec) BindStyled

func (c *ParamCodec) BindStyled(src, dst string) string

BindStyled returns statements that bind src, the value of a path, header or cookie parameter, into dst, and set err when it can't: a scalar is the value without the style's prefix, an array its parts.

The runtime library read a value with an UnmarshalText method whole, prefix and all, so a `label` or `matrix` date, time, UUID or union never bound; the generated code strips the prefix first.

func (*ParamCodec) ExplodedQueryObject

func (c *ParamCodec) ExplodedQueryObject() bool

ExplodedQueryObject reports whether the parameter is an exploded object in a query, whose properties are query parameters of their own: see BindQueryObject.

func (*ParamCodec) Style

func (c *ParamCodec) Style(v, out string) string

Style returns statements that set out to the styled value v of a path, header or cookie parameter, escaped for its location, and set err when it can't be formatted.

func (*ParamCodec) StyleQuery

func (c *ParamCodec) StyleQuery(v, fragments string) string

StyleQuery returns statements that append the styled value v of the query parameter to fragments, a []string of `key=value` query fragments, and set err when it can't be formatted.

The runtime library couldn't style a scalar in `spaceDelimited` or `pipeDelimited` style; the generated code styles it as `form`.

type ParameterDefinition

type ParameterDefinition struct {
	ParamName string // The original json parameter name, eg param_name
	In        string // Where the parameter is defined - path, header, cookie, query
	Required  bool   // Is this a required parameter?
	Spec      *model.Parameter
	Schema    Schema

	// Shared is true for a parameter declared at the path-item level, which
	// is inherited by every method on the path. Its helper types are declared
	// once for the path item rather than once per operation, so operation type
	// collection skips them (issue #2090).
	Shared bool
	// contains filtered or unexported fields
}

func CombineOperationParameters

func CombineOperationParameters(globalParams []ParameterDefinition, localParams []ParameterDefinition) ([]ParameterDefinition, error)

CombineOperationParameters combines the Parameters defined at a global level (Parameters defined for all methods on a given path) with the Parameters defined at a local level (Parameters defined for a specific path), preferring the locally defined parameter over the global one

func DescribeParameters

func DescribeParameters(params model.Parameters, path []string) ([]ParameterDefinition, error)

DescribeParameters walks the given parameters dictionary, and generates the above descriptors into a flat list. This makes it a lot easier to traverse the data in the template engine.

func FilterParameterDefinitionByType

func FilterParameterDefinitionByType(params []ParameterDefinition, in string) []ParameterDefinition

FilterParameterDefinitionByType returns the subset of the specified parameters which are of the specified type.

func SortParamsByPath

func SortParamsByPath(path string, in []ParameterDefinition) ([]ParameterDefinition, error)

SortParamsByPath reorders the given parameter definitions to match those in the path URI. If a parameter appears more than once in the path (e.g. Keycloak's /clients/{client-uuid}/roles/{role-name}/composites/clients/{client-uuid}), duplicates are removed and only the first occurrence determines the order.

func (ParameterDefinition) Codec

func (pd ParameterDefinition) Codec() *ParamCodec

Codec returns the codec that binds and styles the parameter, or nil when the parameter isn't styled: its value is in a content type, such as JSON.

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

func (pd ParameterDefinition) HasOptionalPointer() bool

HasOptionalPointer indicates whether the generated property has an optional pointer associated with it. This takes into account the `x-go-type-skip-optional-pointer` extension, allowing a parameter definition to control whether the pointer should be skipped.

func (ParameterDefinition) IndirectOptional deprecated

func (pd ParameterDefinition) IndirectOptional() bool

Deprecated: Use HasOptionalPointer, as it is clearer what the intent is.

func (ParameterDefinition) IsJson

func (pd ParameterDefinition) IsJson() bool

func (ParameterDefinition) IsPassThrough

func (pd ParameterDefinition) IsPassThrough() bool

func (ParameterDefinition) IsStyled

func (pd ParameterDefinition) IsStyled() bool

func (ParameterDefinition) JsonTag

func (pd ParameterDefinition) JsonTag() string

JsonTag generates the struct tag annotation for a parameter field on a server RequestObject struct. If Parameter Foo is marshaled to json as "foo", this will create the annotation 'json:"foo"'. Tags configured via output-options.struct-tags are rendered too. It also includes any additional struct tags from x-oapi-codegen-extra-tags at the parameter or schema level (parameter-level takes precedence).

func (ParameterDefinition) PathSegmentStmts

func (pd ParameterDefinition) PathSegmentStmts() string

PathSegmentStmts is the Go that splits a mixed path segment, or empty when this parameter occupies its segment alone. The text starts with a newline so it can be appended to the parameter's variable declaration without changing the source generated for whole-segment parameters.

func (ParameterDefinition) PathValueExpr

func (pd ParameterDefinition) PathValueExpr() string

PathValueExpr is the Go expression for this path parameter's raw text.

func (ParameterDefinition) RequiresNilCheck

func (pd ParameterDefinition) RequiresNilCheck() bool

RequiresNilCheck indicates whether the generated property should have a nil check performed on it before other checks. This should be used in templates when performing `nil` checks, but NOT when i.e. determining if there should be an optional pointer given to the type - in that case, use `HasOptionalPointer`

func (ParameterDefinition) SanitizedParamName

func (pd ParameterDefinition) SanitizedParamName() string

SanitizedParamName returns the parameter name sanitized to be a valid Go identifier. This is needed for routers like net/http's ServeMux where path wildcards (e.g. {name}) must be valid Go identifiers. For the original OpenAPI parameter name (e.g. for error messages or JSON tags), use ParamName.

func (ParameterDefinition) Style

func (pd ParameterDefinition) Style() string

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.

func (ParameterDefinition) ZeroValueIsNil

func (pd ParameterDefinition) ZeroValueIsNil() bool

ZeroValueIsNil is a helper function to determine if the given Go type used for this property has `nil` as its Go zero value. Slices (OpenAPI `array`) and maps (OpenAPI `object` with only `additionalProperties`, rendered as `map[K]V`) both satisfy this — templates use it to decide whether to emit a nil-check before reading the field.

type ParameterDefinitions

type ParameterDefinitions []ParameterDefinition

func (ParameterDefinitions) FindByName

func (p ParameterDefinitions) FindByName(name string) *ParameterDefinition

type Property

type Property struct {
	Description   string
	JsonFieldName string
	Schema        Schema
	Required      bool
	Nullable      bool
	ReadOnly      bool
	WriteOnly     bool
	NeedsFormTag  bool
	Extensions    map[string]any
	Deprecated    bool
	// contains filtered or unexported fields
}

func (Property) GoFieldName

func (p Property) GoFieldName() string

func (Property) GoTypeDef

func (p Property) GoTypeDef() string

func (Property) HasOptionalPointer

func (p Property) HasOptionalPointer() bool

HasOptionalPointer indicates whether the generated property has an optional pointer associated with it. This takes into account the `x-go-type-skip-optional-pointer` extension, allowing a parameter definition to control whether the pointer should be skipped.

func (Property) IsPointer

func (p Property) IsPointer() bool

IsPointer reports whether the generated Go field for this property is pointer-typed, i.e. GoTypeDef renders with a leading `*`. Templates use it when assigning a value to the field requires taking an address first.

func (Property) RequiresNilCheck

func (p Property) RequiresNilCheck() bool

RequiresNilCheck indicates whether the generated property should have a nil check performed on it before other checks. This should be used in templates when performing `nil` checks, but NOT when i.e. determining if there should be an optional pointer given to the type - in that case, use `HasOptionalPointer`

func (Property) ZeroValueIsNil

func (p Property) ZeroValueIsNil() bool

ZeroValueIsNil is a helper function to determine if the given Go type used for this property has `nil` as its Go zero value. Slices (OpenAPI `array`) and maps (OpenAPI `object` with only `additionalProperties`, rendered as `map[K]V`) both satisfy this — the custom-marshal templates use it to decide whether to emit a nil-check before reading the field.

type ReceiverTemplateData

type ReceiverTemplateData struct {
	Prefix      string // "Webhook" or "Callback"
	PrefixLower string // lowercase form of Prefix, for prose
	Operations  []OperationDefinition
}

ReceiverTemplateData is the input to the per-framework webhook / callback receiver template. Prefix selects between "Webhook" and "Callback" (and the lowercase form for prose), so a single template per framework handles both kinds.

func NewReceiverTemplateData

func NewReceiverTemplateData(prefix string, ops []OperationDefinition) ReceiverTemplateData

NewReceiverTemplateData builds the template input for the given prefix ("Webhook" or "Callback") and operation list.

type RefWrapper

type RefWrapper struct {
	Ref       string
	HasValue  bool
	SourceRef any
}

type RequestBodyDefinition

type RequestBodyDefinition struct {
	// Is this body required, or optional?
	Required bool

	// This is the schema describing this body
	Schema Schema

	// When we generate type names, we need a Tag for it, such as JSON, in
	// which case we will produce "JSONBody".
	NameTag string

	// This is the content type corresponding to the body, eg, application/json
	ContentType string

	// Whether this is the default body type. For an operation named OpFoo, we
	// will not add suffixes like OpFooJSONBody for this one.
	Default bool

	// Contains encoding options for formdata
	Encoding map[string]RequestBodyEncoding

	// Deprecated indicates the parent operation is deprecated, so this body
	// type alias should be marked deprecated too.
	Deprecated bool

	// DeprecationReason is propagated from the parent operation's x-deprecated-reason.
	DeprecationReason string
}

RequestBodyDefinition describes a request body

func (RequestBodyDefinition) CustomType

func (r RequestBodyDefinition) CustomType() bool

CustomType returns whether the body is a custom inline type, or pre-defined. This is poorly named, but it's here for compatibility reasons post-refactoring TODO: clean up the templates code, it can be simpler.

func (RequestBodyDefinition) GenerateFunctionComment

func (r RequestBodyDefinition) GenerateFunctionComment(originalFunctionName string, parent OperationDefinition, functionSuffix string, isFunctionWithResponses bool) string

GenerateFunctionComment returns a full Godoc-style multi-line comment with: - the Summary, if present, as the first line of the comment - if not present, an indication of the HTTP call this corresponds with - whether this function takes a body and a content type

Takes originalFunctionName (the OperationId or the function name being generated for this Operation), a suffix (if necessary) and whether this is being generated for ClientInterface or ClientWithResponsesInterface

func (RequestBodyDefinition) HasModel

func (r RequestBodyDefinition) HasModel() bool

HasModel returns true when a Go model type is generated for this body — either a built-in supported media type or one matched by output-options.content-types.

func (RequestBodyDefinition) IsFixedContentType

func (r RequestBodyDefinition) IsFixedContentType() bool

IsFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol

func (RequestBodyDefinition) IsFormdata

func (r RequestBodyDefinition) IsFormdata() bool

IsFormdata returns whether this body is form-urlencoded

func (RequestBodyDefinition) IsJSON

func (r RequestBodyDefinition) IsJSON() bool

IsJSON returns whether this is a JSON media type, for instance: - application/json - application/vnd.api+json - application/*+json

func (RequestBodyDefinition) IsMultipart

func (r RequestBodyDefinition) IsMultipart() bool

IsMultipart returns whether this body is a multipart media type

func (RequestBodyDefinition) IsSupported

func (r RequestBodyDefinition) IsSupported() bool

IsSupported returns true if we support this content type for server. Otherwise io.Reader will be generated. Wire-level support is derived from the media type, not from NameTag, so user-configured short names (output-options.content-types) don't change how a body is bound.

func (RequestBodyDefinition) IsSupportedByClient

func (r RequestBodyDefinition) IsSupportedByClient() bool

IsSupportedByClient returns true if we support this content type for client. Otherwise only generic method will ge generated

func (RequestBodyDefinition) IsText

func (r RequestBodyDefinition) IsText() bool

IsText returns whether this body is plain text

func (RequestBodyDefinition) Suffix

func (r RequestBodyDefinition) Suffix() string

When we're generating multiple functions which relate to request bodies, this generates the suffix. Such as Operation DoFoo would be suffixed with DoFooWithXMLBody.

func (RequestBodyDefinition) TypeDef

func (r RequestBodyDefinition) TypeDef(opID string) *TypeDefinition

TypeDef returns the Go type definition for a request body

type RequestBodyEncoding

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

type ResolvedName

type ResolvedName struct {
	Schema    *GatheredSchema
	GoName    string // The resolved Go type name
	Candidate string // The initial candidate name before collision resolution
	Pinned    bool   // True if name came from x-go-name; must not be renamed
}

ResolvedName holds the final Go type name assigned to a gathered schema.

type ResponseContentDefinition

type ResponseContentDefinition struct {
	// This is the schema describing this content
	Schema Schema

	// This is the content type corresponding to the body, eg, application/json
	ContentType string

	// When we generate type names, we need a Tag for it, such as JSON, in
	// which case we will produce "Response200JSONContent".
	NameTag string

	// NeedsBodyWrapper is true when a schema-backed server response cannot use
	// its generated Go type directly: as a method receiver, or, for a reusable
	// response envelope, as an embedded field.
	NeedsBodyWrapper bool
}

func (ResponseContentDefinition) CanUseDirectResponseType

func (r ResponseContentDefinition) CanUseDirectResponseType() bool

CanUseDirectResponseType reports whether the server response can use its wire type directly instead of exposing a Body field.

func (ResponseContentDefinition) HasFixedContentType

func (r ResponseContentDefinition) HasFixedContentType() bool

HasFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol

func (ResponseContentDefinition) IsFormdata

func (r ResponseContentDefinition) IsFormdata() bool

IsFormdata returns whether this content is form-urlencoded

func (ResponseContentDefinition) IsJSON

func (r ResponseContentDefinition) IsJSON() bool

IsJSON returns whether this is a JSON media type, for instance: - application/json - application/vnd.api+json - application/*+json

func (ResponseContentDefinition) IsMultipart

func (r ResponseContentDefinition) IsMultipart() bool

IsMultipart returns whether this content is a multipart media type

func (ResponseContentDefinition) IsStreamingContentType

func (r ResponseContentDefinition) IsStreamingContentType() bool

IsStreamingContentType reports whether this response's media type matches any configured streaming-content-types pattern (defaults merged with OutputOptions.StreamingContentTypes). Templates use this to emit a flush-per-chunk streaming path instead of a buffered io.Copy.

func (ResponseContentDefinition) IsSupported

func (r ResponseContentDefinition) IsSupported() bool

IsSupported returns true if we know how to serialize this content type. Otherwise io.Reader will be generated. Wire-level support is derived from the media type, not from NameTag, so user-configured short names (output-options.content-types) don't change how a response is written.

func (ResponseContentDefinition) IsText

func (r ResponseContentDefinition) IsText() bool

IsText returns whether this content is plain text

func (ResponseContentDefinition) NameTagOrContentType

func (r ResponseContentDefinition) NameTagOrContentType() string

func (ResponseContentDefinition) TypeDef

func (r ResponseContentDefinition) TypeDef(opID string, statusCode int) *TypeDefinition

TypeDef returns the Go type definition for a request body

type ResponseDefinition

type ResponseDefinition struct {
	StatusCode  string
	Description string
	Contents    []ResponseContentDefinition
	Headers     []ResponseHeaderDefinition
	Ref         string
}

func GenerateResponseDefinitions

func GenerateResponseDefinitions(operationID string, responses map[string]*model.ResponseRef, pathItemRef string) ([]ResponseDefinition, error)

func (ResponseDefinition) GoName

func (r ResponseDefinition) GoName() string

func (ResponseDefinition) HasFixedStatusCode

func (r ResponseDefinition) HasFixedStatusCode() bool

func (ResponseDefinition) IsExternalRef

func (r ResponseDefinition) IsExternalRef() bool

func (ResponseDefinition) IsRef

func (r ResponseDefinition) IsRef() bool

type ResponseHeaderDefinition

type ResponseHeaderDefinition struct {
	Name   string
	GoName string
	Schema Schema
	// Style and Explode mirror the serialization controls on the OpenAPI header
	// object. A response header is always serialized as if it were `in: header`,
	// so these default to "simple" / false when the spec omits them.
	Style             string
	Explode           bool
	Required          bool
	Nullable          bool
	Deprecated        bool
	DeprecationReason string
}

func (ResponseHeaderDefinition) Codec

Codec returns the codec that binds and styles the response header.

func (ResponseHeaderDefinition) DeprecationComment

func (h ResponseHeaderDefinition) DeprecationComment() string

DeprecationComment returns a Go-style deprecation comment if the header is deprecated, otherwise returns an empty string.

func (ResponseHeaderDefinition) GoTypeDef

func (h ResponseHeaderDefinition) GoTypeDef() string

GoTypeDef returns the Go type string for this header, applying pointer or nullable wrapping based on the Required/Nullable fields and global config.

func (ResponseHeaderDefinition) IsNullable

func (h ResponseHeaderDefinition) IsNullable() bool

IsNullable returns true if the header type uses nullable.Nullable[T] rather than a pointer for optionality.

func (ResponseHeaderDefinition) IsOptional

func (h ResponseHeaderDefinition) IsOptional() bool

IsOptional returns true if this header's Go type is indirect (pointer or nullable wrapper), meaning the template should guard before calling w.Header().Set(). This must stay in sync with GoTypeDef().

type ResponseTypeDefinition

type ResponseTypeDefinition struct {
	TypeDefinition
	// The content type name where this is used, eg, application/json
	ContentTypeName string

	// The type name of a response model.
	ResponseName string

	AdditionalTypeDefinitions []TypeDefinition
}

ResponseTypeDefinition is an extension of TypeDefinition, specifically for response unmarshaling in ClientWithResponses.

type ScalarCodec

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

ScalarCodec binds and formats one scalar value of a parameter.

func (*ScalarCodec) Bind

func (c *ScalarCodec) Bind(src, dst string, asText bool) string

Bind returns statements that parse the string src into dst, an addressable variable of the codec's type, and set err when it can't. asText selects how a type with an UnmarshalText method is read: with it, as the whole value of a path, header or cookie parameter is, or as an object, as a query value or an array element is, which uses Bind if there is one and reads time.Time as RFC 3339 or a date.

func (*ScalarCodec) Format

func (c *ScalarCodec) Format(v, out, escape string) string

Format returns statements that set out to v, an expression of the codec's type, as text escaped by escape (a function name, or "" for none), and set err when it can't be formatted.

type Schema

type Schema struct {
	GoType  string // The Go type needed to represent the schema
	RefType string // If the type has a type name, this is set

	ArrayType *Schema // The schema of array element

	EnumValues map[string]string // Enum values

	Properties               []Property       // For an object, the fields with names
	HasAdditionalProperties  bool             // Whether we support additional properties
	AdditionalPropertiesType *Schema          // And if we do, their type
	AdditionalTypes          []TypeDefinition // We may need to generate auxiliary helper types, stored here

	SkipOptionalPointer bool // Some types don't need a * in front when they're optional

	Description string // The description of the element

	UnionElements []UnionElement // Possible elements of oneOf/anyOf union

	// UnionTextKinds lists the JSON types ("boolean", "integer", "number",
	// "string") of a union whose branches are all scalars, so that it can be
	// bound from a parameter's text; nil for any other union.
	UnionTextKinds []string

	// UnionVariantProperties lists, sorted, the JSON property names that the
	// union's branches declare. From* and Merge* drop these keys from the
	// union's additionalProperties, where UnmarshalJSON also puts them.
	UnionVariantProperties []string

	// UnionOwnedKeys is set for a union that combines several oneOfs or
	// anyOfs (see unionComponent): the JSON keys
	// each variant's own union owns, which From* replaces, keeping the other
	// unions' data, where for a single union it replaces all of it.
	UnionOwnedKeys map[UnionElement][]string

	// UnionRefComponents lists, for such a union, the unions that are a $ref
	// to a union type, which get As* and From* of their own.
	UnionRefComponents []UnionRefComponent

	// UnionAllowedKeys maps each variant with `additionalProperties: false`
	// to the JSON keys its As* allows: the variant's own, and those anything
	// else in the union's object declares (see closeUnionVariants). As* returns an error for any other key.
	UnionAllowedKeys map[UnionElement][]string

	Discriminator *Discriminator // Describes which value is stored in a union

	// If this is set, the schema will declare a type via alias, eg,
	// `type Foo = bool`. If this is not set, we will define this type via
	// type definition `type Foo bool`
	//
	// Can be overriden by the OutputOptions#DisableTypeAliasesForType field
	DefineViaAlias bool

	// The original OpenAPIv3 Schema.
	OAPISchema *model.Schema
	// contains filtered or unexported fields
}

Schema describes an OpenAPI schema, with lots of helper fields to use in the templating engine.

func GenerateGoSchema

func GenerateGoSchema(sref *model.SchemaRef, path []string) (Schema, error)

GenerateGoSchema converts an OpenAPI schema into a Go type definition.

It starts a fresh generation context, so a call made from outside the package behaves exactly as it always has. Within the package, prefer generateGoSchema so that the recursion state described by genContext survives the descent.

func (Schema) AdoptedProperties

func (s Schema) AdoptedProperties() []Property

AdoptedProperties returns the properties of a union that its From* and Merge* helpers fill from the variant: those that MarshalJSON always writes, so that a zero value would overwrite the variant's. The rest are written only when set, and otherwise the union data's value is written as it is.

func (Schema) ClosedUnionVariant

func (s Schema) ClosedUnionVariant(e UnionElement) bool

ClosedUnionVariant reports whether a variant's As* allows only some keys (see UnionAllowedKeys).

func (Schema) DiscriminatorCases

func (s Schema) DiscriminatorCases() []DiscriminatorCase

DiscriminatorCases returns the ValueByDiscriminator() switch arms for the union, sorted by discriminator value for deterministic output. Each mapping value is the Go type of a union element (the union generators write both from the same elementSchema.GoType), so it resolves to that element's Method(). A mapping value not found among the union elements is skipped: it has no As* helper to dispatch to, so no case is emitted and it falls through to the switch default.

func (Schema) DiscriminatorStampFor

func (s Schema) DiscriminatorStampFor(element UnionElement) *DiscriminatorStamp

DiscriminatorStampFor resolves the discriminator stamp for the given union element, or nil when nothing should be stamped: there is no discriminator, the mapping doesn't cover every element, or several mapping values share one element type, making the value ambiguous (the 1:1 gate keeps parity with issue #2071).

func (Schema) GetAdditionalTypeDefs

func (s Schema) GetAdditionalTypeDefs() []TypeDefinition

func (Schema) HasCustomMarshalJSON

func (s Schema) HasCustomMarshalJSON() bool

HasCustomMarshalJSON reports whether a named type declared over this schema position (the server response envelope, or a request-body wrapper) needs a delegating MarshalJSON/UnmarshalJSON pair.

The templates declare such a type either as an alias (`type X = Y`) or as a defined type (`type X Y`), keyed on whether the schema carries a RefType that lives in this package. An alias *is* Y, so Y's methods are already reachable and delegating would redeclare them. A defined type has an empty method set, so any marshalling Y generated is silently lost — that is the data loss behind https://github.com/oapi-codegen/oapi-codegen/issues/2549 — and we emit a delegator.

func (Schema) HasCustomMarshalJSONForRequestBody

func (s Schema) HasCustomMarshalJSONForRequestBody() bool

HasCustomMarshalJSONForRequestBody reports whether a named request body wrapper needs to delegate JSON marshaling to its underlying type.

The request-body template only asks when it declares the wrapper as a defined type (`type XJSONRequestBody XJSONBody`), and a defined type has an empty method set, so the answer is simply whether the underlying type has generated marshalling. That includes an inline body with properties and additionalProperties, which HasCustomMarshalJSON's alias shortcut would miss: the body is a local RefType, yet the wrapper is not an alias of it.

func (Schema) InUnionComponent

func (s Schema) InUnionComponent(e UnionElement) bool

InUnionComponent reports whether a variant belongs to one of several unions the schema combines (see UnionOwnedKeys).

func (Schema) IsExternalRef

func (s Schema) IsExternalRef() bool

func (Schema) IsPrimitive

func (s Schema) IsPrimitive() bool

IsPrimitive returns true if the schema represents a primitive OpenAPI type (string, integer, number, or boolean) as opposed to an object, array, or composed type.

func (Schema) IsRef

func (s Schema) IsRef() bool

func (Schema) TypeDecl

func (s Schema) TypeDecl() string

func (Schema) UnionAllowedKeysFor

func (s Schema) UnionAllowedKeysFor(e UnionElement) []string

UnionAllowedKeysFor returns the JSON keys a variant's As* allows (see UnionAllowedKeys).

func (Schema) UnionOwnedKeysFor

func (s Schema) UnionOwnedKeysFor(e UnionElement) []string

UnionOwnedKeysFor returns the JSON keys a variant's own union owns (see UnionOwnedKeys).

func (Schema) UnionTextAccepts

func (s Schema) UnionTextAccepts(kind string) bool

UnionTextAccepts reports whether a scalar union has a branch of the given JSON type; see UnionTextKinds.

func (Schema) UnionTextNonStringKinds

func (s Schema) UnionTextNonStringKinds() string

UnionTextNonStringKinds names the JSON types other than string that a scalar union accepts, for its UnmarshalText doc comment: "boolean or integer"; see UnionTextKinds.

type SchemaContext

type SchemaContext int

SchemaContext identifies where in the OpenAPI document a schema was found.

const (
	ContextComponentSchema SchemaContext = iota
	ContextComponentParameter
	ContextComponentRequestBody
	ContextComponentResponse
	ContextComponentHeader
	ContextOperationParameter
	ContextOperationRequestBody
	ContextOperationResponse
	ContextClientResponseWrapper
)

func (SchemaContext) String

func (sc SchemaContext) String() string

String returns a human-readable name for the context.

func (SchemaContext) Suffix

func (sc SchemaContext) Suffix() string

Suffix returns the suffix to use for collision resolution.

type SchemaDescriptor

type SchemaDescriptor struct {
	Fields                   []FieldDescriptor
	HasAdditionalProperties  bool
	AdditionalPropertiesType string
}

SchemaDescriptor describes a Schema, a type definition.

type SchemaPath

type SchemaPath []string

SchemaPath represents the document location of a schema, e.g. ["components", "schemas", "Pet", "properties", "name"].

func (SchemaPath) String

func (sp SchemaPath) String() string

String returns the path joined with "/".

type SecurityRequirementDefinition

type SecurityRequirementDefinition []SecuritySchemeScopes

SecurityRequirementDefinition is one way to satisfy an operation's security: every scheme it lists, each with the scopes it requires. An empty one lets the operation be called anonymously.

type SecuritySchemeScopes

type SecuritySchemeScopes struct {
	Scheme string
	Scopes []string
}

SecuritySchemeScopes names a security scheme and the scopes a security requirement needs of it.

type SimpleTypeSpec

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

SimpleTypeSpec defines the Go type for an OpenAPI type/format combination, along with any import required to use it.

type StructTagInfo

type StructTagInfo struct {
	// FieldName is the property name from the OpenAPI spec.
	FieldName string
	// IsOptional is true when the field is not listed as required.
	IsOptional bool
	// OmitEmpty is true when the field should carry ",omitempty".
	OmitEmpty bool
	// OmitZero is true when the field should carry ",omitzero".
	OmitZero bool
	// NeedsFormTag is true for fields bound from form-style parameters or
	// urlencoded request bodies.
	NeedsFormTag bool
}

StructTagInfo is the data made available to struct tag templates. The omit flags are fully computed before rendering: OmitEmpty folds in the required/readOnly/writeOnly logic and the x-omitempty extension; OmitZero folds in x-omitzero and prefer-skip-optional-pointer-with-omitzero. Templates therefore only need to decide whether to emit them, not re-derive them.

type StructTagTemplate

type StructTagTemplate struct {
	// Name is the tag name (e.g. "json", "yaml", "db").
	Name string `yaml:"name"`
	// Template is a Go text/template producing the tag value.
	// Available fields: .FieldName, .IsOptional, .OmitEmpty, .OmitZero,
	// .NeedsFormTag.
	Template string `yaml:"template"`
}

StructTagTemplate defines a single struct tag as a name plus a Go text/template rendered against StructTagInfo. A template that renders to the empty string suppresses the tag on that field.

type StructTagsConfig

type StructTagsConfig struct {
	// Tags lists the tags to generate. Entries are merged by name on top
	// of the defaults: a matching name replaces the default template, a
	// new name adds a tag. Output ordering is always alphabetical by name.
	Tags []StructTagTemplate `yaml:"tags,omitempty"`
}

StructTagsConfig configures struct tag generation for generated fields.

func (StructTagsConfig) Merge

Merge merges user config on top of this config by tag name: matching names override the default template, new names are appended.

type TypeDefinition

type TypeDefinition struct {
	// The name of the type, eg, type <...> Person
	TypeName string

	// The name of the corresponding JSON description, as it will sometimes
	// differ due to invalid characters.
	JsonName string

	// This is the Schema wrapper is used to populate the type description
	Schema Schema

	// ForceEnumPrefix, when true, forces the enum-value constants generated
	// from this TypeDefinition to be prefixed with the type name, regardless
	// of whether GenerateEnums detects a cross-enum conflict. Used for
	// synthesised enum types (e.g. server-URL variable enums) whose
	// generated identifiers must remain stable to avoid colliding with
	// other constants emitted alongside them.
	ForceEnumPrefix bool

	// Deprecated marks this type as deprecated, independent of the underlying
	// schema's own deprecated flag. Used when the type is generated for a
	// deprecated operation (e.g. request/response body aliases).
	Deprecated bool

	// DeprecationReason is the human-readable reason for deprecation, used
	// when Deprecated is true. If empty, a generic message is emitted.
	DeprecationReason string

	// Comment, when set, is the full doc comment (including the leading "//")
	// emitted above the type in the operation parameter template, replacing the
	// default "<name> defines parameters for <op>." line. Used to explain
	// non-obvious generated names, e.g. the per-path hash prefix on a shared
	// parameter disambiguated across paths (issue #2090).
	Comment string
}

TypeDefinition describes a Go type definition in generated code.

Let's use this example schema: components:

schemas:
  Person:
    type: object
    properties:
    name:
      type: string

func GenerateParamsTypes

func GenerateParamsTypes(op OperationDefinition) []TypeDefinition

GenerateParamsTypes defines the schema for a parameters definition object which encapsulates all the query, header and cookie parameters for an operation.

func GenerateTypeDefsForOperation

func GenerateTypeDefsForOperation(op OperationDefinition) []TypeDefinition

func GenerateTypesForParameters

func GenerateTypesForParameters(t *template.Template, params map[string]*model.ParameterRef) ([]TypeDefinition, error)

GenerateTypesForParameters generates type definitions for any custom types defined in the components/parameters section of the Swagger spec.

func GenerateTypesForRequestBodies

func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*model.RequestBodyRef) ([]TypeDefinition, error)

GenerateTypesForRequestBodies generates type definitions for any custom types defined in the components/requestBodies section of the Swagger spec.

func GenerateTypesForResponses

func GenerateTypesForResponses(t *template.Template, responses model.ResponseBodies) ([]TypeDefinition, error)

GenerateTypesForResponses generates type definitions for any custom types defined in the components/responses section of the Swagger spec.

func GenerateTypesForSchemas

func GenerateTypesForSchemas(t *template.Template, schemas map[string]*model.SchemaRef, excludeSchemas []string) ([]TypeDefinition, error)

GenerateTypesForSchemas generates type definitions for any custom types defined in the components/schemas section of the Swagger spec.

func (TypeDefinition) DeprecationComment

func (t TypeDefinition) DeprecationComment() string

DeprecationComment returns a Go-style deprecation comment if the type is deprecated, otherwise returns an empty string.

func (TypeDefinition) DocComment

func (t TypeDefinition) DocComment() string

DocComment returns the full Go doc comment for the type, including the deprecation notice as a separate paragraph when the type is deprecated.

func (*TypeDefinition) IsAlias

func (t *TypeDefinition) IsAlias() bool

type TypeMapping

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

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 UnionElement

type UnionElement string

UnionElement describe union element, based on prefix externalRef\d+ and real ref name from external schema.

func (UnionElement) Method

func (u UnionElement) Method() string

Method generate union method name for template functions `As/From/Merge`.

func (UnionElement) String

func (u UnionElement) String() string

String returns externalRef\d+ and real ref name from external schema, like externalRef0.SomeType.

type UnionRefComponent

type UnionRefComponent struct {
	// Type is the union's Go type.
	Type UnionElement
	// OwnedKeys are the JSON keys only this union's variants declare.
	OwnedKeys []string
	// OtherKeys are the JSON keys only the rest of the object declares, the
	// other unions' variants and the object's own properties, which As*
	// leaves out of this union.
	OtherKeys []string
}

UnionRefComponent is a union type that a union combining several includes through a $ref (see Schema.UnionRefComponents).

Jump to

Keyboard shortcuts

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