codegen

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: May 3, 2019 License: Apache-2.0 Imports: 14 Imported by: 23

Documentation

Overview

Copyright 2019 DeepMap, Inc.

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

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

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

Copyright 2019 DeepMap, Inc.

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

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

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

Copyright 2019 DeepMap, Inc.

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

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

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

Copyright 2019 DeepMap, Inc.

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

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

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

Index

Constants

This section is empty.

Variables

View Source
var TemplateFunctions = template.FuncMap{
	"genParamArgs":        genParamArgs,
	"genParamTypes":       genParamTypes,
	"genParamNames":       genParamNames,
	"genParamFmtString":   genParamFmtString,
	"swaggerUriToEchoUri": SwaggerUriToEchoUri,
	"lcFirst":             LowercaseFirstCharacter,
}

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

Functions

func GenFieldsFromSchemaDescriptors

func GenFieldsFromSchemaDescriptors(desc []SchemaDescriptor) []string

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

func GenStructFromAllOf

func GenStructFromAllOf(allOf []*openapi3.SchemaRef) (string, error)

This function 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.

func GenStructFromSchemaDescriptors

func GenStructFromSchemaDescriptors(desc []SchemaDescriptor) string

Given the list of schema descriptors above, generate a Go struct to represent a type, with one field per SchemaDescriptor

func GenerateClient added in v1.1.0

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

Uses the template engine to generate the function which registers our wrappers as Echo path handlers.

func GenerateImports

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

Generate our import statements and package definition.

func GenerateInlinedSpec added in v1.0.3

func GenerateInlinedSpec(t *template.Template, swagger *openapi3.Swagger) (string, error)

This generates a gzipped, base64 encoded JSON representation of the swagger definition, which we embed inside the generated code.

func GeneratePathHandlers

func GeneratePathHandlers(t *template.Template, swagger *openapi3.Swagger) (string, error)

This function generates all the go code for the ServerInterface as well as all the wrapper functions around our handlers.

func GenerateRegistration

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

Uses the template engine to generate the function which registers our wrappers as Echo path handlers.

func GenerateServer

func GenerateServer(swagger *openapi3.Swagger, packageName string) (string, error)

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

func GenerateServerInterface

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

Uses the template engine to generate the server interface

func GenerateTypes

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

Helper function to pass a bunch of types to the template engine, and buffer its output into a string.

func GenerateTypesForParameters

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

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

func GenerateTypesForResponses

func GenerateTypesForResponses(t *template.Template, responses openapi3.Responses) (string, error)

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

func GenerateTypesForRquestBodies

func GenerateTypesForRquestBodies(t *template.Template, bodies map[string]*openapi3.RequestBodyRef) (string, error)

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

func GenerateTypesForSchemas

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

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

func GenerateWrappers

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

Uses the template engine to generate all the wrappers which wrap our simple interface functions and perform marshallin/unmarshalling from HTTP request objects.

func LowercaseFirstCharacter

func LowercaseFirstCharacter(str string) string

Same as above, except lower case

func OrderedParamsFromUri added in v1.1.0

func OrderedParamsFromUri(uri string) []string

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

func RefPathToGoType

func RefPathToGoType(refPath string) (string, error)

This function 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 not yet supported URL components (http://deepmap.com/schemas/document.json#Foo) are not yet supported We only support flat components for now, so no components in a schema under components.

func ReplacePathParamsWithStr added in v1.1.0

func ReplacePathParamsWithStr(uri string) string

Replaces path parameters with %s

func SortedContentKeys

func SortedContentKeys(dict openapi3.Content) []string

This returns Content dictionary keys in sorted order

func SortedOperationsKeys

func SortedOperationsKeys(dict map[string]*openapi3.Operation) []string

This function returns Operation dictionary keys in sorted order

func SortedParameterKeys

func SortedParameterKeys(dict map[string]*openapi3.ParameterRef) []string

This returns sorted keys for a ParameterRef dict

func SortedPathsKeys

func SortedPathsKeys(dict openapi3.Paths) []string

This function is the same as above, except it sorts the keys for a Paths dictionary.

func SortedRequestBodyKeys

func SortedRequestBodyKeys(dict map[string]*openapi3.RequestBodyRef) []string

func SortedResponsesKeys

func SortedResponsesKeys(dict openapi3.Responses) []string

This function returns Responses dictionary keys in sorted order

func SortedSchemaKeys

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

This function returns the keys of the given SchemaRef dictionary in sorted order, since Golang scrambles dictionary keys

func StringInArray

func StringInArray(str string, array []string) bool

This function checks whether the specified string is present in an array of strings

func SwaggerUriToEchoUri

func SwaggerUriToEchoUri(uri string) string

This function converts a swagger style path URI with parameters to a Echo compatible path URI. We need to replace all of Swagger parameters with ":param". Valid input parameters are:

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

func ToCamelCase

func ToCamelCase(str string) string

This function will convert query-arg style strings to CamelCase. We will use (., -, _, ~, ' ') as valid delimiters for words. So, "word.word-word~word_word word" would be converted to WordWordWordWord

func UppercaseFirstCharacter

func UppercaseFirstCharacter(str string) string

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

Types

type OperationDefinition

type OperationDefinition struct {
	PathParams   []ParameterDefinition  // Parameters in the path, eg, /path/:param
	HeaderParams []ParameterDefinition  // Parameters in HTTP headers
	QueryParams  []ParameterDefinition  // Parameters in the query, /path?param
	CookieParams []ParameterDefinition  // Parameters in cookies
	OperationId  string                 // The operation_id description from Swagger, used to generate function names
	Body         *RequestBodyDefinition // The body of the request if it takes one
	Summary      string                 // Summary string from Swagger, used to generate a comment
	Method       string                 // GET, POST, DELETE, etc.
	Path         string                 // The Swagger path for the operation, like /resource/{id}
	Spec         *openapi3.Operation
}

This structure describes an Operation

func (*OperationDefinition) AllParams added in v1.0.5

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

Returns all parameters

func (*OperationDefinition) GenerateGenericForm added in v1.1.0

func (o *OperationDefinition) GenerateGenericForm() bool

This decides whether we need to generate the second, generic form of a function with a body implementation. This is described in the top level README.

func (*OperationDefinition) GetBodyDefinition

func (o *OperationDefinition) GetBodyDefinition() RequestBodyDefinition

Called by the template engine to get the body definition

func (*OperationDefinition) HasAnyBody added in v1.1.0

func (o *OperationDefinition) HasAnyBody() bool

This returns whether the operation has any kind of body specified

func (*OperationDefinition) HasBody

func (o *OperationDefinition) HasBody() bool

Called by template engine to determine whether to generate a body definition. This is true if the Operation has a body marshalled as application/json

func (*OperationDefinition) HasGenericBody added in v1.1.0

func (o *OperationDefinition) HasGenericBody() bool

This returns whether we have any non-json body

func (*OperationDefinition) Params

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

func (*OperationDefinition) RequiresParamObject

func (o *OperationDefinition) RequiresParamObject() bool

If we have parameters other than path parameters, they're bundled into an object. Returns true if we have any of those. This is used from the template engine.

type ParameterDefinition

type ParameterDefinition struct {
	ParamName string // The original json parameter name, eg param_name
	GoName    string // The Go friendly type name of above, ParamName
	TypeDef   string // The Go type definition of the parameter, "int" or "CustomType"
	Reference string // Swagger reference if present
	In        string // Where the parameter is defined - path, header, cookie, query
	Required  bool   // Is this a required parameter?
	Spec      *openapi3.Parameter
}

func DescribeParameters

func DescribeParameters(params openapi3.Parameters) ([]ParameterDefinition, error)

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

func FilterParameterDefinitionByType

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

This function returns the subset of the specified parameters which are of the specified type.

func SortParamsByPath added in v1.1.0

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

Reorders the given parameter definitions to match those in the path URI.

func (*ParameterDefinition) Explode added in v1.0.5

func (pd *ParameterDefinition) Explode() bool

func (*ParameterDefinition) IsJson added in v1.0.5

func (pd *ParameterDefinition) IsJson() bool

func (*ParameterDefinition) IsPassThrough added in v1.0.5

func (pd *ParameterDefinition) IsPassThrough() bool

func (*ParameterDefinition) IsStyled added in v1.0.5

func (pd *ParameterDefinition) IsStyled() bool

func (*ParameterDefinition) JsonTag

func (pd *ParameterDefinition) JsonTag() string

Generate 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 (*ParameterDefinition) Style added in v1.0.5

func (pd *ParameterDefinition) Style() string

type ParameterDefinitions added in v1.1.0

type ParameterDefinitions []ParameterDefinition

func (ParameterDefinitions) FindByName added in v1.1.0

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

type RequestBodyDefinition

type RequestBodyDefinition struct {
	TypeDef    string // The go type definition for the body
	Required   bool   // Is this body required, or optional?
	CustomType bool   // Is the type pre-defined, or defined inline?
}

This describes a request body

type SchemaDescriptor

type SchemaDescriptor struct {
	Required bool   // Is the schema required? If not, we'll pass by pointer
	GoType   string // The Go type needed to represent the json type.
	GoName   string // The Go compatible type name for the type
	JsonName string // The json type name for the type
	IsRef    bool   // Is this schema a reference to predefined object?
}

This describes a Schema, a type definition.

func DescribeSchemaProperties

func DescribeSchemaProperties(schema *openapi3.Schema) ([]SchemaDescriptor, error)

Walk the Properties field of the specified schema, generating SchemaDescriptors for each of them.

type TypeDefinition

type TypeDefinition struct {
	TypeName     string // The Go type name of an object
	JsonTypeName string // The corresponding JSON field name
	TypeDef      string // The Go type definition for the type
}

This structure is passed into our type generation code to give the templating system the context needed to produce our type definitions.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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