Documentation
¶
Overview ¶
Package swgen (Swagger Generator) is a library which helps to generate [Swagger Specification](http://swagger.io/specification/) in JSON format on-the-fly.
Index ¶
- Constants
- func GenDocument() ([]byte, error)
- func ReflectTypeHash(t reflect.Type) uint32
- func ReflectTypeReliableName(t reflect.Type) string
- func ResetDefinitions()
- func ResetPaths()
- func ServeHTTP(w http.ResponseWriter, r *http.Request)
- func SetPathItem(info PathItemInfo, params interface{}, body interface{}, response interface{}) error
- type ContactObj
- type Definition
- type Document
- type Enum
- type Generator
- func AddExtendedField(name string, value interface{}) *Generator
- func AddTypeMap(src interface{}, dst interface{}) *Generator
- func EnableCORS(b bool, allowHeaders ...string) *Generator
- func NewGenerator() *Generator
- func SetBasePath(basePath string) *Generator
- func SetContact(name, url, email string) *Generator
- func SetHost(host string) *Generator
- func SetInfo(title, description, term, version string) *Generator
- func SetLicense(name, url string) *Generator
- func (g *Generator) AddExtendedField(name string, value interface{}) *Generator
- func (g *Generator) AddSecurityDefinition(name string, def SecurityDef) *Generator
- func (g *Generator) AddTypeMap(src interface{}, dst interface{}) *Generator
- func (g *Generator) EnableCORS(b bool, allowHeaders ...string) *Generator
- func (g *Generator) GenDocument() ([]byte, error)
- func (g *Generator) IndentJSON(enabled bool) *Generator
- func (g *Generator) ParseDefinition(i interface{}) (schema SchemaObj, err error)
- func (g *Generator) ParseParameter(i interface{}) (name string, params []ParamObj, err error)
- func (g *Generator) ReflectGoTypes(enabled bool) *Generator
- func (g *Generator) ResetDefinitions()
- func (g *Generator) ResetPaths()
- func (g *Generator) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (g *Generator) SetBasePath(basePath string) *Generator
- func (g *Generator) SetContact(name, url, email string) *Generator
- func (g *Generator) SetHost(host string) *Generator
- func (g *Generator) SetInfo(title, description, term, version string) *Generator
- func (g *Generator) SetLicense(name, url string) *Generator
- func (g *Generator) SetPathItem(info PathItemInfo, params interface{}, body interface{}, response interface{}) error
- func (g *Generator) SetSchemes(schemes []string) *Generator
- type IDefinition
- type IParameter
- type InfoObj
- type LicenseObj
- type OperationObj
- type ParamItemObj
- type ParamObj
- type PathItem
- type PathItemInfo
- type ResponseObj
- type Responses
- type SchemaObj
- type SecurityDef
- type ServiceType
Examples ¶
Constants ¶
const ( // CommonNameInteger data type is integer, format int32 (signed 32 bits) CommonNameInteger commonName = "integer" // CommonNameLong data type is integer, format int64 (signed 64 bits) CommonNameLong commonName = "long" // CommonNameFloat data type is number, format float CommonNameFloat commonName = "float" // CommonNameDouble data type is number, format double CommonNameDouble commonName = "double" // CommonNameString data type is string CommonNameString commonName = "string" // CommonNameByte data type is string, format byte (base64 encoded characters) CommonNameByte commonName = "byte" // CommonNameBinary data type is string, format binary (any sequence of octets) CommonNameBinary commonName = "binary" // CommonNameBoolean data type is boolean CommonNameBoolean commonName = "boolean" // CommonNameDate data type is string, format date (As defined by full-date - RFC3339) CommonNameDate commonName = "date" // CommonNameDateTime data type is string, format date-time (As defined by date-time - RFC3339) CommonNameDateTime commonName = "dateTime" // CommonNamePassword data type is string, format password CommonNamePassword commonName = "password" )
const ( // SecurityBasicAuth is a HTTP Basic Authentication security type SecurityBasicAuth securityType = "basic" // SecurityAPIKey is an API key security type SecurityAPIKey securityType = "apiKey" // SecurityOAuth2 is an OAuth2 security type SecurityOAuth2 securityType = "oauth2" // SecurityHTTP is an http security type SecurityHTTP securityType = "http" )
const ( // APIKeyInHeader defines API key in header APIKeyInHeader apiKeyIn = "header" // APIKeyInQuery defines API key in query parameter APIKeyInQuery apiKeyIn = "query" )
const ( // Oauth2AccessCode is access code Oauth2 flow Oauth2AccessCode oauthFlow = "accessCode" // Oauth2Application is application Oauth2 flow Oauth2Application oauthFlow = "application" // Oauth2Implicit is implicit Oauth2 flow Oauth2Implicit oauthFlow = "implicit" // Oauth2Password is password Oauth2 flow Oauth2Password oauthFlow = "password" )
const ( AuthenticationSchemeBasic authenticationScheme = "basic" AuthenticationSchemeBearer authenticationScheme = "bearer" AuthenticationSchemeDigest authenticationScheme = "digest" AuthenticationSchemeHOBA authenticationScheme = "hoba" )
const (
BearerFormatJWT bearerFormat = "JWT"
)
Variables ¶
This section is empty.
Functions ¶
func GenDocument ¶
GenDocument returns document specification in JSON string (in []byte)
func ReflectTypeHash ¶ added in v0.3.0
ReflectTypeHash returns private (unexported) `hash` field of the Golang internal reflect.rtype struct for a given reflect.Type This hash is used to (quasi-)uniquely identify a reflect.Type value
func ReflectTypeReliableName ¶ added in v0.3.0
ReflectTypeReliableName returns real name of given reflect.Type, if it is non-empty, or auto-generates "anon_*"] name for anonymous structs
func ResetDefinitions ¶
func ResetDefinitions()
ResetDefinitions will remove all exists definitions and init again
func ServeHTTP ¶
func ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.HandleFunc to server swagger.json document
func SetPathItem ¶
func SetPathItem(info PathItemInfo, params interface{}, body interface{}, response interface{}) error
SetPathItem register path item with some information and input, output
Types ¶
type ContactObj ¶
type ContactObj struct {
Name string `json:"name"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
ContactObj contains contact information for the exposed API
type Definition ¶ added in v0.2.0
Definition is a helper that implements interface IDefinition
func (Definition) SwgenDefinition ¶ added in v0.2.0
func (s Definition) SwgenDefinition() (typeName string, typeDef SchemaObj, err error)
SwgenDefinition return type name and definition that was set
type Document ¶
type Document struct {
Version string `json:"swagger"` // Specifies the Swagger Specification version being used
Info InfoObj `json:"info"` // Provides metadata about the API
Host string `json:"host,omitempty"` // The host (name or ip) serving the API
BasePath string `json:"basePath,omitempty"` // The base path on which the API is served, which is relative to the host
Schemes []string `json:"schemes,omitempty"` // Values MUST be from the list: "http", "https", "ws", "wss"
Paths map[string]PathItem `json:"paths"` // The available paths and operations for the API
Definitions map[string]SchemaObj `json:"definitions"` // An object to hold data types produced and consumed by operations
SecurityDefinitions map[string]SecurityDef `json:"securityDefinitions,omitempty"` // An object to hold available security mechanisms
// contains filtered or unexported fields
}
Document represent for a document object of swagger data see http://swagger.io/specification/
func (*Document) AddExtendedField ¶
func (ad *Document) AddExtendedField(name string, value interface{})
AddExtendedField add field to additional data map
func (Document) MarshalJSON ¶
MarshalJSON marshal Document with additionalData inlined
type Enum ¶
type Enum struct {
Enum []interface{} `json:"enum,omitempty"`
EnumNames []string `json:"x-enum-names,omitempty"`
}
Enum can be use for sending Enum data that need validate
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator create swagger document
func AddExtendedField ¶ added in v0.2.0
AddExtendedField add vendor extension field to document
func AddTypeMap ¶
func AddTypeMap(src interface{}, dst interface{}) *Generator
AddTypeMap add rule to use dst interface instead of src
func EnableCORS ¶ added in v0.2.0
EnableCORS enable HTTP handler support CORS
func SetBasePath ¶
SetBasePath set host info for swagger specification
func SetContact ¶
SetContact set contact information for API
func SetLicense ¶
SetLicense set license information for API
func (*Generator) AddExtendedField ¶ added in v0.2.0
AddExtendedField add vendor extension field to document
func (*Generator) AddSecurityDefinition ¶ added in v0.3.0
func (g *Generator) AddSecurityDefinition(name string, def SecurityDef) *Generator
AddSecurityDefinition adds shared security definition to document
func (*Generator) AddTypeMap ¶
AddTypeMap add rule to use dst interface instead of src
func (*Generator) EnableCORS ¶ added in v0.2.0
EnableCORS enable HTTP handler support CORS
func (*Generator) GenDocument ¶
GenDocument returns document specification in JSON string (in []byte)
Example ¶
package main
import (
"fmt"
"github.com/halfi/swgen"
)
func main() {
// PetsRequest defines all params for /pets request
type Pets struct {
Pet string `schema:"pet" in:"query" required:"-" description:"pet"`
}
type PetsRequest struct {
Tags []string `schema:"tags" in:"query" required:"-" description:"tags to filter by"`
Limit int32 `schema:"limit" in:"query" required:"-" description:"maximum number of results to return"`
Pets
}
// Pet contains information of a pet
type Pet struct {
ID int64 `json:"id"`
Name string `json:"name"`
Tag string `json:"tag"`
}
gen := swgen.NewGenerator()
gen.SetHost("petstore.swagger.io").SetBasePath("/api")
gen.SetInfo("Swagger Petstore (Simple)", "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "http://helloreverb.com/terms/", "2.0")
gen.SetLicense("MIT", "http://opensource.org/licenses/MIT")
gen.SetContact("Swagger API team", "http://swagger.io", "foo@example.com")
gen.AddSecurityDefinition("BasicAuth", swgen.SecurityDef{Type: swgen.SecurityBasicAuth})
pathInf := swgen.PathItemInfo{
Path: "/pets",
Method: "GET",
Title: "findPets",
Description: "Returns all pets from the system that the user has access to",
Tag: "v1",
Deprecated: false,
Security: []string{"BasicAuth"},
}
pathInf.AddExtendedField("x-example", "example")
gen.SetPathItem(
pathInf,
PetsRequest{}, // request object
nil, // body data if any
[]Pet{}, // response object
)
// extended field
gen.AddExtendedField("x-uppercase-version", true)
docData, _ := gen.GenDocument()
fmt.Println(string(docData))
}
Output: {"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"2.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http","https"],"paths":{"/pets":{"get":{"tags":["v1"],"summary":"findPets","description":"Returns all pets from the system that the user has access to","parameters":[{"name":"tags","in":"query","type":"array","items":{"type":"string"},"collectionFormat":"multi","description":"tags to filter by"},{"name":"limit","in":"query","type":"integer","format":"int32","description":"maximum number of results to return"}],"responses":{"200":{"description":"request success","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}}},"security":[{"BasicAuth":[]}],"x-example":"example"}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"securityDefinitions":{"BasicAuth":{"type":"basic"}},"x-uppercase-version":true}
Example (Jsonrpc) ¶
package main
import (
"fmt"
"github.com/halfi/swgen"
)
func main() {
const (
// XServiceType is a swagger vendor extension
XServiceType = `x-service-type`
// XAttachVersionToHead is a swagger vendor extension
XAttachVersionToHead = `x-attach-version-to-head`
)
// Pet contains information of a pet
type Pet struct {
ID int64 `json:"id"`
Name string `json:"name"`
Tag string `json:"tag"`
}
gen := swgen.NewGenerator()
gen.SetHost("petstore.swagger.io")
gen.SetBasePath("/rpc") // set JSON-RPC path
gen.SetInfo("Swagger Petstore (Simple)", "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "http://helloreverb.com/terms/", "2.0")
gen.SetLicense("MIT", "http://opensource.org/licenses/MIT")
gen.SetContact("Swagger API team", "http://swagger.io", "foo@example.com")
// set service type is JSON-RPC
gen.AddExtendedField(XServiceType, swgen.ServiceTypeJSONRPC)
gen.AddExtendedField(XAttachVersionToHead, false)
pathInf := swgen.PathItemInfo{
Path: "addPet", // in JSON-RPC, use name of method for Path
Method: "POST",
Title: "Add new Pet",
Description: "Add a new pet to the store",
Tag: "v1",
Deprecated: false,
}
gen.SetPathItem(
pathInf,
nil, // request object
Pet{}, // body data if any
Pet{}, // response object
)
docData, _ := gen.GenDocument()
fmt.Println(string(docData))
}
Output: {"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"2.0"},"host":"petstore.swagger.io","basePath":"/rpc","schemes":["http","https"],"paths":{"addPet":{"post":{"tags":["v1"],"summary":"Add new Pet","description":"Add a new pet to the store","parameters":[{"name":"body","in":"body","schema":{"$ref":"#/definitions/Pet"},"required":true}],"responses":{"200":{"description":"request success","schema":{"$ref":"#/definitions/Pet"}}}}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"x-attach-version-to-head":false,"x-service-type":"json-rpc"}
func (*Generator) IndentJSON ¶ added in v0.2.0
IndentJSON controls JSON indentation
func (*Generator) ParseDefinition ¶
ParseDefinition create a DefObj from input object, it should be a non-nil pointer to anything it reuse schema/json tag for property name.
func (*Generator) ParseParameter ¶
ParseParameter parse input struct to swagger parameter object
func (*Generator) ReflectGoTypes ¶ added in v0.2.0
ReflectGoTypes controls JSON indentation
func (*Generator) ResetDefinitions ¶
func (g *Generator) ResetDefinitions()
ResetDefinitions will remove all exists definitions and init again
func (*Generator) ServeHTTP ¶
func (g *Generator) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler to server swagger.json document
func (*Generator) SetBasePath ¶
SetBasePath set host info for swagger specification
func (*Generator) SetContact ¶
SetContact set contact information for API
func (*Generator) SetLicense ¶
SetLicense set license information for API
func (*Generator) SetPathItem ¶
func (g *Generator) SetPathItem(info PathItemInfo, params interface{}, body interface{}, response interface{}) error
SetPathItem register path item with some information and input, output
func (*Generator) SetSchemes ¶ added in v0.4.5
SetSchemes set schemes
type IDefinition ¶
IDefinition allows to return custom definitions
type IParameter ¶
IParameter allows to return custom parameters
type InfoObj ¶
type InfoObj struct {
Title string `json:"title"` // The title of the application
Description string `json:"description"`
TermsOfService string `json:"termsOfService"`
Contact ContactObj `json:"contact"`
License LicenseObj `json:"license"`
Version string `json:"version"`
}
InfoObj provides metadata about the API
type LicenseObj ¶
LicenseObj license information for the exposed API
type OperationObj ¶
type OperationObj struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary"` // like a title, a short summary of what the operation does (120 chars)
Description string `json:"description"` // A verbose explanation of the operation behavior
Parameters []ParamObj `json:"parameters,omitempty"`
Responses Responses `json:"responses"`
Security []map[string][]string `json:"security,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
// contains filtered or unexported fields
}
OperationObj describes a single API operation on a path see http://swagger.io/specification/#operationObject
func (*OperationObj) AddExtendedField ¶
func (ad *OperationObj) AddExtendedField(name string, value interface{})
AddExtendedField add field to additional data map
func (OperationObj) MarshalJSON ¶
func (o OperationObj) MarshalJSON() ([]byte, error)
MarshalJSON marshal OperationObj with additionalData inlined
type ParamItemObj ¶
type ParamItemObj struct {
Ref string `json:"$ref,omitempty"`
Type string `json:"type"`
Format string `json:"format,omitempty"`
Items *ParamItemObj `json:"items,omitempty"` // Required if type is "array"
CollectionFormat string `json:"collectionFormat,omitempty"` // "multi" - this is valid only for parameters in "query" or "formData"
}
ParamItemObj describes an property object, in param object or property of definition see http://swagger.io/specification/#itemsObject
type ParamObj ¶
type ParamObj struct {
Ref string `json:"$ref,omitempty"`
Name string `json:"name"`
In string `json:"in"` // Possible values are "query", "header", "path", "formData" or "body"
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Items *ParamItemObj `json:"items,omitempty"` // Required if type is "array"
Schema *SchemaObj `json:"schema,omitempty"` // Required if type is "body"
CollectionFormat string `json:"collectionFormat,omitempty"` // "multi" - this is valid only for parameters in "query" or "formData"
Description string `json:"description,omitempty"`
Default interface{} `json:"default,omitempty"`
Required bool `json:"required,omitempty"`
Enum
// contains filtered or unexported fields
}
ParamObj describes a single operation parameter see http://swagger.io/specification/#parameterObject
func ParseParameter ¶
ParseParameter parse input struct to swagger parameter object
func (*ParamObj) AddExtendedField ¶ added in v0.2.0
func (ad *ParamObj) AddExtendedField(name string, value interface{})
AddExtendedField add field to additional data map
func (ParamObj) MarshalJSON ¶ added in v0.2.0
MarshalJSON marshal OperationObj with additionalData inlined
type PathItem ¶
type PathItem struct {
Ref string `json:"$ref,omitempty"`
Get *OperationObj `json:"get,omitempty"`
Put *OperationObj `json:"put,omitempty"`
Post *OperationObj `json:"post,omitempty"`
Delete *OperationObj `json:"delete,omitempty"`
Options *OperationObj `json:"options,omitempty"`
Head *OperationObj `json:"head,omitempty"`
Patch *OperationObj `json:"patch,omitempty"`
Params *ParamObj `json:"parameters,omitempty"`
}
PathItem describes the operations available on a single path see http://swagger.io/specification/#pathItemObject
type PathItemInfo ¶
type PathItemInfo struct {
Path string
Method string
Title string
Description string
Tag string
Deprecated bool
Security []string // Names of security definitions
SecurityOAuth2 map[string][]string // Map of names of security definitions to required scopes
// contains filtered or unexported fields
}
PathItemInfo some basic information of a path item and operation object
func (*PathItemInfo) AddExtendedField ¶
func (ad *PathItemInfo) AddExtendedField(name string, value interface{})
AddExtendedField add field to additional data map
type ResponseObj ¶
type ResponseObj struct {
Ref string `json:"$ref,omitempty"`
Description string `json:"description,omitempty"`
Schema *SchemaObj `json:"schema,omitempty"`
Headers interface{} `json:"headers,omitempty"`
Examples interface{} `json:"examples,omitempty"`
}
ResponseObj describes a single response from an API Operation
type SchemaObj ¶
type SchemaObj struct {
Ref string `json:"$ref,omitempty"`
Description string `json:"description,omitempty"`
Default interface{} `json:"default,omitempty"`
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Title string `json:"title,omitempty"`
Items *SchemaObj `json:"items,omitempty"` // if type is array
AdditionalProperties *SchemaObj `json:"additionalProperties,omitempty"` // if type is object (map[])
Properties map[string]SchemaObj `json:"properties,omitempty"` // if type is object
TypeName string `json:"-"` // for internal using, passing typeName
GoType string `json:"x-go-type,omitempty"`
GoPropertyNames map[string]string `json:"x-go-property-names,omitempty"`
GoPropertyTypes map[string]string `json:"x-go-property-types,omitempty"`
}
SchemaObj describes a schema for json format
func NewSchemaObj ¶ added in v0.3.0
NewSchemaObj Constructor function for SchemaObj struct type
func ParseDefinition ¶
ParseDefinition create a DefObj from input object, it should be a pointer to a struct, it reuse schema/json tag for property name.
func SchemaFromCommonName ¶ added in v0.2.0
func SchemaFromCommonName(name commonName) SchemaObj
SchemaFromCommonName create SchemaObj from common name of data types supported types: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
func (SchemaObj) Export ¶ added in v0.3.0
Export returns a "schema reference object" corresponding to this schema object. A "schema reference object" is an abridged version of the original SchemaObj, having only two non-empty fields: Ref and TypeName. "Schema reference objects" are used to refer original schema objects from other schemas.
type SecurityDef ¶ added in v0.3.0
type SecurityDef struct {
Type securityType `json:"type"`
// apiKey properties
In apiKeyIn `json:"in,omitempty"`
Name string `json:"name,omitempty"` // Example: X-API-Key
// http properties
Scheme authenticationScheme `json:"authenticationScheme,omitempty"`
BearerFormat bearerFormat `json:"bearerFormat,omitempty"`
// oauth2 properties
Flow oauthFlow `json:"flow,omitempty"`
AuthorizationURL string `json:"authorizationUrl,omitempty"` // Example: https://example.com/oauth/authorize
TokenURL string `json:"tokenUrl,omitempty"` // Example: https://example.com/oauth/token
Scopes map[string]string `json:"scopes,omitempty"` // Example: {"read": "Grants read access", "write": "Grants write access"}
}
SecurityDef holds security definition
type ServiceType ¶
type ServiceType string
ServiceType data type for type of your service
const ( // ServiceTypeRest define service type for RESTful service ServiceTypeRest ServiceType = "rest" // ServiceTypeJSONRPC define service type for JSON-RPC service ServiceTypeJSONRPC ServiceType = "json-rpc" )