codegen package - github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen - Go Packages
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.
- Constants
- 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 any) (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 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
- type AdditionalImport
- type CompatibilityOptions
- type ComponentType
- type Configuration
- type Constants
- type Discriminator
- type EnumDefinition
- type FieldDescriptor
- type FormatMapping
- 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) RequiresNilCheck() bool
- func (pd *ParameterDefinition) SchemaFormat() string
- func (pd *ParameterDefinition) SchemaType() string
- func (pd *ParameterDefinition) Style() string
- func (pd ParameterDefinition) TypeDef() string
- func (pd ParameterDefinition) ZeroValueIsNil() bool
- 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 SimpleTypeSpec
- type TypeDefinition
- func FixDuplicateTypeNames(typeDefs []TypeDefinition) []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 TypeMapping
- type UnionElement
const ( ComponentTypeSchema = iota ComponentTypeParameter ComponentTypeRequestBody ComponentTypeResponse )
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"}, "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.
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, "toGoString": StringToGoString, "toGoComment": StringWithTypeNameToGoComment, "genServerURLWithVariablesFunctionParams": genServerURLWithVariablesFunctionParams, }
TemplateFunctions is passed to the template engine, and we can call each function here by keyName from the template code.
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.
GenFieldsFromProperties produce corresponding field names with JSON annotations, given a list of schema descriptors
GenStructFromAllOf generates an object that is the union of the objects in the input array. In the case of Ref objects, we use an embedded struct, otherwise, we inline the fields.
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
GenerateAdditionalPropertyBoilerplate generates all the glue code which provides the API for interacting with additional properties and JSON-ification
func GenerateBodyDefinitions ¶
GenerateBodyDefinitions turns the Swagger body definitions into a list of our body definitions which will be used for code generation.
GenerateChiServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateClient uses the template engine to generate the function which registers our wrappers as Echo path handlers.
GenerateClientWithResponses generates a client which extends the basic client which does response unmarshaling.
GenerateConstants generates operation ids, context keys, paths, etc. to be exported as constants
GenerateEchoServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateFiberServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateGinServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateGorillaServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateImports generates our import statements and package definition.
GenerateInlinedSpec generates a gzipped, base64 encoded JSON representation of the swagger definition, which we embed inside the generated code.
GenerateIrisServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateStdHTTPServer generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.
GenerateTemplates used to generate templates
GenerateTypes passes a bunch of types to the template engine, and buffers its output into a string.
GenerateTypesForOperations generates code for all types produced within operations
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.
IsGoKeyword returns whether the given string is a go keyword
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.
IsValidGoIdentity checks if the given string can be used as a name of variable, constant, or type.
LoadTemplates loads all of our template files into a text/template. The path of template is relative to the templates directory.
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.
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 MergeImports(dst, src map[string]goImport)
OrderedParamsFromUri returns the argument names, in order, in a given URI string, so for /path/{param1}/{.param2*}/{?param3}, it would return param1, param2, param3
PathToTypeName converts a path, like Object/field1/nestedField into a go type name.
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.
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.
ReplacePathParamsWithStr replaces path parameters of the form {param} with %s
SanitizeCode runs sanitizers across the generated Go code to ensure the generated code will be able to compile.
SanitizeEnumNames fixes illegal chars in the enum names and removes duplicates
SanitizeGoIdentity deletes and replaces the illegal runes in the given string to use the string as a valid identity.
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.
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
SortedMapKeys takes a map with keys of type string and returns a slice of those keys sorted lexicographically.
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.
StringInArray checks whether the specified string is present in an array of strings
StringToGoComment renders a possible multi-line string as a valid Go-Comment. Each line is prefixed as a comment.
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\""`
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.
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*}
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*}
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*}
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*}
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*}
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*}
SwaggerUriToStdHttpUri 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*}
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
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
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.
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.
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.
type AdditionalImport struct {
Alias string `yaml:"alias,omitempty"`
Package string `yaml:"package"`
}
type CompatibilityOptions struct {
OldMergeSchemas bool `yaml:"old-merge-schemas,omitempty"`
OldEnumConflicts bool `yaml:"old-enum-conflicts,omitempty"`
OldAliasing bool `yaml:"old-aliasing,omitempty"`
DisableFlattenAdditionalProperties bool `yaml:"disable-flatten-additional-properties,omitempty"`
DisableRequiredReadOnlyAsPointer bool `yaml:"disable-required-readonly-as-pointer,omitempty"`
AlwaysPrefixEnumValues bool `yaml:"always-prefix-enum-values,omitempty"`
ApplyChiMiddlewareFirstToLast bool `yaml:"apply-chi-middleware-first-to-last,omitempty"`
ApplyGorillaMiddlewareFirstToLast bool `yaml:"apply-gorilla-middleware-first-to-last,omitempty"`
CircularReferenceLimit int `yaml:"circular-reference-limit"`
AllowUnexportedStructFieldNames bool `yaml:"allow-unexported-struct-field-names"`
PreserveOriginalOperationIdCasingInEmbeddedSpec bool `yaml:"preserve-original-operation-id-casing-in-embedded-spec"`
}
CompatibilityOptions specifies backward compatibility settings for the code generator.
ComponentType is used to keep track of where a given schema came from, in order to perform type name collision resolution.
type Configuration struct {
PackageName string `yaml:"package"`
Generate GenerateOptions `yaml:"generate,omitempty"`
Compatibility CompatibilityOptions `yaml:"compatibility,omitempty"`
OutputOptions OutputOptions `yaml:"output-options,omitempty"`
ImportMapping map[string]string `yaml:"import-mapping,omitempty"`
AdditionalImports []AdditionalImport `yaml:"additional-imports,omitempty"`
NoVCSVersionOverride *string `yaml:"-"`
}
Configuration defines code generation customizations
func (o Configuration) UpdateDefaults() Configuration
UpdateDefaults sets reasonable default values for unset fields in Configuration
Validate checks whether Configuration represent a valid configuration
type Constants struct {
SecuritySchemeProviderNames []string
EnumDefinitions []EnumDefinition
}
type EnumDefinition struct {
Schema Schema
TypeName string
ValueWrapper string
PrefixTypeName bool
}
EnumDefinition holds type information for enum
GetValues generates enum names in a way to minimize global conflicts
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.
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 GenerateOptions struct {
IrisServer bool `yaml:"iris-server,omitempty"`
ChiServer bool `yaml:"chi-server,omitempty"`
FiberServer bool `yaml:"fiber-server,omitempty"`
EchoServer bool `yaml:"echo-server,omitempty"`
GinServer bool `yaml:"gin-server,omitempty"`
GorillaServer bool `yaml:"gorilla-server,omitempty"`
StdHTTPServer bool `yaml:"std-http-server,omitempty"`
Strict bool `yaml:"strict-server,omitempty"`
Client bool `yaml:"client,omitempty"`
Models bool `yaml:"models,omitempty"`
EmbeddedSpec bool `yaml:"embedded-spec,omitempty"`
ServerURLs bool `yaml:"server-urls,omitempty"`
}
GenerateOptions specifies which supported output formats to generate.
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 NameNormalizerFunction = "" NameNormalizerFunctionToCamelCase NameNormalizerFunction = "ToCamelCase" NameNormalizerFunctionToCamelCaseWithDigits NameNormalizerFunction = "ToCamelCaseWithDigits" NameNormalizerFunctionToCamelCaseWithInitialisms NameNormalizerFunction = "ToCamelCaseWithInitialisms" )
type NameNormalizerMap map[NameNormalizerFunction]NameNormalizer
OperationDefinition describes an Operation
OperationDefinitions returns all operations for a swagger definition.
func (o *OperationDefinition) AllParams() []ParameterDefinition
AllParams returns all parameters
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) HasBody ¶
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) 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.
SummaryAsComment returns the Operations summary as a multi line comment
type OutputOptions struct {
SkipFmt bool `yaml:"skip-fmt,omitempty"`
SkipPrune bool `yaml:"skip-prune,omitempty"`
IncludeTags []string `yaml:"include-tags,omitempty"`
ExcludeTags []string `yaml:"exclude-tags,omitempty"`
IncludeOperationIDs []string `yaml:"include-operation-ids,omitempty"`
ExcludeOperationIDs []string `yaml:"exclude-operation-ids,omitempty"`
UserTemplates map[string]string `yaml:"user-templates,omitempty"`
ExcludeSchemas []string `yaml:"exclude-schemas,omitempty"`
ResponseTypeSuffix string `yaml:"response-type-suffix,omitempty"`
ClientTypeName string `yaml:"client-type-name,omitempty"`
InitialismOverrides bool `yaml:"initialism-overrides,omitempty"`
AdditionalInitialisms []string `yaml:"additional-initialisms,omitempty"`
NullableType bool `yaml:"nullable-type,omitempty"`
DisableTypeAliasesForType []string `yaml:"disable-type-aliases-for-type"`
NameNormalizer string `yaml:"name-normalizer,omitempty"`
Overlay OutputOptionsOverlay `yaml:"overlay"`
EnableYamlTags bool `yaml:"yaml-tags,omitempty"`
ClientResponseBytesFunction bool `yaml:"client-response-bytes-function,omitempty"`
PreferSkipOptionalPointer bool `yaml:"prefer-skip-optional-pointer,omitempty"`
PreferSkipOptionalPointerWithOmitzero bool `yaml:"prefer-skip-optional-pointer-with-omitzero,omitempty"`
PreferSkipOptionalPointerOnContainerTypes bool `yaml:"prefer-skip-optional-pointer-on-container-types,omitempty"`
ResolveTypeNameCollisions bool `yaml:"resolve-type-name-collisions,omitempty"`
TypeMapping *TypeMapping `yaml:"type-mapping,omitempty"`
}
OutputOptions are used to modify the output code in some way.
type OutputOptionsOverlay struct {
Path string `yaml:"path"`
Strict *bool `yaml:"strict,omitempty"`
}
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
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.
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 (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 (pd ParameterDefinition) IndirectOptional() bool
Deprecated: Use HasOptionalPointer, as it is clearer what the intent is.
func (pd *ParameterDefinition) IsPassThrough() bool
JsonTag generates the JSON annotation to map GoType to json type name. If Parameter Foo is marshaled to json as "foo", this will create the annotation 'json:"foo"'
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`
SchemaFormat returns the OpenAPI format string for this parameter's schema (e.g. "byte", "date-time"), or empty string if unavailable.
SchemaType returns the first OpenAPI type string for this parameter's schema (e.g. "string", "integer"), or empty string if unavailable.
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 (pd ParameterDefinition) ZeroValueIsNil() bool
ZeroValueIsNil is a helper function to determine if the given Go type used for this property Will return true if the OpenAPI `type` is: - `array`
type ParameterDefinitions []ParameterDefinition
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.
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`
type RequestBodyDefinition ¶
RequestBodyDefinition describes a request body
func (RequestBodyDefinition) CustomType ¶
CustomType returns whether the body is a custom inline type, or pre-defined. This is poorly named, but it's here for compatibility reasons post-refactoring TODO: clean up the templates code, it can be simpler.
func (RequestBodyDefinition) IsFixedContentType ¶
func (r RequestBodyDefinition) IsFixedContentType() bool
IsFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (RequestBodyDefinition) IsJSON ¶
IsJSON returns whether this is a JSON media type, for instance: - application/json - application/vnd.api+json - application/*+json
func (RequestBodyDefinition) IsSupported ¶
IsSupported returns true if we support this content type for server. Otherwise io.Reader will be generated
func (RequestBodyDefinition) IsSupportedByClient ¶
func (r RequestBodyDefinition) IsSupportedByClient() bool
IsSupportedByClient returns true if we support this content type for client. Otherwise only generic method will ge generated
type ResponseContentDefinition ¶
func (ResponseContentDefinition) HasFixedContentType ¶
func (r ResponseContentDefinition) HasFixedContentType() bool
HasFixedContentType returns true if content type has fixed content type, i.e. contains no "*" symbol
func (r ResponseDefinition) HasFixedStatusCode() bool
func (r ResponseDefinition) IsExternalRef() bool
type ResponseHeaderDefinition struct {
}
type ResponseTypeDefinition struct {
TypeDefinition
ContentTypeName string
ResponseName string
AdditionalTypeDefinitions []TypeDefinition
}
ResponseTypeDefinition is an extension of TypeDefinition, specifically for response unmarshaling in ClientWithResponses.
type Schema struct {
GoType string
RefType string
ArrayType *Schema
EnumValues map[string]string
Properties []Property
HasAdditionalProperties bool
AdditionalPropertiesType *Schema
AdditionalTypes []TypeDefinition
SkipOptionalPointer bool
Description string
UnionElements []UnionElement
Discriminator *Discriminator
DefineViaAlias bool
OAPISchema *openapi3.Schema
DefinedComp ComponentType
}
Schema describes an OpenAPI schema, with lots of helper fields to use in the templating engine.
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.
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) GetAdditionalTypeDefs() []TypeDefinition
type SchemaDescriptor struct {
Fields []FieldDescriptor
HasAdditionalProperties bool
AdditionalPropertiesType string
}
SchemaDescriptor describes a Schema, a type definition.
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.
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 FixDuplicateTypeNames(typeDefs []TypeDefinition) []TypeDefinition
FixDuplicateTypeNames renames duplicate type names.
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
GenerateTypesForParameters generates type definitions for any custom types defined in the components/parameters section of the Swagger spec.
GenerateTypesForRequestBodies generates type definitions for any custom types defined in the components/requestBodies section of the Swagger spec.
GenerateTypesForResponses generates type definitions for any custom types defined in the components/responses section of the Swagger spec.
GenerateTypesForSchemas generates type definitions for any custom types defined in the components/schemas section of the Swagger spec.
type TypeMapping struct {
Integer FormatMapping `yaml:"integer,omitempty" json:"integer,omitempty"`
Number FormatMapping `yaml:"number,omitempty" json:"number,omitempty"`
Boolean FormatMapping `yaml:"boolean,omitempty" json:"boolean,omitempty"`
String FormatMapping `yaml:"string,omitempty" json:"string,omitempty"`
}
TypeMapping defines the mapping from OpenAPI types to Go types.
func (base TypeMapping) Merge(user TypeMapping) TypeMapping
Merge returns a new TypeMapping with user overrides applied on top of base.
UnionElement describe union element, based on prefix externalRef\d+ and real ref name from external schema.
Method generate union method name for template functions `As/From/Merge`.
String returns externalRef\d+ and real ref name from external schema, like externalRef0.SomeType.