codegen
package
v2.9.0
Latest
Latest
This package is not in the latest version of its module.
Go to latest
Published: Nov 21, 2026
License:
Apache-2.0
Imports: 42
Imported by: 44 modules, 32 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.
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
- Variables
-
func DeprecationComment(reason string) string
-
func EscapePathElements(path string) string
-
func GenFieldsFromProperties(props []Property) []string
-
func GenPathString(uri, paramVarName string) string
-
func GenStructFromSchema(schema Schema) string
-
func Generate(spec *openapi3.T, opts Configuration) (string, error)
-
func GenerateAdditionalPropertyBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)
-
func GenerateBodyDefinitions(operationID string, bodyOrRef *openapi3.RequestBodyRef, pathItemRef string) ([]RequestBodyDefinition, []TypeDefinition, error)
-
func GenerateCallbackInitiator(t *template.Template, callbackOps []OperationDefinition) (string, error)
-
func GenerateChiReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateChiServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateClient(t *template.Template, ops []OperationDefinition) (string, error)
-
func GenerateClientWithResponses(t *template.Template, ops []OperationDefinition) (string, error)
-
func GenerateConstants(t *template.Template, swagger *openapi3.T) (string, error)
-
func GenerateEcho5Receiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateEcho5Server(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateEchoReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateEchoServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)
-
func GenerateFiberReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateFiberServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateFiberV3Receiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateFiberV3Server(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateGinReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateGinServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateGorillaReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateGorillaServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateImports(t *template.Template, externalImports []string, packageName string, ...) (string, error)
-
func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string, error)
-
func GenerateIrisReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateIrisServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateServerURLs(t *template.Template, spec *openapi3.T) (string, error)
-
func GenerateStdHTTPReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
-
func GenerateStdHTTPServer(t *template.Template, operations []OperationDefinition) (string, error)
-
func GenerateStrictResponses(t *template.Template, responses []ResponseDefinition) (string, error)
-
func GenerateStrictServer(t *template.Template, serverTemplates map[string]*template.Template, ...) (string, error)
-
func GenerateTemplates(templates []string, t *template.Template, ops any) (string, error)
-
func GenerateTemplatesIntoBuffer(buf *bytes.Buffer, templates []string, t *template.Template, ops any) error
-
func GenerateTypes(t *template.Template, types []TypeDefinition) (string, error)
-
func GenerateTypesForOperations(t *template.Template, ops []OperationDefinition) (string, error)
-
func GenerateUnionAndAdditionalProopertiesBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)
-
func GenerateUnionBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)
-
func GenerateWebhookInitiator(t *template.Template, webhookOps []OperationDefinition) (string, error)
-
func GetParametersImports(params map[string]*openapi3.ParameterRef) (map[string]goImport, error)
-
func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[string]goImport, error)
-
func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string]goImport, error)
-
func GetSchemaImports(schemas map[string]*openapi3.SchemaRef, excludeSchemas []string) (map[string]goImport, error)
-
func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (map[string]goImport, error)
-
func GetUserTemplateText(inputData string) (template string, err error)
-
func GoSchemaImports(schemas ...*openapi3.SchemaRef) (map[string]goImport, error)
-
func IsGoIdentity(str string) bool
-
func IsGoKeyword(str string) bool
-
func IsGoTypeReference(ref string) bool
-
func IsPredeclaredGoIdentifier(str string) bool
-
func IsValidGoIdentity(str string) bool
-
func IsWholeDocumentReference(ref string) bool
-
func LoadTemplates(src embed.FS, t *template.Template) error
-
func LowercaseFirstCharacter(str string) string
-
func LowercaseFirstCharacters(str string) string
-
func OperationImports(ops []OperationDefinition) (map[string]goImport, error)
-
func OperationSchemaImports(s *Schema) (map[string]goImport, error)
-
func OrderedParamsFromUri(uri string) []string
-
func ParseGoImportExtension(v *openapi3.SchemaRef) (*goImport, error)
-
func PathToTypeName(path []string) string
-
func PropertiesEqual(a, b Property) bool
-
func RefPathToGoType(refPath string) (string, error)
-
func RefPathToObjName(refPath string) string
-
func ResolveNames(schemas []*GatheredSchema) map[string]string
-
func SanitizeCode(goCode string) string
-
func SanitizeEnumNames(enumNames, enumValues []string) map[string]string
-
func SanitizeGoIdentifier(str string) string
-
func SanitizeGoIdentity(str string) string
-
func SchemaHasAdditionalProperties(schema *openapi3.Schema) bool
-
func SchemaNameToTypeName(name string) string
-
func SetGlobalStateSpec(spec *openapi3.T)
-
func SortedMapKeys[T any](m map[string]T) []string
-
func SortedSchemaKeys(dict map[string]*openapi3.SchemaRef) []string
-
func SortedSecuritySchemeKeys(dict map[string]*openapi3.SecuritySchemeRef) []string
-
func StringToGoComment(in string) string
-
func StringToGoString(in string) string
-
func StringWithTypeNameToGoComment(in, typeName string) string
-
func SwaggerUriToChiUri(uri string) string
-
func SwaggerUriToEchoUri(uri string) string
-
func SwaggerUriToFiberUri(uri string) string
-
func SwaggerUriToGinUri(uri string) string
-
func SwaggerUriToGorillaUri(uri string) string
-
func SwaggerUriToIrisUri(uri string) string
-
func SwaggerUriToStdHttpUri(uri string) string
-
func ToCamelCase(str string) string
-
func ToCamelCaseWithDigits(s string) string
-
func ToCamelCaseWithInitialism(str string) string
-
func ToCamelCaseWithInitialisms(s string) string
-
func TypeDefinitionsEquivalent(t1, t2 TypeDefinition) bool
-
func UppercaseFirstCharacter(str string) string
-
func UppercaseFirstCharacterWithPkgName(str string) string
-
func ValidateServerURLs(spec *openapi3.T) error
-
func ValidateSpec(spec *openapi3.T) error
-
func ValidateStdHTTPPath(path string) error
-
func ValidateStdHTTPPaths(spec *openapi3.T) error
-
type AdditionalImport
-
type ClientMethodVariant
-
type CompatibilityOptions
-
-
type Configuration
-
-
type Constants
-
type Discriminator
-
-
type DiscriminatorCase
-
type DiscriminatorStamp
-
type EchoRegisterTemplateData
-
type EnumDefinition
-
-
type EnumValueNamingOptions
-
type ExplicitNamesMode
-
type FieldDescriptor
-
type FormatMapping
-
-
type GatheredSchema
-
-
-
type GenerateOptions
-
-
type InitiatorTemplateData
-
-
type LeadingUnderscoreMode
-
type NameNormalizer
-
type NameNormalizerFunction
-
type NameNormalizerMap
-
-
type NamingOptions
-
-
type OperationDefinition
-
-
-
type OutputOptions
-
-
type OutputOptionsOverlay
-
type ParameterDefinition
-
-
-
type ParameterDefinitions
-
-
type Property
-
-
type PropertyNamingOptions
-
type ReceiverTemplateData
-
-
type RefWrapper
-
type RequestBodyDefinition
-
-
type RequestBodyEncoding
-
type ResolvedName
-
type ResponseContentDefinition
-
-
type ResponseDefinition
-
-
-
type ResponseHeaderDefinition
-
-
type ResponseTypeDefinition
-
type Schema
-
-
-
type SchemaContext
-
-
type SchemaDescriptor
-
type SchemaPath
-
-
type SecurityDefinition
-
-
type SecuritySchemeProvider
-
type ServerObjectDefinition
-
-
type ServerURLDefaultPointer
-
type SimpleTypeSpec
-
type StructTagInfo
-
type StructTagTemplate
-
type StructTagsConfig
-
-
type TypeDefinition
-
func BuildServerURLTypeDefinitions(spec *openapi3.T) ([]TypeDefinition, error)
-
func GenerateParamsTypes(op OperationDefinition) []TypeDefinition
-
func GenerateTypeDefsForOperation(op OperationDefinition) []TypeDefinition
-
func GenerateTypesForParameters(t *template.Template, params map[string]*openapi3.ParameterRef) ([]TypeDefinition, error)
-
func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*openapi3.RequestBodyRef) ([]TypeDefinition, error)
-
func GenerateTypesForResponses(t *template.Template, responses openapi3.ResponseBodies) ([]TypeDefinition, error)
-
func GenerateTypesForSchemas(t *template.Template, schemas map[string]*openapi3.SchemaRef, ...) ([]TypeDefinition, error)
-
func GenerateTypesForSecuritySchemes(t *template.Template, schemes map[string]*openapi3.SecuritySchemeRef) ([]TypeDefinition, error)
-
-
type TypeMapping
-
-
type UnionElement
-
-
type UnionRefComponent
Constants
View Source
const (
SchemaMergingV1 = "v1"
SchemaMergingV2 = "v2"
SchemaMergingV3 = "v3"
)
The values of CompatibilityOptions.SchemaMergingBehavior.
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: "openapi_types.Email"},
"date": {Type: "openapi_types.Date"},
"date-time": {Type: "time.Time", Import: "time"},
"duration": {Type: "openapi_types.Duration"},
"json": {Type: "json.RawMessage", Import: "encoding/json"},
"uuid": {Type: "openapi_types.UUID"},
"binary": {Type: "openapi_types.File"},
},
},
}
DefaultTypeMapping provides the default OpenAPI type/format to Go type mappings.
View Source
var NameNormalizers = NameNormalizerMap{
NameNormalizerFunctionUnset: ToCamelCase,
NameNormalizerFunctionToCamelCase: ToCamelCase,
NameNormalizerFunctionToCamelCaseWithDigits: ToCamelCaseWithDigits,
NameNormalizerFunctionToCamelCaseWithInitialisms: ToCamelCaseWithInitialisms,
}
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,
"genParamArgs": genParamArgs,
"genParamTypes": genParamTypes,
"genParamNames": genParamNames,
"genPathString": GenPathString,
"swaggerUriToIrisUri": SwaggerUriToIrisUri,
"swaggerUriToEchoUri": SwaggerUriToEchoUri,
"swaggerUriToFiberUri": SwaggerUriToFiberUri,
"swaggerUriToChiUri": SwaggerUriToChiUri,
"swaggerUriToGinUri": SwaggerUriToGinUri,
"swaggerUriToGorillaUri": SwaggerUriToGorillaUri,
"swaggerUriToStdHttpUri": SwaggerUriToStdHttpUri,
"lcFirst": LowercaseFirstCharacter,
"ucFirst": UppercaseFirstCharacter,
"ucFirstWithPkgName": UppercaseFirstCharacterWithPkgName,
"camelCase": ToCamelCase,
"genResponsePayload": genResponsePayload,
"genResponseTypeName": genResponseTypeName,
"genResponseUnmarshal": genResponseUnmarshal,
"getConditionOfResponseName": getConditionOfResponseName,
"responsesWithHeaders": responsesWithHeaders,
"getResponseTypeDefinitions": getResponseTypeDefinitions,
"toStringArray": toStringArray,
"lower": strings.ToLower,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"title": titleCaser.String,
"stripNewLines": stripNewLines,
"sanitizeGoIdentity": SanitizeGoIdentity,
"schemaNameToTypeName": SchemaNameToTypeName,
"toGoString": StringToGoString,
"toGoComment": StringWithTypeNameToGoComment,
"unionTypes": unionTypesFragment,
"withoutPkgName": withoutPkgName,
"additionalPropertiesType": additionalPropertiesType,
"genServerURLWithVariablesFunctionParams": genServerURLWithVariablesFunctionParams,
"httpMethodConstant": httpMethodConstant,
"isCustomHTTPMethod": isCustomHTTPMethod,
"customHTTPMethods": customHTTPMethods,
}
TemplateFunctions is passed to the template engine, and we can call each
function here by keyName from the template code.
Functions
func DeprecationComment(reason string) string
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(props []Property) []string
GenFieldsFromProperties produce corresponding field names with JSON annotations,
given a list of schema descriptors
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(schema Schema) string
func Generate(spec *openapi3.T, 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(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(operationID string, bodyOrRef *openapi3.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(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 GenerateChiReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateChiReceiver renders the chi receiver template. Chi shares
stdhttp's (w, r) handler signature, so it renders the same shared
receiver-stdlib.tmpl template.
func GenerateChiServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateChiServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateClient(t *template.Template, ops []OperationDefinition) (string, error)
GenerateClient uses the template engine to generate the function which registers our wrappers
as Echo path handlers.
func GenerateClientWithResponses(t *template.Template, ops []OperationDefinition) (string, error)
GenerateClientWithResponses generates a client which extends the basic client which does response
unmarshaling.
func GenerateConstants(t *template.Template, swagger *openapi3.T) (string, error)
GenerateConstants generates operation ids, context keys, paths, etc. to be exported as constants
Scopes constants are derived from components/securitySchemes rather than
from the operations' security requirements (which are filtered to defined
schemes anyway), so that a spec holding shared definitions with no paths
still exports the constants other packages alias via import-mapping.
func GenerateEcho5Receiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateEcho5Receiver renders the shared echo receiver template with
echo v5's `*echo.Context` (pointer) context type -- the only API
difference between echo v4 and v5 that affects the receiver.
func GenerateEcho5Server(t *template.Template, operations []OperationDefinition) (string, error)
GenerateEcho5Server generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateEchoReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateEchoReceiver renders the echo (v4) receiver template. Echo's
handler shape is `(ctx echo.Context) error`, and binding errors are
returned via echo.NewHTTPError so echo's framework error chain
reports them as 400 -- there's no errHandler argument like the
stdhttp receiver factory has.
func GenerateEchoServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateEchoServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)
func GenerateFiberReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateFiberReceiver renders the fiber (v2) receiver template.
Fiber's handler shape is `(c *fiber.Ctx) error`; binding errors are
returned via fiber.NewError so fiber's error chain reports them as
400. Per-handler middleware is not generated; use fiber.App.Use().
func GenerateFiberServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateFiberServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateFiberV3Receiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateFiberV3Receiver renders the shared fiber receiver template with
fiber v3's `fiber.Ctx` (interface, by value) context type -- the only
API difference between fiber v2 and v3 that affects the receiver.
func GenerateFiberV3Server(t *template.Template, operations []OperationDefinition) (string, error)
GenerateFiberV3Server generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateGinReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateGinReceiver renders the gin receiver template. Gin's handler
shape is `(c *gin.Context)` (no error return); binding errors abort
with c.JSON(400, gin.H{"error": ...}). Per-handler middleware is not
generated here -- gin's idiom prefers engine .Use() composition.
func GenerateGinServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateGinServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateGorillaReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateGorillaReceiver renders the gorilla/mux receiver template.
Gorilla shares stdhttp's (w, r) handler signature, so it renders the
same shared receiver-stdlib.tmpl template.
func GenerateGorillaServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateGorillaServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateImports(t *template.Template, externalImports []string, packageName string, versionOverride *string) (string, error)
GenerateImports generates our import statements and package definition.
func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string, error)
GenerateInlinedSpec generates a gzipped, base64 encoded JSON representation of the
swagger definition, which we embed inside the generated code.
func GenerateIrisReceiver(t *template.Template, prefix string, ops []OperationDefinition) (string, error)
GenerateIrisReceiver renders the iris receiver template. Iris's
handler shape is `(ctx iris.Context)` (no error return); binding
errors set ctx.StatusCode(400) plus ctx.WriteString and return.
Per-handler middleware is not generated; use app.Use() at the
engine or Party level.
func GenerateIrisServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateIrisServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateServerURLs(t *template.Template, spec *openapi3.T) (string, error)
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 GenerateStdHTTPServer(t *template.Template, operations []OperationDefinition) (string, error)
GenerateStdHTTPServer generates all the go code for the ServerInterface as well as
all the wrapper functions around our handlers.
func GenerateStrictResponses(t *template.Template, responses []ResponseDefinition) (string, error)
func GenerateStrictServer(t *template.Template, serverTemplates map[string]*template.Template, operations []OperationDefinition, opts Configuration) (string, error)
func GenerateTemplates(templates []string, t *template.Template, ops any) (string, error)
GenerateTemplates used to generate templates
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(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(t *template.Template, ops []OperationDefinition) (string, error)
GenerateTypesForOperations generates code for all types produced within operations
func GenerateUnionAndAdditionalProopertiesBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)
func GenerateUnionBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string, error)
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(params map[string]*openapi3.ParameterRef) (map[string]goImport, error)
func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[string]goImport, error)
func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string]goImport, error)
func GetSchemaImports(schemas map[string]*openapi3.SchemaRef, excludeSchemas []string) (map[string]goImport, error)
func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (map[string]goImport, error)
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(schemas ...*openapi3.SchemaRef) (map[string]goImport, error)
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(str string) bool
IsGoKeyword returns whether the given string is a go keyword
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(str string) bool
IsPredeclaredGoIdentifier returns whether the given string
is a predefined go identifier.
See https://golang.org/ref/spec#Predeclared_identifiers
func IsValidGoIdentity(str string) bool
IsValidGoIdentity checks if the given string can be used as a
name of variable, constant, or type.
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(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(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(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(ops []OperationDefinition) (map[string]goImport, error)
func OperationSchemaImports(s *Schema) (map[string]goImport, error)
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(v *openapi3.SchemaRef) (*goImport, error)
func PathToTypeName(path []string) string
PathToTypeName converts a path, like Object/field1/nestedField into a go
type name.
func PropertiesEqual(a, b Property) bool
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(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(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(goCode string) string
SanitizeCode runs sanitizers across the generated Go code to ensure the
generated code will be able to compile.
func SanitizeEnumNames(enumNames, enumValues []string) map[string]string
SanitizeEnumNames fixes illegal chars in the enum names
and removes duplicates
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(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(schema *openapi3.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(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(spec *openapi3.T)
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(dict map[string]*openapi3.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 SortedSecuritySchemeKeys(dict map[string]*openapi3.SecuritySchemeRef) []string
SortedSecuritySchemeKeys returns sorted keys for a SecuritySchemeRef dict
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(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(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 SwaggerUriToChiUri(uri string) string
SwaggerUriToChiUri converts a swagger style path URI with parameters to a
Chi compatible path URI. We need to replace all Swagger parameters with
"{param}". Valid input parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
func SwaggerUriToEchoUri(uri string) string
SwaggerUriToEchoUri converts a OpenAPI style path URI with parameters to an
Echo compatible path URI. We need to replace all of OpenAPI parameters with
":param". Valid input parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
func SwaggerUriToFiberUri(uri string) string
SwaggerUriToFiberUri converts a OpenAPI style path URI with parameters to a
Fiber compatible path URI. We need to replace all of OpenAPI parameters with
":param". Valid input parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
func SwaggerUriToGinUri(uri string) string
SwaggerUriToGinUri converts a swagger style path URI with parameters to a
Gin compatible path URI. We need to replace all Swagger parameters with
":param". Valid input parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
func SwaggerUriToGorillaUri(uri string) string
SwaggerUriToGorillaUri converts a swagger style path URI with parameters to a
Gorilla compatible path URI. We need to replace all Swagger parameters with
":param". Valid input parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
func SwaggerUriToIrisUri(uri string) string
SwaggerUriToIrisUri converts a OpenAPI style path URI with parameters to an
Iris compatible path URI. We need to replace all of OpenAPI parameters with
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
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. Valid input
parameters are:
{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}
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(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(str string) string
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(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.
The schemas are compared like reflect.DeepEqual, except that kin-openapi's
source locations (*openapi3.Origin) are ignored, so the same schema declared
on two different lines is still the same type. Comparing the JSON encodings
instead would not work: a $ref encodes as its string alone, so two schemas
whose $refs resolve to different targets would look equal.
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(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 ValidateServerURLs(spec *openapi3.T) error
ValidateServerURLs checks the parts of the document's servers that the
`server-urls` generator copies into Go source as identifiers: the x-go-name
extension, the names of the variables the URL uses (function parameters and
type names), the `{placeholder}` names a URL uses without declaring (also
parameters), and the enum values of the used variables, which are appended
to the variable's type name to form constant names. None of them is
sanitized on the way, so names have to be Go identifiers as written and enum
values have to be made of identifier characters. A declared variable whose
placeholder does not appear in the URL produces no code and is not checked.
The function is separate from ValidateSpec because it only applies when
server URLs are generated: specs with, say, a hyphenated variable name are
fine otherwise.
func ValidateSpec(spec *openapi3.T) 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. A `$ref` with a fragment is not followed: it resolves to a
component that is validated at its own definition, or to a type in another
package whose contents are never copied into the generated output. A
whole-document `$ref` (one without a fragment, such as `./other.yaml`) is
followed, because code generation inlines what it points at (see descend).
The members of an allOf are validated as the default schema-merging
behavior combines them (see allOfMergesUnions). Generate validates with the
behavior its options select instead, through validateSpec.
func ValidateStdHTTPPath(path string) error
ValidateStdHTTPPath reports whether an OpenAPI path can be registered with
net/http ServeMux. ServeMux wildcards must occupy an entire path segment, so
mixed segments such as "{resourceId}:apply" are rejected at codegen time
instead of panicking at server startup (see #2488).
func ValidateStdHTTPPaths(spec *openapi3.T) 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.
Types
type AdditionalImport struct {
Alias string `yaml:"alias,omitempty"`
Package string `yaml:"package"`
}
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 CompatibilityOptions struct {
// In the past, we merged schemas for `allOf` by inlining each schema
// within the schema list. This approach, though, is incorrect because
// `allOf` merges at the schema definition level, not at the resulting model
// level. So, new behavior merges OpenAPI specs but generates different code
// than we have in the past. Set OldMergeSchemas to true for the old behavior.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/531
//
// Deprecated: set SchemaMergingBehavior to "v1" instead, which this is an
// alias for.
OldMergeSchemas bool `yaml:"old-merge-schemas,omitempty"`
// SchemaMergingBehavior selects how schemas composed with allOf are merged
// into Go types, and how anyOf and oneOf are turned into Go unions. Each
// value is a version of that behavior:
//
// - "v1": allOf members that are $refs are embedded in the Go struct, and
// the fields of inline members are inlined. This was the only behavior
// before v1.11.0; OldMergeSchemas: true is an alias for it. For anyOf and
// oneOf it does what v2 does.
// - "v2": allOf members are merged keyword by keyword into one Go type,
// and anyOf and oneOf become a union type with As*, From* and Merge*
// methods. The default since v1.11.0.
// - "v3": allOf members are merged by what allOf means, a value that
// matches every member, and members no value can match are an error.
// Unions model more of the spec: an allOf of several unions keeps each,
// a oneOf or anyOf that only adds constraints makes no union, and the
// As* of a variant with additionalProperties: false rejects keys no
// part of the object declares. Added in v2.9.0 as an option; it becomes
// the default after at least one release as an option.
//
// Leaving it unset means "v2". The versions are compared in
// https://github.com/oapi-codegen/oapi-codegen/blob/main/docs/schema-merging.md
SchemaMergingBehavior string `yaml:"schema-merging-behavior,omitempty"`
// In the past, when a schema combined `allOf` with sibling fields at the
// same level (`properties`, `required`, `additionalProperties`,
// `description`), those siblings were silently discarded and the schema
// was emitted as a Go type alias to its sole `allOf` target. New behavior
// merges the parent's siblings with the `allOf` members so the generated
// type carries every field declared in the spec. This is a more accurate
// translation of OpenAPI semantics, but it changes the shape of generated
// types: a schema that previously produced `type X = Y` may now produce
// a distinct struct embedding Y with extra fields, which is not
// interchangeable with Y in downstream Go code. Set OldAllOfSiblingMerging
// to true to restore the prior behavior.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/697
OldAllOfSiblingMerging bool `yaml:"old-allof-sibling-merging,omitempty"`
// Enum values can generate conflicting typenames, so we've updated the
// code for enum generation to avoid these conflicts, but it will result
// in some enum types being renamed in existing code. Set OldEnumConflicts to true
// to revert to old behavior. Please see:
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/549
OldEnumConflicts bool `yaml:"old-enum-conflicts,omitempty"`
// It was a mistake to generate a go type definition for every $ref in
// the OpenAPI schema. New behavior uses type aliases where possible, but
// this can generate code which breaks existing builds. Set OldAliasing to true
// for old behavior.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/549
OldAliasing bool `yaml:"old-aliasing,omitempty"`
// When an object contains no members, and only an additionalProperties specification,
// it is flattened to a map
DisableFlattenAdditionalProperties bool `yaml:"disable-flatten-additional-properties,omitempty"`
// When an object property is both required and readOnly the go model is generated
// as a pointer. Set DisableRequiredReadOnlyAsPointer to true to mark them as non pointer.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/604
DisableRequiredReadOnlyAsPointer bool `yaml:"disable-required-readonly-as-pointer,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"`
// DisableEnumValueConflictResolution turns off cross-enum value conflict
// resolution. By default, when two enums declare the same value, the
// generated constants are prefixed with their type name so they don't
// collide. Set this to true to disable that resolution and restore the
// prior behavior, in which conflict detection compared already-prefixed
// constant names and could miss overlaps depending on declaration order.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/2391
DisableEnumValueConflictResolution bool `yaml:"disable-enum-value-conflict-resolution,omitempty"`
// Our generated code for Chi has historically inverted the order in which Chi middleware is
// applied such that the last invoked middleware ends up executing first in the Chi chain
// This resolves the behavior such that middlewares are chained in the order they are invoked.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/786
ApplyChiMiddlewareFirstToLast bool `yaml:"apply-chi-middleware-first-to-last,omitempty"`
// Our generated code for gorilla/mux has historically inverted the order in which gorilla/mux middleware is
// applied such that the last invoked middleware ends up executing first in the middlewares chain
// This resolves the behavior such that middlewares are chained in the order they are invoked.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/841
ApplyGorillaMiddlewareFirstToLast bool `yaml:"apply-gorilla-middleware-first-to-last,omitempty"`
// CircularReferenceLimit allows controlling the limit for circular reference checking.
// In some OpenAPI specifications, we have a higher number of circular
// references than is allowed out-of-the-box, but can be tuned to allow
// traversing them.
// Deprecated: In kin-openapi v0.126.0 (https://github.com/getkin/kin-openapi/tree/v0.126.0?tab=readme-ov-file#v01260) the Circular Reference Counter functionality was removed, instead resolving all references with backtracking, to avoid needing to provide a limit to reference counts.
CircularReferenceLimit int `yaml:"circular-reference-limit"`
// 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"`
// PreserveOriginalOperationIdCasingInEmbeddedSpec ensures that the `operationId` from the source spec is kept intact in case when embedding it into the Embedded Spec output.
// When `oapi-codegen` parses the original OpenAPI specification, it will apply the configured `output-options.name-normalizer` to each operation's `operationId` before that is used to generate code from.
// However, this is also applied to the copy of the `operationId`s in the `embedded-spec` generation, which means that the embedded OpenAPI specification is then out-of-sync with the input specificiation.
// To ensure that the `operationId` in the embedded spec is preserved as-is from the input specification, set this.
// NOTE that this will not impact generated code.
// NOTE that if you're using `include-operation-ids` or `exclude-operation-ids` you may want to ensure that the `operationId`s used are correct.
PreserveOriginalOperationIdCasingInEmbeddedSpec bool `yaml:"preserve-original-operation-id-casing-in-embedded-spec"`
// HeadersImplicitlyRequired treats all response headers as required, ignoring
// the `required` property from the header definition. Prior to v2.6.0,
// oapi-codegen generated all response headers as direct values (implicitly
// required). The OpenAPI specification defaults headers to optional
// (required: false), so the corrected behavior generates optional headers as
// pointers. Set this to true to restore the old behavior where all headers
// are treated as required.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/2267
HeadersImplicitlyRequired bool `yaml:"headers-implicitly-required,omitempty"`
// EnableAuthScopesOnContext re-enables the legacy emission of security
// scheme scopes by generated server code: the per-scheme context key
// types (e.g. `bearerAuthContextKey`), the scope constants (e.g.
// `BearerAuthScopes`), and the per-operation calls that store the
// operation's scopes into the request context.
//
// A security scheme that is a $ref into a spec covered by import-mapping
// does not declare its own context key type; its scopes constant is an
// alias of the one in the mapped package, so `context.Value` lookups use
// the same key across the generated packages. This requires the mapped
// spec's config to also set this flag, so that the referenced constant
// exists. Please see
// https://github.com/oapi-codegen/oapi-codegen/issues/2383
//
// Deprecated: this mechanism is off by default because it flattens the
// OpenAPI `security` requirements into a per-scheme list of scopes, and
// cannot represent alternative schemes (OR), combined schemes (AND), or
// anonymous (`{}`) alternatives. Authentication and authorization should
// instead be performed at runtime using the request validation
// middleware, which evaluates the spec's security requirements directly.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/1524
EnableAuthScopesOnContext bool `yaml:"enable-auth-scopes-on-context,omitempty"`
// SortHandlerRegistrations restores the historical behavior of registering
// generated route handlers in sorted (lexicographic, by path then method)
// order. By default handlers are registered in the order their paths are
// declared in the spec, so that on routers which match in registration
// order (e.g. Fiber, Gorilla/mux) overlapping paths can be disambiguated by
// ordering them in the spec. Set this to true to opt out and go back to the
// old sorted registration order.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/1887
SortHandlerRegistrations bool `yaml:"sort-handler-registrations,omitempty"`
// OverlaysUseYamlJsonpath reads the targets of `output-options.overlay`
// actions in the JSONPath dialect used by oapi-codegen before v2.9.0
// (yaml-jsonpath), by translating them to RFC 9535. The setting applies
// to the whole overlay: by default every target is read as RFC 9535
// JSONPath, including targets that are valid in both dialects but mean
// something else in each, such as `$.paths.*.*[?(!@.servers)]`; there
// is no per-target detection. The translation covers the differences
// found in practice, but is not an exact emulation; its known
// limitations are documented in the internal/overlay/legacyjsonpath
// package.
// Please see https://github.com/oapi-codegen/oapi-codegen/issues/2502
OverlaysUseYamlJsonpath bool `yaml:"overlays-use-yaml-jsonpath,omitempty"`
}
CompatibilityOptions specifies backward compatibility settings for the
code generator.
func (CompatibilityOptions) Validate
added in
v2.4.0
func (co CompatibilityOptions) Validate() map[string]string
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"`
// CompatibilityOptions specifies backward compatibility settings for the code generator
Compatibility CompatibilityOptions `yaml:"compatibility,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"`
// AllowRemoteRefsFrom lists the remote documents that external $refs in
// the input specification may be fetched from while it is loaded. Each
// entry is the URL of a referenced document exactly as it appears in the
// $ref, without the fragment, or "*" to allow every URL. When empty, which
// is the default, remote references are refused and only references to
// local files are followed.
AllowRemoteRefsFrom []string `yaml:"allow-remote-refs-from,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 (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
added in
v2.8.0
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 struct {
// SecuritySchemeProviders holds all security schemes for which scopes
// context-key constants are generated.
SecuritySchemeProviders []SecuritySchemeProvider
// 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 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
added in
v2.9.0
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
added in
v2.9.0
func (d *Discriminator) SwitchType() string
SwitchType returns the Go type ValueByDiscriminator decodes the
discriminator into and switches on: int64 or float64 for a v3 integer or
number discriminator, and "" when it compares the value's JSON text.
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 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 EchoRegisterTemplateData struct {
RouteReturnType string
Operations []OperationDefinition
}
EchoRegisterTemplateData is the input to the shared echo route-
registration template. RouteReturnType selects between echo v4's
"*echo.Route" and echo v5's "echo.RouteInfo" in the EchoRouter
interface method signatures -- the only difference between the two
echo versions' registration code.
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
// `compatibility.always-prefix-enum-values` option.
PrefixTypeName bool
}
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 EnumValueNamingOptions struct {
// KeepUnderscores stops the name normalizer from treating an underscore as
// a word separator that it removes. The words on either side are
// normalized as usual and the underscore between them is kept, so the enum
// value `SOME_ENUM_NAME` becomes the constant `SOME_ENUM_NAME` rather than
// `SOMEENUMNAME`.
KeepUnderscores bool `yaml:"keep-underscores,omitempty"`
}
EnumValueNamingOptions adjusts the names of enum constants.
type ExplicitNamesMode string
ExplicitNamesMode is a value of `output-options.naming.explicit-names`.
const (
// ExplicitNamesNormalize is the default: a name the spec states itself
// goes through the name normalizer.
ExplicitNamesNormalize ExplicitNamesMode = ""
// ExplicitNamesVerbatim emits a name the spec states itself exactly as
// written.
ExplicitNamesVerbatim ExplicitNamesMode = "verbatim"
)
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 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
added in
v2.6.0
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 struct {
Path SchemaPath
Context SchemaContext
Ref string // $ref string if this is a reference
Schema *openapi3.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(spec *openapi3.T, 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
added in
v2.7.0
func (gs *GatheredSchema) FormatPath() string
FormatPath returns a human-readable representation of the path for debugging.
func (*GatheredSchema) IsComponentSchema
added in
v2.7.0
func (gs *GatheredSchema) IsComponentSchema() bool
IsComponentSchema returns true if this schema came from components/schemas.
type GenerateOptions struct {
// IrisServer specifies whether to generate iris server boilerplate
IrisServer bool `yaml:"iris-server,omitempty"`
// ChiServer specifies whether to generate chi server boilerplate
ChiServer bool `yaml:"chi-server,omitempty"`
// FiberServer specifies whether to generate fiber server boilerplate
FiberServer bool `yaml:"fiber-server,omitempty"`
// FiberV3Server specifies whether to generate fiber v3 server boilerplate
FiberV3Server bool `yaml:"fiber-v3-server,omitempty"`
// EchoServer specifies whether to generate echo server boilerplate
EchoServer bool `yaml:"echo-server,omitempty"`
// Echo5Server specifies whether to generate echo v5 server boilerplate
Echo5Server bool `yaml:"echo5-server,omitempty"`
// GinServer specifies whether to generate gin server boilerplate
GinServer bool `yaml:"gin-server,omitempty"`
// GorillaServer specifies whether to generate Gorilla server boilerplate
GorillaServer bool `yaml:"gorilla-server,omitempty"`
// StdHTTPServer specifies whether to generate stdlib http server boilerplate
StdHTTPServer bool `yaml:"std-http-server,omitempty"`
// Strict specifies whether to generate strict server wrapper
Strict bool `yaml:"strict-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"`
// EmbeddedSpec indicates whether to embed the swagger spec in the generated code
EmbeddedSpec bool `yaml:"embedded-spec,omitempty"`
// ServerURLs generates types for the `Server` definitions' URLs, instead of needing to provide your own values
ServerURLs bool `yaml:"server-urls,omitempty"`
}
GenerateOptions specifies which supported output formats to generate.
func (g GenerateOptions) AnyOperationGenerator() bool
AnyOperationGenerator returns true if any code generator that emits
per-operation Go code (clients, server frameworks, strict-server) is
enabled. Used to detect configurations where operation-derived type
references would be emitted without a corresponding declaration.
func (GenerateOptions) RouterImports
added in
v2.7.0
func (g GenerateOptions) RouterImports() []AdditionalImport
RouterImports returns the framework-specific and strict middleware imports
needed based on which server type is selected.
func (GenerateOptions) Validate
added in
v2.4.0
func (oo GenerateOptions) Validate() map[string]string
func (GenerateOptions) Warnings
added in
v2.5.0
func (oo GenerateOptions) Warnings() map[string]string
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(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 LeadingUnderscoreMode string
LeadingUnderscoreMode is a value of
`output-options.naming.properties.leading-underscore`.
const (
// LeadingUnderscoreSpell is the default: a leading underscore becomes the
// word `Underscore`.
LeadingUnderscoreSpell LeadingUnderscoreMode = ""
// LeadingUnderscoreDrop makes leading underscores contribute nothing to
// the name.
LeadingUnderscoreDrop LeadingUnderscoreMode = "drop"
)
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 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 map[NameNormalizerFunction]NameNormalizer
func (NameNormalizerMap) Options
func (m NameNormalizerMap) Options() []string
type NamingOptions struct {
// EnumValues adjusts the names of the constants generated for enum values.
EnumValues EnumValueNamingOptions `yaml:"enum-values,omitempty"`
// Properties adjusts the names of the struct fields generated for object
// properties and for the query, header and cookie parameters of an
// operation.
Properties PropertyNamingOptions `yaml:"properties,omitempty"`
// ExplicitNames decides what happens to a Go name the spec states itself,
// with `x-go-name` on a property or a parameter, or with `x-enum-varnames`
// / `x-enumNames`. By default such a name goes through the name normalizer
// like any other. Set to `verbatim` to emit it exactly as written.
ExplicitNames ExplicitNamesMode `yaml:"explicit-names,omitempty"`
}
NamingOptions holds opt-in adjustments to how Go names are derived from the
names in a spec. Each one switches a single, narrowly scoped behavior of the
configured `name-normalizer`; with none of them set, names are derived
exactly as they always were.
func (NamingOptions) Validate
added in
v2.9.0
func (n NamingOptions) Validate() map[string]string
Validate reports the naming options that have a value they do not accept,
keyed by option.
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
// SpecOperationId is the raw `operationId` value as it appears in the OpenAPI spec, before normalization to a Go identifier. Empty when the spec didn't supply one (in which case the codegen-generated ID is the only available identifier and is exposed via OperationId).
SpecOperationId 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
SecurityDefinitions []SecurityDefinition // These are the security providers
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 *openapi3.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
// 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(swagger *openapi3.T) ([]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(swagger *openapi3.T) ([]OperationDefinition, error)
func WebhookOperationDefinitions(swagger *openapi3.T) ([]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.
kin-openapi only populates the Webhooks field 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
added in
v2.9.0
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
added in
v2.8.0
func (o *OperationDefinition) DeprecationComment() string
DeprecationComment returns a Go-style deprecation comment if the operation is deprecated, otherwise returns an empty string.
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
added in
v2.9.0
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 (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
added in
v2.7.0
func (o *OperationDefinition) HandlerName() string
HandlerName returns the OperationId to use when referencing the server-side
wrapper function. For alias operations this is the canonical operation's ID,
since the alias doesn't generate its own wrapper.
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 (o *OperationDefinition) HasMaskedRequestContentTypes() bool
func (*OperationDefinition) MiddlewareKey
added in
v2.7.0
func (o *OperationDefinition) MiddlewareKey() string
MiddlewareKey returns the identifier to use as the key in per-operation
middleware maps. The raw spec OperationId is preferred so map keys mirror
the OpenAPI spec verbatim; falls back to the normalized OperationId when
the spec didn't supply one.
func (*OperationDefinition) Params
func (o *OperationDefinition) Params() []ParameterDefinition
Params returns the list of all parameters except Path parameters. Path parameters
are handled differently from the rest, since they're mandatory.
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) SourceName
added in
v2.8.0
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 (o *OperationDefinition) SummaryAsComment(prefix string) string
SummaryAsComment returns the Operations summary as a Godoc-style multi line comment
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"`
// 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, with schema-merging-behavior v3,
// 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. The older values ignore this
// option: their As* always ignore such properties.
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"`
// Naming holds opt-in adjustments to how the name normalizer derives the
// names of enum constants and struct fields, and whether it applies to
// names the spec states itself.
Naming NamingOptions `yaml:"naming,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"`
// EnableYamlTags adds YAML tags to generated structs, in addition to default JSON ones.
// Superseded by StructTags: when a `yaml` entry is present in `struct-tags`, this flag
// has no effect.
EnableYamlTags bool `yaml:"yaml-tags,omitempty"`
// 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.
//
// It covers struct field names as well. Properties of one object whose
// JSON names derive the same Go field name ("host-fqdn" and "host_fqdn"
// are both "HostFqdn") are each renamed to that name and a short hash of
// the JSON name, as in "HostFqdn_cea8c90". Every colliding property is
// renamed, so that a field's name depends only on its own property and
// stays put as the spec changes around it. A field named with x-go-name
// is never renamed. Without this, such a collision is an error.
//
// The option is still named for type names, which is all it covered at
// first, so that existing configurations keep working.
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
added in
v2.4.0
func (oo OutputOptions) Validate() map[string]string
type OutputOptionsOverlay struct {
// Path is the path to the Overlay file. Action targets are RFC 9535
// JSONPath expressions; set CompatibilityOptions.OverlaysUseYamlJsonpath
// to read all of them in the dialect of earlier versions instead.
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 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 *openapi3.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
}
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(params openapi3.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(params []ParameterDefinition, in string) []ParameterDefinition
FilterParameterDefinitionByType returns the subset of the specified parameters which are of the
specified type.
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) Explode
func (pd *ParameterDefinition) Explode() bool
func (ParameterDefinition) GoName
func (pd ParameterDefinition) GoName() string
GoName is the Go name of the parameter, and the only place that name is
made: everything that declares or refers to the parameter takes it from
here.
A query, header or cookie parameter is a field of the operation's
parameters struct, so it is named as a struct field. A path parameter is a
function argument, and a field only of the strict server's request object;
it does not take part in the naming of struct fields, which could otherwise
turn it into an argument the generated functions already have, such as ctx.
func (pd ParameterDefinition) GoVariableName() string
func (ParameterDefinition) HasOptionalPointer
added in
v2.5.0
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
strict 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 (the legacy yaml-tags flag does
not apply to these fields).
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) RequiresNilCheck
added in
v2.6.0
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
added in
v2.7.0
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) SchemaFormat
added in
v2.6.0
func (pd *ParameterDefinition) SchemaFormat() string
SchemaFormat returns the OpenAPI format string for this parameter's schema (e.g. "byte", "date-time"),
or empty string if unavailable.
func (*ParameterDefinition) SchemaType
added in
v2.6.0
func (pd *ParameterDefinition) SchemaType() string
SchemaType returns the single OpenAPI type of this parameter's schema
(e.g. "string", "integer") with the OpenAPI 3.1 "null" nullability marker
stripped, or empty string when the schema declares no type or a
multi-type union (unions are carried by SchemaTypes instead).
func (*ParameterDefinition) SchemaTypes
added in
v2.9.0
func (pd *ParameterDefinition) SchemaTypes() []string
SchemaTypes returns the members of this parameter's OpenAPI 3.1
multi-type union (e.g. ["string", "integer"]) with the "null" nullability
marker stripped, or nil when the schema declares at most one non-null
type. Non-nil only for genuine unions, where the generated bind call
passes the list to the runtime (Types option, runtime v1.7.0+) so the
value can bind into the parameter's `any` destination.
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
added in
v2.6.0
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 []ParameterDefinition
func (ParameterDefinitions) FindByName
func (p ParameterDefinitions) FindByName(name string) *ParameterDefinition
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 (p Property) GoFieldName() string
GoFieldName returns the name of the struct field generated for p.
func (p Property) GoTypeDef() string
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
added in
v2.8.0
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 (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
added in
v2.5.1
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 PropertyNamingOptions struct {
// LeadingUnderscore decides what the underscores such a name starts with
// contribute to its field name. By default each one is spelled out,
// so `_id` becomes `UnderscoreId`. Set to `drop` for them to contribute
// nothing, so `_id` becomes `Id`.
LeadingUnderscore LeadingUnderscoreMode `yaml:"leading-underscore,omitempty"`
}
PropertyNamingOptions adjusts the names of struct fields: those of an
object's properties, and those of an operation's query, header and cookie
parameters, which are the fields of its parameters struct.
type ReceiverTemplateData struct {
Prefix string // "Webhook" or "Callback"
PrefixLower string // lowercase form of Prefix, for prose
// CtxType is the framework context type as it appears in the handler
// signature: "echo.Context" vs "*echo.Context" for echo v4/v5, and
// "*fiber.Ctx" vs "fiber.Ctx" for fiber v2/v3. Only the echo and fiber
// receiver templates read it; the other frameworks' templates embed
// their fixed context type directly and leave this empty.
CtxType string
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(prefix string, ops []OperationDefinition) ReceiverTemplateData
NewReceiverTemplateData builds the template input for the given
prefix ("Webhook" or "Callback") and operation list.
type RefWrapper struct {
Ref string
HasValue bool
SourceRef any
}
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
// ExplodedFormArrays lists, sorted, the properties of a form-urlencoded
// body which the client serializes with repeated keys (name=a&name=b)
// rather than indexed ones (name[0]=a&name[1]=b). See
// explodedFormArrays.
ExplodedFormArrays []string
// 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 (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
added in
v2.9.0
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 (r RequestBodyDefinition) IsFixedContentType() bool
IsFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (RequestBodyDefinition) IsFormdata
added in
v2.9.0
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
added in
v2.9.0
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 (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
added in
v2.9.0
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 struct {
ContentType string
Style string
Explode *bool
}
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 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 strict 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
added in
v2.9.0
func (r ResponseContentDefinition) CanUseDirectResponseType() bool
CanUseDirectResponseType reports whether the strict response can use its
wire type directly instead of exposing a Body field.
func (r ResponseContentDefinition) HasFixedContentType() bool
HasFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (ResponseContentDefinition) IsFormdata
added in
v2.9.0
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
added in
v2.9.0
func (r ResponseContentDefinition) IsMultipart() bool
IsMultipart returns whether this content is a multipart media type
func (ResponseContentDefinition) IsStreamingContentType
added in
v2.7.0
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
added in
v2.9.0
func (r ResponseContentDefinition) IsText() bool
IsText returns whether this content is plain text
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 struct {
StatusCode string
Description string
Contents []ResponseContentDefinition
Headers []ResponseHeaderDefinition
Ref string
}
func GenerateResponseDefinitions(operationID string, responses map[string]*openapi3.ResponseRef, pathItemRef string) ([]ResponseDefinition, error)
func (ResponseDefinition) GoName
func (r ResponseDefinition) GoName() string
func (r ResponseDefinition) HasFixedStatusCode() bool
func (r ResponseDefinition) IsExternalRef() bool
func (ResponseDefinition) IsRef
func (r ResponseDefinition) IsRef() bool
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) DeprecationComment
added in
v2.8.0
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
added in
v2.7.0
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
added in
v2.7.0
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
added in
v2.7.0
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().
func (ResponseHeaderDefinition) SchemaFormat
added in
v2.8.0
func (h ResponseHeaderDefinition) SchemaFormat() string
SchemaFormat returns the OpenAPI format string for this header's schema
(e.g. "date-time", "duration"), or empty string if unavailable.
func (ResponseHeaderDefinition) SchemaType
added in
v2.8.0
func (h ResponseHeaderDefinition) SchemaType() string
SchemaType returns the single OpenAPI type of this header's schema
(e.g. "string", "integer") with the OpenAPI 3.1 "null" nullability marker
stripped, or empty string when the schema declares no type or a
multi-type union (unions are carried by SchemaTypes instead).
func (ResponseHeaderDefinition) SchemaTypes
added in
v2.9.0
func (h ResponseHeaderDefinition) SchemaTypes() []string
SchemaTypes returns the members of this header's OpenAPI 3.1 multi-type
union with the "null" nullability marker stripped, or nil when the schema
declares at most one non-null type. See ParameterDefinition.SchemaTypes.
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 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 (schema-merging-behavior v3, 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 (schema-merging-behavior v3, 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 *openapi3.Schema
// contains filtered or unexported fields
}
Schema describes an OpenAPI schema, with lots of helper fields to use in the
templating engine.
func GenerateGoSchema(sref *openapi3.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 (s *Schema) AddProperty(p Property) error
AddProperty adds a new property to the current Schema, and returns an error
if it collides. Two identical fields will not collide, but two properties by
the same name, but different definition, will collide. It's safe to merge the
fields of two schemas with overlapping properties if those properties are
identical.
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 (s Schema) ClosedUnionVariant(e UnionElement) bool
ClosedUnionVariant reports whether a variant's As* allows only some keys
(see UnionAllowedKeys).
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 (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 (s Schema) GetAdditionalTypeDefs() []TypeDefinition
func (s Schema) HasCustomMarshalJSON() bool
HasCustomMarshalJSON reports whether a named type declared over this schema
position (the strict-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 (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 (s Schema) InUnionComponent(e UnionElement) bool
InUnionComponent reports whether a variant belongs to one of several unions
the schema combines (see UnionOwnedKeys).
func (s Schema) IsExternalRef() bool
func (Schema) IsPrimitive
added in
v2.7.0
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 (s Schema) TypeDecl() string
func (s Schema) UnionAllowedKeysFor(e UnionElement) []string
UnionAllowedKeysFor returns the JSON keys a variant's As* allows (see
UnionAllowedKeys).
func (s Schema) UnionOwnedKeysFor(e UnionElement) []string
UnionOwnedKeysFor returns the JSON keys a variant's own union owns (see
UnionOwnedKeys).
func (s Schema) UnionTextAccepts(kind string) bool
UnionTextAccepts reports whether a scalar union has a branch of the given
JSON type; see UnionTextKinds.
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 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
added in
v2.7.0
func (sc SchemaContext) String() string
String returns a human-readable name for the context.
func (SchemaContext) Suffix
added in
v2.7.0
func (sc SchemaContext) Suffix() string
Suffix returns the suffix to use for collision resolution.
type SchemaDescriptor struct {
Fields []FieldDescriptor
HasAdditionalProperties bool
AdditionalPropertiesType string
}
SchemaDescriptor describes a Schema, a type definition.
type SchemaPath
added in
v2.7.0
type SchemaPath []string
SchemaPath represents the document location of a schema, e.g.
["components", "schemas", "Pet", "properties", "name"].
func (SchemaPath) String
added in
v2.7.0
func (sp SchemaPath) String() string
String returns the path joined with "/".
type SecurityDefinition struct {
ProviderName string
Scopes []string
}
func DescribeSecurityDefinition(securityRequirements openapi3.SecurityRequirements) []SecurityDefinition
type SecuritySchemeProvider struct {
// Name is the sanitized scheme name; templates derive the constant name
// (<Name>Scopes), the context key type name and the key's string value
// from it.
Name string
// ImportedScopes, when non-empty, is the scopes constant declared by the
// package that import-mapping assigns this scheme's $ref to (e.g.
// "externalRef0.BearerAuthScopes", or unqualified for the current
// package). The local constant is declared as an alias of it, so the
// context key -- which context.Value compares by type and value -- is
// shared across the generated packages. Empty means the scheme is
// declared locally with its own context key type.
ImportedScopes string
}
SecuritySchemeProvider describes one security scheme from
components/securitySchemes for which a scopes context-key constant is
generated.
type ServerObjectDefinition struct {
// GoName is the name of the variable for this Server URL
GoName string
// OAPISchema is the underlying OpenAPI representation of the Server
OAPISchema *openapi3.Server
}
ServerObjectDefinition defines the definition of an OpenAPI Server object (https://spec.openapis.org/oas/v3.0.3#server-object ) as it is provided to code generation in `oapi-codegen`
func (ServerObjectDefinition) EnumDefaultPointers
added in
v2.7.0
func (s ServerObjectDefinition) EnumDefaultPointers() []ServerURLDefaultPointer
EnumDefaultPointers returns one entry per enum-typed used variable
with a `default` set. The template iterates this directly rather
than recomputing identifier names from `$v.Default`.
func (s ServerObjectDefinition) NewServerFunctionParams() string
NewServerFunctionParams returns the formatted parameter list for
the generated `New<ServerName>(...)` function -- one typed parameter
per declared-and-used variable, plus one `string` parameter per
`{name}` placeholder that appears in the URL but isn't in
`variables` (#2005). The two groups are sorted together
alphabetically so the generated signature is deterministic.
Equivalent to calling `genServerURLWithVariablesFunctionParams` for
the typed half and concatenating the undeclared half -- but exposing
it as a method keeps server-urls.tmpl free of that combination
logic and means the template helper itself stayed at its
pre-existing two-argument shape (so any user-supplied custom
`server-urls.tmpl` override that calls the helper directly is
unaffected).
func (ServerObjectDefinition) UndeclaredPlaceholders
added in
v2.7.0
func (s ServerObjectDefinition) UndeclaredPlaceholders() []string
UndeclaredPlaceholders returns the sorted list of `{name}`
placeholder names that appear in OAPISchema.URL but have no
corresponding entry in OAPISchema.Variables. The previous code
generated a function that referenced only declared variables, so
any undeclared placeholder remained in the URL after substitution
and the trailing `{`/`}` runtime check tripped on every call --
making the generated function permanently unusable
(https://github.com/oapi-codegen/oapi-codegen/issues/2005 ). The
template now adds these as plain `string` parameters so callers
can fill them in directly.
func (ServerObjectDefinition) UsedVariables
added in
v2.7.0
func (s ServerObjectDefinition) UsedVariables() map[string]*openapi3.ServerVariable
UsedVariables returns the subset of OAPISchema.Variables whose
`{name}` placeholder actually appears in OAPISchema.URL. Variables
declared but unused are skipped -- they would otherwise produce a
type, constant, function parameter, and a no-op `strings.ReplaceAll`
(https://github.com/oapi-codegen/oapi-codegen/issues/2004 ). Used by
both server-urls.tmpl and BuildServerURLTypeDefinitions so that
emitted types and the generated function signature stay in sync.
type ServerURLDefaultPointer struct {
// VariableName is the OpenAPI variable name (for doc comments).
VariableName string
// TypeName is the enum's Go type, e.g. `ServerUrlFooBarVariable`.
TypeName string
// PointerName is the constant being declared. Normally it is
// `<TypeName>Default` (matching the historical naming). Switches
// to `<TypeName>DefaultValue` only when the variable's enum
// contains a value whose identifier suffix is the literal string
// "Default" -- i.e. exactly the case that produced #2003's
// duplicate-const compile error under the old codegen. Specs that
// compiled cleanly before keep their `Default` name.
PointerName string
// TargetName is the fully-qualified enum-value constant that the
// pointer references, e.g. `<TypeName>N443` or `<TypeName>Foo1`.
TargetName string
// Description is the variable's OpenAPI description (doc comment).
Description string
}
ServerURLDefaultPointer carries the pre-computed identifier names
needed to emit a typed default-pointer constant for an enum-typed
server-URL variable. Computed in Go (not the template) so that the
pointer's reference to the enum-value constant always agrees with
the identifier the const-block actually emitted, including in
dedup-suffix cases (e.g. `enum: ["foo", "FOO"]` with `default: "FOO"`
→ enum const is `<Prefix>Foo1`, pointer must reference exactly that).
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 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, compatibility options 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 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 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
added in
v2.9.0
func (c StructTagsConfig) Merge(other StructTagsConfig) StructTagsConfig
Merge merges user config on top of this config by tag name: matching
names override the default template, new names are appended.
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 BuildServerURLTypeDefinitions(spec *openapi3.T) ([]TypeDefinition, error)
BuildServerURLTypeDefinitions synthesizes a TypeDefinition for every
server-URL variable that defines an `enum`. These are appended into
the same TypeDefinition slices used by GenerateTypes (typedef.tmpl)
and GenerateEnums (constants.tmpl), so that server-URL enum
variables get the same `type X string`, `const ( ... )` block, and
`Valid()` method as any other enum-bearing schema. The
server-urls.tmpl template no longer emits these declarations
directly.
Variables without an `enum` are not handled here: server-urls.tmpl
continues to emit their `type` and (optional) default constant
inline, since the generic enum path has nothing to contribute for a
non-enum string.
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(op OperationDefinition) []TypeDefinition
func GenerateTypesForParameters(t *template.Template, params map[string]*openapi3.ParameterRef) ([]TypeDefinition, error)
GenerateTypesForParameters generates type definitions for any custom types defined in the
components/parameters section of the Swagger spec.
func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*openapi3.RequestBodyRef) ([]TypeDefinition, error)
GenerateTypesForRequestBodies generates type definitions for any custom types defined in the
components/requestBodies section of the Swagger spec.
func GenerateTypesForResponses(t *template.Template, responses openapi3.ResponseBodies) ([]TypeDefinition, error)
GenerateTypesForResponses generates type definitions for any custom types defined in the
components/responses section of the Swagger spec.
func GenerateTypesForSchemas(t *template.Template, schemas map[string]*openapi3.SchemaRef, excludeSchemas []string) ([]TypeDefinition, error)
GenerateTypesForSchemas generates type definitions for any custom types defined in the
components/schemas section of the Swagger spec.
func GenerateTypesForSecuritySchemes(t *template.Template, schemes map[string]*openapi3.SecuritySchemeRef) ([]TypeDefinition, error)
GenerateTypesForSecuritySchemes generates type definitions for any custom types defined in the
components/securitySchemes section of the Swagger spec.
func (TypeDefinition) DeprecationComment
added in
v2.8.0
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
added in
v2.8.0
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 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
added in
v2.6.0
func (base TypeMapping) Merge(user TypeMapping) TypeMapping
Merge returns a new TypeMapping with user overrides applied on top of base.
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 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).
Source Files
View all Source files