codegen
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
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, softwaredistributed 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 andlimitations 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, softwaredistributed 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 andlimitations 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, softwaredistributed 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 andlimitations 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, softwaredistributed 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 andlimitations under the License.
Index¶
- Variables
- func DeprecationComment(reason string) string
- func EscapePathElements(path string) string
- func GenFieldsFromProperties(props []Property) []string
- func GenStructFromAllOf(allOf []*openapi3.SchemaRef, path []string) (string, error)
- 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) ([]RequestBodyDefinition, []TypeDefinition, 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, ops []OperationDefinition) (string, error)
- func GenerateEchoServer(t *template.Template, operations []OperationDefinition) (string, error)
- func GenerateEnums(t *template.Template, types []TypeDefinition) (string, error)
- func GenerateFiberServer(t *template.Template, operations []OperationDefinition) (string, error)
- func GenerateGinServer(t *template.Template, operations []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 GenerateIrisServer(t *template.Template, operations []OperationDefinition) (string, error)
- func GenerateServerURLs(t *template.Template, spec *openapi3.T) (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, operations []OperationDefinition, opts Configuration) (string, error)
- func GenerateTemplates(templates []string, t *template.Template, ops interface{}) (string, error)
- func GenerateTypeDefinitions(t *template.Template, swagger *openapi3.T, ops []OperationDefinition, ...) (string, 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 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 MergeImports(dst, src map[string]goImport)
- 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 ReplacePathParamsWithStr(uri string) string
- func SanitizeCode(goCode string) string
- func SanitizeEnumNames(enumNames, enumValues []string) map[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 StringInArray(str string, array []string) bool
- func StringToGoComment(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
- type AdditionalImport
- type CompatibilityOptions
- type Configuration
- type Constants
- type Discriminator
- type EnumDefinition
- type FieldDescriptor
- type GenerateOptions
- type NameNormalizer
- type NameNormalizerFunction
- type NameNormalizerMap
- type OperationDefinition
- func (o *OperationDefinition) AllParams() []ParameterDefinition
- func (o *OperationDefinition) GetResponseTypeDefinitions() ([]ResponseTypeDefinition, error)
- func (o *OperationDefinition) HasBody() bool
- func (o OperationDefinition) HasMaskedRequestContentTypes() bool
- func (o *OperationDefinition) Params() []ParameterDefinition
- func (o *OperationDefinition) RequiresParamObject() bool
- func (o *OperationDefinition) SummaryAsComment() string
- type OutputOptions
- type OutputOptionsOverlay
- type ParameterDefinition
- func CombineOperationParameters(globalParams []ParameterDefinition, localParams []ParameterDefinition) ([]ParameterDefinition, error)
- func DescribeParameters(params openapi3.Parameters, path []string) ([]ParameterDefinition, error)
- func FilterParameterDefinitionByType(params []ParameterDefinition, in string) []ParameterDefinition
- func SortParamsByPath(path string, in []ParameterDefinition) ([]ParameterDefinition, error)
- func (pd *ParameterDefinition) Explode() bool
- func (pd ParameterDefinition) GoName() string
- func (pd ParameterDefinition) GoVariableName() string
- func (pd ParameterDefinition) HasOptionalPointer() bool
- func (pd ParameterDefinition) IndirectOptional() booldeprecated
- func (pd *ParameterDefinition) IsJson() bool
- func (pd *ParameterDefinition) IsPassThrough() bool
- func (pd *ParameterDefinition) IsStyled() bool
- func (pd *ParameterDefinition) JsonTag() string
- func (pd *ParameterDefinition) Style() string
- func (pd ParameterDefinition) TypeDef() string
- type ParameterDefinitions
- type Property
- type RefWrapper
- type RequestBodyDefinition
- func (r RequestBodyDefinition) CustomType() bool
- func (r RequestBodyDefinition) IsFixedContentType() bool
- func (r RequestBodyDefinition) IsJSON() bool
- func (r RequestBodyDefinition) IsSupported() bool
- func (r RequestBodyDefinition) IsSupportedByClient() bool
- func (r RequestBodyDefinition) Suffix() string
- func (r RequestBodyDefinition) TypeDef(opID string) *TypeDefinition
- type RequestBodyEncoding
- type ResponseContentDefinition
- func (r ResponseContentDefinition) HasFixedContentType() bool
- func (r ResponseContentDefinition) IsJSON() bool
- func (r ResponseContentDefinition) IsSupported() bool
- func (r ResponseContentDefinition) NameTagOrContentType() string
- func (r ResponseContentDefinition) TypeDef(opID string, statusCode int) *TypeDefinition
- type ResponseDefinition
- type ResponseHeaderDefinition
- type ResponseTypeDefinition
- type Schema
- type SchemaDescriptor
- type SecurityDefinition
- type ServerObjectDefinition
- type TypeDefinition
- 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)
- type UnionElement
Constants¶
This section is empty.
Variables¶
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.
var TemplateFunctions =template.FuncMap{"genParamArgs": genParamArgs,"genParamTypes": genParamTypes,"genParamNames": genParamNames,"genParamFmtString":ReplacePathParamsWithStr,"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,"getResponseTypeDefinitions": getResponseTypeDefinitions,"toStringArray": toStringArray,"lower":strings.ToLower,"title": titleCaser.String,"stripNewLines": stripNewLines,"sanitizeGoIdentity":SanitizeGoIdentity,"toGoComment":StringWithTypeNameToGoComment,"genServerURLWithVariablesFunctionParams": genServerURLWithVariablesFunctionParams,}
TemplateFunctions is passed to the template engine, and we can call eachfunction here by keyName from the template code.
Functions¶
funcEscapePathElements¶
EscapePathElements breaks apart a path, and looks at each element. If it'snot a path parameter, eg, {param}, it will URL-escape the element.
funcGenFieldsFromProperties¶
GenFieldsFromProperties produce corresponding field names with JSON annotations,given a list of schema descriptors
funcGenStructFromAllOf¶
GenStructFromAllOf generates an object that is the union of the objects in theinput array. In the case of Ref objects, we use an embedded struct, otherwise,we inline the fields.
funcGenerate¶
func Generate(spec *openapi3.T, optsConfiguration) (string,error)
Generate uses the Go templating engine to generate all of our server wrappers fromthe descriptions we've built up above from the schema objects.opts defines
funcGenerateAdditionalPropertyBoilerplate¶
func GenerateAdditionalPropertyBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string,error)
GenerateAdditionalPropertyBoilerplate generates all the glue code which providesthe API for interacting with additional properties and JSON-ification
funcGenerateBodyDefinitions¶
func GenerateBodyDefinitions(operationIDstring, bodyOrRef *openapi3.RequestBodyRef) ([]RequestBodyDefinition, []TypeDefinition,error)
GenerateBodyDefinitions turns the Swagger body definitions into a list of our bodydefinitions which will be used for code generation.
funcGenerateChiServer¶
func GenerateChiServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateChiServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateClient¶
func GenerateClient(t *template.Template, ops []OperationDefinition) (string,error)
GenerateClient uses the template engine to generate the function which registers our wrappersas Echo path handlers.
funcGenerateClientWithResponses¶
func GenerateClientWithResponses(t *template.Template, ops []OperationDefinition) (string,error)
GenerateClientWithResponses generates a client which extends the basic client which does responseunmarshaling.
funcGenerateConstants¶
func GenerateConstants(t *template.Template, ops []OperationDefinition) (string,error)
GenerateConstants generates operation ids, context keys, paths, etc. to be exported as constants
funcGenerateEchoServer¶
func GenerateEchoServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateEchoServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateEnums¶
func GenerateEnums(t *template.Template, types []TypeDefinition) (string,error)
funcGenerateFiberServer¶
func GenerateFiberServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateFiberServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateGinServer¶
func GenerateGinServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateGinServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateGorillaServer¶
func GenerateGorillaServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateGorillaServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateImports¶
func GenerateImports(t *template.Template, externalImports []string, packageNamestring, versionOverride *string) (string,error)
GenerateImports generates our import statements and package definition.
funcGenerateInlinedSpec¶
func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string,error)
GenerateInlinedSpec generates a gzipped, base64 encoded JSON representation of theswagger definition, which we embed inside the generated code.
funcGenerateIrisServer¶
func GenerateIrisServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateIrisServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateServerURLs¶added inv2.5.0
funcGenerateStdHTTPServer¶
func GenerateStdHTTPServer(t *template.Template, operations []OperationDefinition) (string,error)
GenerateStdHTTPServer generates all the go code for the ServerInterface as well asall the wrapper functions around our handlers.
funcGenerateStrictResponses¶
func GenerateStrictResponses(t *template.Template, responses []ResponseDefinition) (string,error)
funcGenerateStrictServer¶
func GenerateStrictServer(t *template.Template, operations []OperationDefinition, optsConfiguration) (string,error)
funcGenerateTemplates¶
GenerateTemplates used to generate templates
funcGenerateTypes¶
func GenerateTypes(t *template.Template, types []TypeDefinition) (string,error)
GenerateTypes passes a bunch of types to the template engine, and buffersits output into a string.
funcGenerateTypesForOperations¶
func GenerateTypesForOperations(t *template.Template, ops []OperationDefinition) (string,error)
GenerateTypesForOperations generates code for all types produced within operations
funcGenerateUnionAndAdditionalProopertiesBoilerplate¶
func GenerateUnionAndAdditionalProopertiesBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string,error)
funcGenerateUnionBoilerplate¶
func GenerateUnionBoilerplate(t *template.Template, typeDefs []TypeDefinition) (string,error)
funcGetParametersImports¶
func GetParametersImports(params map[string]*openapi3.ParameterRef) (map[string]goImport,error)
funcGetRequestBodiesImports¶
func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[string]goImport,error)
funcGetResponsesImports¶
func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string]goImport,error)
funcGetUserTemplateText¶
GetUserTemplateText attempts to retrieve the template text from a passed in URL or filepath when inputData is more than one line.This function will attempt to load a file first, and if it fails, will try to get thedata from the remote endpoint.The timeout for remote download file is 30 seconds.
funcGoSchemaImports¶
funcIsGoIdentity¶
IsGoIdentity checks if the given string can be used as an identityin the generated code like a type name or constant name.
funcIsGoKeyword¶
IsGoKeyword returns whether the given string is a go keyword
funcIsGoTypeReference¶
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 -> falseIsGoTypeReference can be used to check whether RefPathToGoType($ref) is possible.
funcIsPredeclaredGoIdentifier¶
IsPredeclaredGoIdentifier returns whether the given stringis a predefined go identifier.
funcIsValidGoIdentity¶
IsValidGoIdentity checks if the given string can be used as aname of variable, constant, or type.
funcIsWholeDocumentReference¶
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 -> truehttp://deepmap.com/schemas/document.json -> truehttp://deepmap.com/schemas/document.json#/Foo -> false
funcLoadTemplates¶
LoadTemplates loads all of our template files into a text/template. Thepath of template is relative to the templates directory.
funcLowercaseFirstCharacter¶
LowercaseFirstCharacter Lowercases the first character in a string. This assumes UTF-8, so we haveto be careful with unicode, don't treat it as a byte array.
funcLowercaseFirstCharacters¶
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.
funcMergeImports¶
func MergeImports(dst, src map[string]goImport)
funcOperationImports¶
func OperationImports(ops []OperationDefinition) (map[string]goImport,error)
funcOrderedParamsFromUri¶
OrderedParamsFromUri returns the argument names, in order, in a given URI string, so for/path/{param1}/{.param2*}/{?param3}, it would return param1, param2, param3
funcPathToTypeName¶
PathToTypeName converts a path, like Object/field1/nestedField into a gotype name.
funcPropertiesEqual¶
funcRefPathToGoType¶
RefPathToGoType takes a $ref value and converts it to a Go typename.#/components/schemas/Foo -> Foo#/components/parameters/Bar -> Bar#/components/responses/Baz -> BazRemote components (document.json#/Foo) are supported if they present in --import-mappingURL components (http://deepmap.com/schemas/document.json#/Foo) are supported if they present in --import-mappingRemote and URL also support standard local paths even though the spec doesn't mention them.
funcRefPathToObjName¶
RefPathToObjName returns the name of referenced object without changes.
#/components/schemas/Foo -> Foo#/components/parameters/Bar -> Bar#/components/responses/baz_baz -> baz_bazdocument.json#/Foo -> Foohttp://deepmap.com/schemas/document.json#/objObj -> objObj
Does not check refPath correctness.
funcReplacePathParamsWithStr¶
ReplacePathParamsWithStr replaces path parameters of the form {param} with %s
funcSanitizeCode¶
SanitizeCode runs sanitizers across the generated Go code to ensure thegenerated code will be able to compile.
funcSanitizeEnumNames¶
SanitizeEnumNames fixes illegal chars in the enum namesand removes duplicates
funcSanitizeGoIdentity¶
SanitizeGoIdentity deletes and replaces the illegal runes in the givenstring to use the string as a valid identity.
funcSchemaHasAdditionalProperties¶
According to the spec, additionalProperties may be true, false, or aschema. 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 littledifferently, in that if you want additionalProperties code to be generated,you must specify an additionalProperties typeIf additionalProperties it true/false, this field will be non-nil.
funcSchemaNameToTypeName¶
SchemaNameToTypeName converts a Schema name to a valid Go type name. It converts to camel case, and makes sure the name isvalid in Go
funcSortedMapKeys¶
SortedMapKeys takes a map with keys of type string and returns a slice of thosekeys sorted lexicographically.
funcSortedSchemaKeys¶
SortedSchemaKeys returns the keys of the given SchemaRef dictionary in sortedorder, since Golang scrambles dictionary keys. This isn't a generic key sort, becausewe support an extension to grant specific orders to schemas to help control outputordering.
funcStringInArray¶
StringInArray checks whether the specified string is present in an arrayof strings
funcStringToGoComment¶
StringToGoComment renders a possible multi-line string as a valid Go-Comment.Each line is prefixed as a comment.
funcStringWithTypeNameToGoComment¶
StringWithTypeNameToGoComment renders a possible multi-line string as avalid Go-Comment, including the name of the type being referenced. Each lineis prefixed as a comment.
funcSwaggerUriToChiUri¶
SwaggerUriToChiUri converts a swagger style path URI with parameters to aChi compatible path URI. We need to replace all Swagger parameters with"{param}". Valid input parameters are:
{param}{param*}{.param}{.param*}{;param}{;param*}{?param}{?param*}
funcSwaggerUriToEchoUri¶
SwaggerUriToEchoUri converts a OpenAPI style path URI with parameters to anEcho 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*}
funcSwaggerUriToFiberUri¶
SwaggerUriToFiberUri converts a OpenAPI style path URI with parameters to aFiber 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*}
funcSwaggerUriToGinUri¶
SwaggerUriToGinUri converts a swagger style path URI with parameters to aGin compatible path URI. We need to replace all Swagger parameters with":param". Valid input parameters are:
{param}{param*}{.param}{.param*}{;param}{;param*}{?param}{?param*}
funcSwaggerUriToGorillaUri¶
SwaggerUriToGorillaUri converts a swagger style path URI with parameters to aGorilla compatible path URI. We need to replace all Swagger parameters with":param". Valid input parameters are:
{param}{param*}{.param}{.param*}{;param}{;param*}{?param}{?param*}
funcSwaggerUriToIrisUri¶
SwaggerUriToIrisUri converts a OpenAPI style path URI with parameters to anIris compatible path URI. We need to replace all of OpenAPI parameters with
{param}{param*}{.param}{.param*}{;param}{;param*}{?param}{?param*}
funcSwaggerUriToStdHttpUri¶
SwaggerUriToStdHttpUri converts a swagger style path URI with parameters to aChi compatible path URI. We need to replace all Swagger parameters with"{param}". Valid input parameters are:
{param}{param*}{.param}{.param*}{;param}{;param*}{?param}{?param*}
funcToCamelCase¶
ToCamelCase will convert query-arg style strings to CamelCase. We willuse `., -, +, :, ;, _, ~, ' ', (, ), {, }, [, ]` as valid delimiters for words.So, "word.word-word+word:word;word_word~word word(word)word{word}[word]"would be converted to WordWordWordWordWordWordWordWordWordWordWordWordWord
funcToCamelCaseWithDigits¶
ToCamelCaseWithDigits function will convert query-arg style strings to CamelCase. We willuse `., -, +, :, ;, _, ~, ' ', (, ), {, }, [, ]` 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
funcToCamelCaseWithInitialisms¶
ToCamelCaseWithInitialisms function will convert query-arg style strings to CamelCase with initialisms in uppercase.So, httpOperationId would be converted to HTTPOperationID
funcTypeDefinitionsEquivalent¶
func TypeDefinitionsEquivalent(t1, t2TypeDefinition)bool
TypeDefinitionsEquivalent checks for equality between two type definitions, butnot every field is considered. We only want to know if they are fundamentallythe same type.
funcUppercaseFirstCharacter¶
UppercaseFirstCharacter Uppercases the first character in a string. This assumes UTF-8, so we haveto be careful with unicode, don't treat it as a byte array.
funcUppercaseFirstCharacterWithPkgName¶
Uppercase the first character in a identifier with pkg name. This assumes UTF-8, so we haveto be careful with unicode, don't treat it as a byte array.
Types¶
typeCompatibilityOptions¶
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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/531OldMergeSchemasbool `yaml:"old-merge-schemas,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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/549OldEnumConflictsbool `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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/549OldAliasingbool `yaml:"old-aliasing,omitempty"`// When an object contains no members, and only an additionalProperties specification,// it is flattened to a mapDisableFlattenAdditionalPropertiesbool `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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/604DisableRequiredReadOnlyAsPointerbool `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.AlwaysPrefixEnumValuesbool `yaml:"always-prefix-enum-values,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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/786ApplyChiMiddlewareFirstToLastbool `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 seehttps://github.com/oapi-codegen/oapi-codegen/issues/841ApplyGorillaMiddlewareFirstToLastbool `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.CircularReferenceLimitint `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.AllowUnexportedStructFieldNamesbool `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.PreserveOriginalOperationIdCasingInEmbeddedSpecbool `yaml:"preserve-original-operation-id-casing-in-embedded-spec"`}
CompatibilityOptions specifies backward compatibility settings for thecode generator.
func (CompatibilityOptions)Validate¶added inv2.4.0
func (coCompatibilityOptions) Validate() map[string]string
typeConfiguration¶
type Configuration struct {// PackageName to generate the code underPackageNamestring `yaml:"package"`// Generate specifies which supported output formats to generateGenerateGenerateOptions `yaml:"generate,omitempty"`// CompatibilityOptions specifies backward compatibility settings for the code generatorCompatibilityCompatibilityOptions `yaml:"compatibility,omitempty"`// OutputOptions are used to modify the output code in some way.OutputOptionsOutputOptions `yaml:"output-options,omitempty"`// ImportMapping specifies the golang package path for each external referenceImportMapping map[string]string `yaml:"import-mapping,omitempty"`// AdditionalImports defines any additional Go imports to add to the generated codeAdditionalImports []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.mdNoVCSVersionOverride *string `yaml:"-"`}
Configuration defines code generation customizations
func (Configuration)UpdateDefaults¶
func (oConfiguration) UpdateDefaults()Configuration
UpdateDefaults sets reasonable default values for unset fields in Configuration
func (Configuration)Validate¶
func (oConfiguration) Validate()error
Validate checks whether Configuration represent a valid configuration
typeConstants¶
type Constants struct {// SecuritySchemeProviderNames holds all provider names for security schemes.SecuritySchemeProviderNames []string// EnumDefinitions holds type and value information for all enumsEnumDefinitions []EnumDefinition}
typeDiscriminator¶
type Discriminator struct {// maps discriminator value to go typeMapping map[string]string// JSON property name that holds the discriminatorPropertystring}
func (*Discriminator)JSONTag¶
func (d *Discriminator) JSONTag()string
func (*Discriminator)PropertyName¶
func (d *Discriminator) PropertyName()string
typeEnumDefinition¶
type EnumDefinition struct {// Schema is the scheme of a type which has a list of enum values, eg, the// "container" of the enum.SchemaSchema// TypeName is the name of the enum's type, usually aliased from something.TypeNamestring// ValueWrapper wraps the value. It's used to conditionally apply quotes// around strings.ValueWrapperstring// 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.PrefixTypeNamebool}
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
typeFieldDescriptor¶
type FieldDescriptor struct {Requiredbool// Is the schema required? If not, we'll pass by pointerGoTypestring// The Go type needed to represent the json type.GoNamestring// The Go compatible type name for the typeJsonNamestring// The json type name for the typeIsRefbool// Is this schema a reference to predefined object?}
typeGenerateOptions¶
type GenerateOptions struct {// IrisServer specifies whether to generate iris server boilerplateIrisServerbool `yaml:"iris-server,omitempty"`// ChiServer specifies whether to generate chi server boilerplateChiServerbool `yaml:"chi-server,omitempty"`// FiberServer specifies whether to generate fiber server boilerplateFiberServerbool `yaml:"fiber-server,omitempty"`// EchoServer specifies whether to generate echo server boilerplateEchoServerbool `yaml:"echo-server,omitempty"`// GinServer specifies whether to generate gin server boilerplateGinServerbool `yaml:"gin-server,omitempty"`// GorillaServer specifies whether to generate Gorilla server boilerplateGorillaServerbool `yaml:"gorilla-server,omitempty"`// StdHTTPServer specifies whether to generate stdlib http server boilerplateStdHTTPServerbool `yaml:"std-http-server,omitempty"`// Strict specifies whether to generate strict server wrapperStrictbool `yaml:"strict-server,omitempty"`// Client specifies whether to generate client boilerplateClientbool `yaml:"client,omitempty"`// Models specifies whether to generate type definitionsModelsbool `yaml:"models,omitempty"`// EmbeddedSpec indicates whether to embed the swagger spec in the generated codeEmbeddedSpecbool `yaml:"embedded-spec,omitempty"`// ServerURLs generates types for the `Server` definitions' URLs, instead of needing to provide your own valuesServerURLsbool `yaml:"server-urls,omitempty"`}
GenerateOptions specifies which supported output formats to generate.
func (GenerateOptions)Validate¶added inv2.4.0
func (ooGenerateOptions) Validate() map[string]string
func (GenerateOptions)Warnings¶added inv2.5.0
func (ooGenerateOptions) Warnings() map[string]string
typeNameNormalizer¶
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
typeNameNormalizerFunction¶
type NameNormalizerFunctionstring
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.NameNormalizerFunctionUnsetNameNormalizerFunction = ""// NameNormalizerFunctionToCamelCase will use the `ToCamelCase` function.//// For instance://// - `getHttpPet` => `GetHttpPet`// - `OneOf2things` => `OneOf2things`NameNormalizerFunctionToCamelCaseNameNormalizerFunction = "ToCamelCase"// NameNormalizerFunctionToCamelCaseWithDigits will use the `NameNormalizerFunctionToCamelCaseWithDigits` function.//// For instance://// - `getHttpPet` => `GetHttpPet`// - `OneOf2things` => `OneOf2Things`NameNormalizerFunctionToCamelCaseWithDigitsNameNormalizerFunction = "ToCamelCaseWithDigits"// NameNormalizerFunctionToCamelCaseWithInitialisms will use the `NameNormalizerFunctionToCamelCaseWithInitialisms` function.//// For instance://// - `getHttpPet` => `GetHTTPPet`// - `OneOf2things` => `OneOf2things`NameNormalizerFunctionToCamelCaseWithInitialismsNameNormalizerFunction = "ToCamelCaseWithInitialisms")
typeNameNormalizerMap¶
type NameNormalizerMap map[NameNormalizerFunction]NameNormalizer
func (NameNormalizerMap)Options¶
func (mNameNormalizerMap) Options() []string
typeOperationDefinition¶
type OperationDefinition struct {// OperationId is the `operationId` field from the OpenAPI Specification, after going through a `nameNormalizer`, and will be used to generate function namesOperationIdstringPathParams []ParameterDefinition// Parameters in the path, eg, /path/:paramHeaderParams []ParameterDefinition// Parameters in HTTP headersQueryParams []ParameterDefinition// Parameters in the query, /path?paramCookieParams []ParameterDefinition// Parameters in cookiesTypeDefinitions []TypeDefinition// These are all the types we need to define for this operationSecurityDefinitions []SecurityDefinition// These are the security providersBodyRequiredboolBodies []RequestBodyDefinition// The list of bodies for which to generate handlers.Responses []ResponseDefinition// The list of responses that can be accepted by handlers.Summarystring// Summary string from Swagger, used to generate a commentMethodstring// GET, POST, DELETE, etc.Pathstring// The Swagger path for the operation, like /resource/{id}Spec *openapi3.Operation}
OperationDefinition describes an Operation
funcOperationDefinitions¶
func OperationDefinitions(swagger *openapi3.T, initialismOverridesbool) ([]OperationDefinition,error)
OperationDefinitions returns all operations for a swagger definition.
func (*OperationDefinition)AllParams¶
func (o *OperationDefinition) AllParams() []ParameterDefinition
AllParams returns all parameters
func (*OperationDefinition)GetResponseTypeDefinitions¶
func (o *OperationDefinition) GetResponseTypeDefinitions() ([]ResponseTypeDefinition,error)
GetResponseTypeDefinitions produces a list of type definitions for a given Operation for the responsetypes which we know how to parse. These will be turned into fields on aresponse object for automatic deserialization of responses in the generatedClient code. See "client-with-responses.tmpl".
func (*OperationDefinition)HasBody¶
func (o *OperationDefinition) HasBody()bool
HasBody is called by the template engine to determine whether to generate bodymarshaling code on the client. This is true for all body types, whetherwe generate types for them.
func (OperationDefinition)HasMaskedRequestContentTypes¶
func (oOperationDefinition) HasMaskedRequestContentTypes()bool
func (*OperationDefinition)Params¶
func (o *OperationDefinition) Params() []ParameterDefinition
Params returns the list of all parameters except Path parameters. Path parametersare handled differently from the rest, since they're mandatory.
func (*OperationDefinition)RequiresParamObject¶
func (o *OperationDefinition) RequiresParamObject()bool
If we have parameters other than path parameters, they're bundled into anobject. Returns true if we have any of those. This is used from the templateengine.
func (*OperationDefinition)SummaryAsComment¶
func (o *OperationDefinition) SummaryAsComment()string
SummaryAsComment returns the Operations summary as a multi line comment
typeOutputOptions¶
type OutputOptions struct {// Whether to skip go imports on the generated codeSkipFmtbool `yaml:"skip-fmt,omitempty"`// Whether to skip pruning unused components on the generated codeSkipPrunebool `yaml:"skip-prune,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 filesUserTemplates 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 typesResponseTypeSuffixstring `yaml:"response-type-suffix,omitempty"`// Override the default generated client type with the valueClientTypeNamestring `yaml:"client-type-name,omitempty"`// Whether to use the initialism overridesInitialismOverridesbool `yaml:"initialism-overrides,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"`// Whether to generate nullable type for nullable fieldsNullableTypebool `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"`// 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`NameNormalizerstring `yaml:"name-normalizer,omitempty"`// Overlay defines configuration for the OpenAPI Overlay (https://github.com/OAI/Overlay-Specification) to manipulate the OpenAPI specification before generation. This allows modifying the specification without needing to apply changes directly to it, making it easier to keep it up-to-date.OverlayOutputOptionsOverlay `yaml:"overlay"`// EnableYamlTags adds YAML tags to generated structs, in addition to default JSON onesEnableYamlTagsbool `yaml:"yaml-tags,omitempty"`// ClientResponseBytesFunction decides whether to enable the generation of a `Bytes()` method on response objects for `ClientWithResponses`ClientResponseBytesFunctionbool `yaml:"client-response-bytes-function,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)PreferSkipOptionalPointerbool `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.PreferSkipOptionalPointerWithOmitzerobool `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` checkPreferSkipOptionalPointerOnContainerTypesbool `yaml:"prefer-skip-optional-pointer-on-container-types,omitempty"`}
OutputOptions are used to modify the output code in some way.
func (OutputOptions)Validate¶added inv2.4.0
func (ooOutputOptions) Validate() map[string]string
typeOutputOptionsOverlay¶added inv2.4.0
type OutputOptionsOverlay struct {Pathstring `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"`}
typeParameterDefinition¶
type ParameterDefinition struct {ParamNamestring// The original json parameter name, eg param_nameInstring// Where the parameter is defined - path, header, cookie, queryRequiredbool// Is this a required parameter?Spec *openapi3.ParameterSchemaSchema}
funcCombineOperationParameters¶
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
funcDescribeParameters¶
func DescribeParameters(paramsopenapi3.Parameters, path []string) ([]ParameterDefinition,error)
DescribeParameters walks the given parameters dictionary, and generates the abovedescriptors into a flat list. This makes it a lot easier to traverse thedata in the template engine.
funcFilterParameterDefinitionByType¶
func FilterParameterDefinitionByType(params []ParameterDefinition, instring) []ParameterDefinition
FilterParameterDefinitionByType returns the subset of the specified parameters which are of thespecified type.
funcSortParamsByPath¶
func SortParamsByPath(pathstring, in []ParameterDefinition) ([]ParameterDefinition,error)
SortParamsByPath reorders the given parameter definitions to match those in the path URI.
func (*ParameterDefinition)Explode¶
func (pd *ParameterDefinition) Explode()bool
func (ParameterDefinition)GoName¶
func (pdParameterDefinition) GoName()string
func (ParameterDefinition)GoVariableName¶
func (pdParameterDefinition) GoVariableName()string
func (ParameterDefinition)HasOptionalPointer¶added inv2.5.0
func (pdParameterDefinition) 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)IndirectOptionaldeprecated
func (pdParameterDefinition) 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 JSON annotation to map GoType to json type name. If ParameterFoo is marshaled to json as "foo", this will create the annotation'json:"foo"'
func (*ParameterDefinition)Style¶
func (pd *ParameterDefinition) Style()string
func (ParameterDefinition)TypeDef¶
func (pdParameterDefinition) TypeDef()string
TypeDef is here as an adapter after a large refactoring so that I don'thave to update all the templates. It returns the type definition for a parameter,without the leading '*' for optional ones.
typeParameterDefinitions¶
type ParameterDefinitions []ParameterDefinition
func (ParameterDefinitions)FindByName¶
func (pParameterDefinitions) FindByName(namestring) *ParameterDefinition
typeProperty¶
type Property struct {DescriptionstringJsonFieldNamestringSchemaSchemaRequiredboolNullableboolReadOnlyboolWriteOnlyboolNeedsFormTagboolExtensions map[string]interface{}Deprecatedbool}
func (Property)GoFieldName¶
func (Property)HasOptionalPointer¶added inv2.5.0
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.
typeRefWrapper¶
typeRequestBodyDefinition¶
type RequestBodyDefinition struct {// Is this body required, or optional?Requiredbool// This is the schema describing this bodySchemaSchema// When we generate type names, we need a Tag for it, such as JSON, in// which case we will produce "JSONBody".NameTagstring// This is the content type corresponding to the body, eg, application/jsonContentTypestring// Whether this is the default body type. For an operation named OpFoo, we// will not add suffixes like OpFooJSONBody for this one.Defaultbool// Contains encoding options for formdataEncoding map[string]RequestBodyEncoding}
RequestBodyDefinition describes a request body
func (RequestBodyDefinition)CustomType¶
func (rRequestBodyDefinition) CustomType()bool
CustomType returns whether the body is a custom inline type, or pre-defined. This ispoorly named, but it's here for compatibility reasons post-refactoringTODO: clean up the templates code, it can be simpler.
func (RequestBodyDefinition)IsFixedContentType¶
func (rRequestBodyDefinition) IsFixedContentType()bool
IsFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (RequestBodyDefinition)IsJSON¶
func (rRequestBodyDefinition) IsJSON()bool
IsJSON returns whether this is a JSON media type, for instance:- application/json- application/vnd.api+json- application/*+json
func (RequestBodyDefinition)IsSupported¶
func (rRequestBodyDefinition) IsSupported()bool
IsSupported returns true if we support this content type for server. Otherwise io.Reader will be generated
func (RequestBodyDefinition)IsSupportedByClient¶
func (rRequestBodyDefinition) IsSupportedByClient()bool
IsSupportedByClient returns true if we support this content type for client. Otherwise only generic method will ge generated
func (RequestBodyDefinition)Suffix¶
func (rRequestBodyDefinition) Suffix()string
When we're generating multiple functions which relate to request bodies,this generates the suffix. Such as Operation DoFoo would be suffixed withDoFooWithXMLBody.
func (RequestBodyDefinition)TypeDef¶
func (rRequestBodyDefinition) TypeDef(opIDstring) *TypeDefinition
TypeDef returns the Go type definition for a request body
typeResponseContentDefinition¶
type ResponseContentDefinition struct {// This is the schema describing this contentSchemaSchema// This is the content type corresponding to the body, eg, application/jsonContentTypestring// When we generate type names, we need a Tag for it, such as JSON, in// which case we will produce "Response200JSONContent".NameTagstring}
func (ResponseContentDefinition)HasFixedContentType¶
func (rResponseContentDefinition) HasFixedContentType()bool
HasFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (ResponseContentDefinition)IsJSON¶
func (rResponseContentDefinition) IsJSON()bool
IsJSON returns whether this is a JSON media type, for instance:- application/json- application/vnd.api+json- application/*+json
func (ResponseContentDefinition)IsSupported¶
func (rResponseContentDefinition) IsSupported()bool
func (ResponseContentDefinition)NameTagOrContentType¶
func (rResponseContentDefinition) NameTagOrContentType()string
func (ResponseContentDefinition)TypeDef¶
func (rResponseContentDefinition) TypeDef(opIDstring, statusCodeint) *TypeDefinition
TypeDef returns the Go type definition for a request body
typeResponseDefinition¶
type ResponseDefinition struct {StatusCodestringDescriptionstringContents []ResponseContentDefinitionHeaders []ResponseHeaderDefinitionRefstring}
funcGenerateResponseDefinitions¶
func GenerateResponseDefinitions(operationIDstring, responses map[string]*openapi3.ResponseRef) ([]ResponseDefinition,error)
func (ResponseDefinition)GoName¶
func (rResponseDefinition) GoName()string
func (ResponseDefinition)HasFixedStatusCode¶
func (rResponseDefinition) HasFixedStatusCode()bool
func (ResponseDefinition)IsExternalRef¶
func (rResponseDefinition) IsExternalRef()bool
func (ResponseDefinition)IsRef¶
func (rResponseDefinition) IsRef()bool
typeResponseTypeDefinition¶
type ResponseTypeDefinition struct {TypeDefinition// The content type name where this is used, eg, application/jsonContentTypeNamestring// The type name of a response model.ResponseNamestringAdditionalTypeDefinitions []TypeDefinition}
ResponseTypeDefinition is an extension of TypeDefinition, specifically forresponse unmarshaling in ClientWithResponses.
typeSchema¶
type Schema struct {GoTypestring// The Go type needed to represent the schemaRefTypestring// If the type has a type name, this is setArrayType *Schema// The schema of array elementEnumValues map[string]string// Enum valuesProperties []Property// For an object, the fields with namesHasAdditionalPropertiesbool// Whether we support additional propertiesAdditionalPropertiesType *Schema// And if we do, their typeAdditionalTypes []TypeDefinition// We may need to generate auxiliary helper types, stored hereSkipOptionalPointerbool// Some types don't need a * in front when they're optionalDescriptionstring// The description of the elementUnionElements []UnionElement// Possible elements of oneOf/anyOf unionDiscriminator *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 fieldDefineViaAliasbool// The original OpenAPIv3 Schema.OAPISchema *openapi3.Schema}
Schema describes an OpenAPI schema, with lots of helper fields to use in thetemplating engine.
funcMergeSchemas¶
MergeSchemas merges all the fields in the schemas supplied into one giant schema.The idea is that we merge all fields together into one schema.
func (*Schema)AddProperty¶
AddProperty adds a new property to the current Schema, and returns an errorif it collides. Two identical fields will not collide, but two properties bythe same name, but different definition, will collide. It's safe to merge thefields of two schemas with overlapping properties if those properties areidentical.
func (Schema)GetAdditionalTypeDefs¶
func (sSchema) GetAdditionalTypeDefs() []TypeDefinition
func (Schema)IsExternalRef¶
typeSchemaDescriptor¶
type SchemaDescriptor struct {Fields []FieldDescriptorHasAdditionalPropertiesboolAdditionalPropertiesTypestring}
SchemaDescriptor describes a Schema, a type definition.
typeSecurityDefinition¶
funcDescribeSecurityDefinition¶
func DescribeSecurityDefinition(securityRequirementsopenapi3.SecurityRequirements) []SecurityDefinition
typeServerObjectDefinition¶added inv2.5.0
type ServerObjectDefinition struct {// GoName is the name of the variable for this Server URLGoNamestring// OAPISchema is the underlying OpenAPI representation of the ServerOAPISchema *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`
typeTypeDefinition¶
type TypeDefinition struct {// The name of the type, eg, type <...> PersonTypeNamestring// The name of the corresponding JSON description, as it will sometimes// differ due to invalid characters.JsonNamestring// This is the Schema wrapper is used to populate the type descriptionSchemaSchema}
TypeDefinition describes a Go type definition in generated code.
Let's use this example schema:components:
schemas: Person: type: object properties: name: type: string
funcGenerateParamsTypes¶
func GenerateParamsTypes(opOperationDefinition) []TypeDefinition
GenerateParamsTypes defines the schema for a parameters definition objectwhich encapsulates all the query, header and cookie parameters for an operation.
funcGenerateTypeDefsForOperation¶
func GenerateTypeDefsForOperation(opOperationDefinition) []TypeDefinition
funcGenerateTypesForParameters¶
func GenerateTypesForParameters(t *template.Template, params map[string]*openapi3.ParameterRef) ([]TypeDefinition,error)
GenerateTypesForParameters generates type definitions for any custom types defined in thecomponents/parameters section of the Swagger spec.
funcGenerateTypesForRequestBodies¶
func GenerateTypesForRequestBodies(t *template.Template, bodies map[string]*openapi3.RequestBodyRef) ([]TypeDefinition,error)
GenerateTypesForRequestBodies generates type definitions for any custom types defined in thecomponents/requestBodies section of the Swagger spec.
funcGenerateTypesForResponses¶
func GenerateTypesForResponses(t *template.Template, responsesopenapi3.ResponseBodies) ([]TypeDefinition,error)
GenerateTypesForResponses generates type definitions for any custom types defined in thecomponents/responses section of the Swagger spec.
funcGenerateTypesForSchemas¶
func GenerateTypesForSchemas(t *template.Template, schemas map[string]*openapi3.SchemaRef, excludeSchemas []string) ([]TypeDefinition,error)
GenerateTypesForSchemas generates type definitions for any custom types defined in thecomponents/schemas section of the Swagger spec.
func (*TypeDefinition)IsAlias¶
func (t *TypeDefinition) IsAlias()bool
typeUnionElement¶
type UnionElementstring
UnionElement describe union element, based on prefix externalRef\d+ and real ref name from external schema.
func (UnionElement)Method¶
func (uUnionElement) Method()string
Method generate union method name for template functions `As/From/Merge`.
func (UnionElement)String¶
func (uUnionElement) String()string
String returns externalRef\d+ and real ref name from external schema, like externalRef0.SomeType.