generator

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2015 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package generator provides the code generation library for go-swagger

The general idea is that you should rarely see interface{} in the generated code. You get a complete representation of a swagger document in somewhat idiomatic go.

To do so there is set of mapping patterns that are applied to a spec to go types:

defintion of primitive => type alias/name
defintion of array => type alias/name
definition of map => type alias/name
definition of object with properties => struct
definition of ref => type alias/name
object with only additional properties => map[string]T
object with additional properties and properties => custom serializer
schema with schema array in items => tuple (struct with properties, custom serializer)
schema with all of => struct
  * all of schema with ref => embedded value
  * all of schema with properties => properties are included in struct
  * adding an all of schema with just "x-isnullable": true or "x-nullable": true turns
  the schema into a pointer when there are only other extension properties provided

JSONSchema and by extension swagger allow for items that have a fixed size array with schema's describing the items at each index. This can be combined with additional items to form some kind of tuple with varargs. To map this to go it creates a struct that has fixed names and a custom json serializer.

The code that is generated also gets the doc comments that are used by the scanner to generate a spec from go code. So that after generation you should be able to reverse generate a spec from the code that was generated by your spec.

It should be equivalent to the original spec but might miss some default values and examples.

Index

Constants

This section is empty.

Variables

View Source
var FuncMap template.FuncMap = map[string]interface{}{
	"pascalize": func(arg string) string {
		if len(arg) == 0 || arg[0] > '9' {
			return swag.ToGoName(arg)
		}

		return swag.ToGoName("Nr " + arg)
	},
	"camelize":  swag.ToJSONName,
	"humanize":  swag.ToHumanNameLower,
	"snakize":   swag.ToFileName,
	"dasherize": swag.ToCommandName,
	"json":      asJSON,
	"hasInsecure": func(arg []string) bool {
		return swag.ContainsStringsCI(arg, "http") || swag.ContainsStringsCI(arg, "ws")
	},
	"hasSecure": func(arg []string) bool {
		return swag.ContainsStringsCI(arg, "https") || swag.ContainsStringsCI(arg, "wss")
	},
	"stripPackage": func(str, pkg string) string {
		return strings.TrimPrefix(str, pkg+".")
	},
	"dropPackage": func(str string) string {
		parts := strings.Split(str, ".")
		strlen := len(parts)
		if strlen > 0 {
			return parts[strlen-1]
		}
		return str
	},
	"upper": func(str string) string {
		return strings.ToUpper(str)
	},
}

FuncMap is a map with default functions for use n the templates. These are available in every template

Functions

func Asset

func Asset(name string) ([]byte, error)

Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetDir

func AssetDir(name string) ([]string, error)

AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:

data/
  foo.txt
  img/
    a.png
    b.png

then AssetDir("data") would return []string{"foo.txt", "img"} AssetDir("data/img") would return []string{"a.png", "b.png"} AssetDir("foo.txt") and AssetDir("notexist") would return an error AssetDir("") will return []string{"data"}.

func AssetInfo

func AssetInfo(name string) (os.FileInfo, error)

AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetNames

func AssetNames() []string

AssetNames returns the names of the assets.

func GenerateClient

func GenerateClient(name string, modelNames, operationIDs []string, opts GenOpts) error

GenerateClient generates a client library for a swagger spec document.

func GenerateDefinition

func GenerateDefinition(modelNames []string, includeModel, includeValidator bool, opts GenOpts) error

GenerateDefinition generates a model file for a schema defintion.

func GenerateServerOperation

func GenerateServerOperation(operationNames, tags []string, includeHandler, includeParameters, includeResponses bool, opts GenOpts) error

GenerateServerOperation generates a parameter model, parameter validator, http handler implementations for a given operation It also generates an operation handler interface that uses the parameter model for handling a valid request. Allows for specifying a list of tags to include only certain tags for the generation

func GenerateSupport

func GenerateSupport(name string, modelNames, operationIDs []string, opts GenOpts) error

GenerateSupport generates the supporting files for an API

func MustAsset

func MustAsset(name string) []byte

MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables.

func RestoreAsset

func RestoreAsset(dir, name string) error

RestoreAsset restores an asset under the given directory

func RestoreAssets

func RestoreAssets(dir, name string) error

RestoreAssets restores an asset under the given directory recursively

Types

type GenApp

type GenApp struct {
	Package             string
	ReceiverName        string
	Name                string
	Principal           string
	DefaultConsumes     string
	DefaultProduces     string
	Host                string
	BasePath            string
	Info                *spec.Info
	ExternalDocs        *spec.ExternalDocumentation
	Imports             map[string]string
	DefaultImports      []string
	Schemes             []string
	Consumes            []GenSerGroup
	Produces            []GenSerGroup
	SecurityDefinitions []GenSecurityScheme
	Models              []GenDefinition
	Operations          GenOperations
	OperationGroups     GenOperationGroups
	SwaggerJSON         string
}

GenApp represents all the meta data needed to generate an application from a swagger spec

type GenDefinition

type GenDefinition struct {
	GenSchema
	Package          string
	Imports          map[string]string
	DefaultImports   []string
	ExtraSchemas     []GenSchema
	DependsOn        []string
	IncludeValidator bool
}

GenDefinition contains all the properties to generate a defintion from a swagger spec

func (*GenDefinition) Zero

func (rt *GenDefinition) Zero() string

type GenHeader

type GenHeader struct {
	Package      string
	ReceiverName string

	Name string
	Path string

	Title       string
	Description string
	Default     interface{}

	Converter string
	Formatter string
	// contains filtered or unexported fields
}

GenHeader represents a header on a response for code generation

func (*GenHeader) Zero

func (rt *GenHeader) Zero() string

type GenHeaders

type GenHeaders []GenHeader

GenHeaders is a sorted collection of headers for codegen

func (GenHeaders) Len

func (g GenHeaders) Len() int

func (GenHeaders) Less

func (g GenHeaders) Less(i, j int) bool

func (GenHeaders) Swap

func (g GenHeaders) Swap(i, j int)

type GenItems

type GenItems struct {
	Name             string
	Path             string
	ValueExpression  string
	CollectionFormat string
	Child            *GenItems
	Parent           *GenItems
	Converter        string
	Formatter        string

	Location string
	// contains filtered or unexported fields
}

GenItems represents the collection items for a collection parameter

func (*GenItems) Zero

func (rt *GenItems) Zero() string

type GenOperation

type GenOperation struct {
	Package      string
	ReceiverName string
	Name         string
	Summary      string
	Description  string
	Method       string
	Path         string
	Tags         []string
	RootPackage  string

	Imports        map[string]string
	DefaultImports []string
	ExtraSchemas   []GenSchema

	Authorized bool
	Principal  string

	SuccessResponse *GenResponse
	Responses       map[int]GenResponse
	DefaultResponse *GenResponse

	Params         GenParameters
	QueryParams    GenParameters
	PathParams     GenParameters
	HeaderParams   GenParameters
	FormParams     GenParameters
	HasQueryParams bool
	HasFormParams  bool
	HasFileParams  bool

	Schemes []string
}

GenOperation represents an operation for code generation

type GenOperationGroup

type GenOperationGroup struct {
	Name       string
	Operations GenOperations

	Summary        string
	Description    string
	Imports        map[string]string
	DefaultImports []string
	RootPackage    string
}

GenOperationGroup represents a named (tagged) group of operations

type GenOperationGroups

type GenOperationGroups []GenOperationGroup

GenOperationGroups is a sorted collection of operation groups

func (GenOperationGroups) Len

func (g GenOperationGroups) Len() int

func (GenOperationGroups) Less

func (g GenOperationGroups) Less(i, j int) bool

func (GenOperationGroups) Swap

func (g GenOperationGroups) Swap(i, j int)

type GenOperations

type GenOperations []GenOperation

GenOperations represents a list of operations to generate this implements a sort by operation id

func (GenOperations) Len

func (g GenOperations) Len() int

func (GenOperations) Less

func (g GenOperations) Less(i, j int) bool

func (GenOperations) Swap

func (g GenOperations) Swap(i, j int)

type GenOpts

type GenOpts struct {
	Spec          string
	APIPackage    string
	ModelPackage  string
	ServerPackage string
	ClientPackage string
	Principal     string
	Target        string
	TypeMapping   map[string]string
	Imports       map[string]string
	DumpData      bool
	DefaultScheme string
}

GenOpts the options for the generator

type GenParameter

type GenParameter struct {
	Name            string
	ModelsPackage   string
	Path            string
	ValueExpression string
	IndexVar        string
	ReceiverName    string
	Location        string
	Title           string
	Description     string
	Converter       string
	Formatter       string

	Schema *GenSchema

	CollectionFormat string

	Child  *GenItems
	Parent *GenItems

	BodyParam *GenParameter

	Default         interface{}
	Enum            []interface{}
	ZeroValue       string
	AllowEmptyValue bool
	// contains filtered or unexported fields
}

GenParameter is used to represent a parameter or a header for code generation.

func (*GenParameter) IsBodyParam

func (g *GenParameter) IsBodyParam() bool

IsBodyParam returns true when this parameter is a body param

func (*GenParameter) IsFileParam

func (g *GenParameter) IsFileParam() bool

IsFileParam returns true when this parameter is a file param

func (*GenParameter) IsFormParam

func (g *GenParameter) IsFormParam() bool

IsFormParam returns true when this parameter is a form param

func (*GenParameter) IsHeaderParam

func (g *GenParameter) IsHeaderParam() bool

IsHeaderParam returns true when this parameter is a header param

func (*GenParameter) IsPathParam

func (g *GenParameter) IsPathParam() bool

IsPathParam returns true when this parameter is a path param

func (*GenParameter) IsQueryParam

func (g *GenParameter) IsQueryParam() bool

IsQueryParam returns true when this parameter is a query param

func (*GenParameter) Zero

func (rt *GenParameter) Zero() string

type GenParameters

type GenParameters []GenParameter

GenParameters represents a sorted parameter collection

func (GenParameters) Len

func (g GenParameters) Len() int

func (GenParameters) Less

func (g GenParameters) Less(i, j int) bool

func (GenParameters) Swap

func (g GenParameters) Swap(i, j int)

type GenResponse

type GenResponse struct {
	Package       string
	ModelsPackage string
	ReceiverName  string
	Name          string
	Description   string

	IsSuccess bool

	Code    int
	Method  string
	Path    string
	Headers GenHeaders
	Schema  *GenSchema

	Imports        map[string]string
	DefaultImports []string
}

GenResponse represents a response object for code generation

type GenSchema

type GenSchema struct {
	Example                 string
	Name                    string
	Suffix                  string
	Path                    string
	ValueExpression         string
	IndexVar                string
	KeyVar                  string
	Title                   string
	Description             string
	Location                string
	ReceiverName            string
	Items                   *GenSchema
	AllowsAdditionalItems   bool
	HasAdditionalItems      bool
	AdditionalItems         *GenSchema
	Object                  *GenSchema
	XMLName                 string
	Properties              GenSchemaList
	AllOf                   []GenSchema
	HasAdditionalProperties bool
	IsAdditionalProperties  bool
	AdditionalProperties    *GenSchema
	ReadOnly                bool
	IsVirtual               bool
	IsBaseType              bool
	HasBaseType             bool
	IsSubType               bool
	IsExported              bool
	DiscriminatorField      string
	DiscriminatorValue      string
	Discriminates           map[string]string
	Parents                 []string
	// contains filtered or unexported fields
}

GenSchema contains all the information needed to generate the code for a schema

func (*GenSchema) Zero

func (rt *GenSchema) Zero() string

type GenSchemaList

type GenSchemaList []GenSchema

GenSchemaList is a list of schemas for generation.

It can be sorted by name to get a stable struct layout for version control and such

func (GenSchemaList) Len

func (g GenSchemaList) Len() int

func (GenSchemaList) Less

func (g GenSchemaList) Less(i, j int) bool

func (GenSchemaList) Swap

func (g GenSchemaList) Swap(i, j int)

type GenSecurityScheme

type GenSecurityScheme struct {
	AppName      string
	ID           string
	Name         string
	ReceiverName string
	IsBasicAuth  bool
	IsAPIKeyAuth bool
	Source       string
	Principal    string
}

GenSecurityScheme represents a security scheme for code generation

type GenSerGroup

type GenSerGroup struct {
	ReceiverName   string
	AppName        string
	Name           string
	MediaType      string
	Implementation string
	AllSerializers []GenSerializer
}

GenSerGroup represents a group of serializers, most likely this is a media type to a list of prioritized serializers.

type GenSerializer

type GenSerializer struct {
	ReceiverName   string
	AppName        string
	Name           string
	MediaType      string
	Implementation string
}

GenSerializer represents a single serializer for a particular media type

Jump to

Keyboard shortcuts

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