swagger

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2016 License: MIT, Apache-2.0 Imports: 9 Imported by: 0

README

How to use Swagger UI with go-restful

Get the Swagger UI sources (version 1.2 only)

git clone https://github.com/wordnik/swagger-ui.git

The project contains a "dist" folder. Its contents has all the Swagger UI files you need.

The index.html has an url set to http://petstore.swagger.wordnik.com/api/api-docs. You need to change that to match your WebService JSON endpoint e.g. http://localhost:8080/apidocs.json

Now, you can install the Swagger WebService for serving the Swagger specification in JSON.

config := swagger.Config{
	WebServices:    restful.RegisteredWebServices(),
	ApiPath:        "/apidocs.json",
	SwaggerPath:     "/apidocs/",
	SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"}
swagger.InstallSwaggerService(config)		

Documenting Structs

Currently there are 2 ways to document your structs in the go-restful Swagger.

By using struct tags
  • Use tag "description" to annotate a struct field with a description to show in the UI
  • Use tag "modelDescription" to annotate the struct itself with a description to show in the UI. The tag can be added in an field of the struct and in case that there are multiple definition, they will be appended with an empty line.
By using the SwaggerDoc method

Here is an example with an Address struct and the documentation for each of the fields. The "" is a special entry for documenting the struct itself.

type Address struct {
	Country  string `json:"country,omitempty"`
	PostCode int    `json:"postcode,omitempty"`
}

func (Address) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "Address doc",
		"country":  "Country doc",
		"postcode": "PostCode doc",
	}
}

This example will generate a JSON like this

{
	"Address": {
		"id": "Address",
		"description": "Address doc",
		"properties": {
			"country": {
			"type": "string",
			"description": "Country doc"
			},
			"postcode": {
			"type": "integer",
			"format": "int32",
			"description": "PostCode doc"
			}
		}
	}
}

Very Important Notes:

  • SwaggerDoc() is using a NON-Pointer receiver (e.g. func (Address) and not func (*Address))
  • The returned map should use as key the name of the field as defined in the JSON parameter (e.g. "postcode" and not "PostCode")

Notes

  • The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..)
  • The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints.

Documentation

Overview

Package swagger implements the structures of the Swagger https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md

Index

Constants

This section is empty.

Variables

View Source
var LogInfo = func(format string, v ...interface{}) {

	log.Printf(format, v...)
}

LogInfo is the function that is called when this package needs to log. It defaults to log.Printf

Functions

func InstallSwaggerService

func InstallSwaggerService(aSwaggerConfig Config)

InstallSwaggerService add the WebService that provides the API documentation of all services conform the Swagger documentation specifcation. (https://github.com/wordnik/swagger-core/wiki).

func RegisterSwaggerService

func RegisterSwaggerService(config Config, wsContainer *restful.Container)

RegisterSwaggerService add the WebService that provides the API documentation of all services conform the Swagger documentation specifcation. (https://github.com/wordnik/swagger-core/wiki).

Types

type Api

type Api struct {
	Path        string      `json:"path"` // relative or absolute, must start with /
	Description string      `json:"description"`
	Operations  []Operation `json:"operations,omitempty"`
}

5.2.2 API Object

type ApiDeclaration

type ApiDeclaration struct {
	SwaggerVersion string          `json:"swaggerVersion"`
	ApiVersion     string          `json:"apiVersion"`
	BasePath       string          `json:"basePath"`
	ResourcePath   string          `json:"resourcePath"` // must start with /
	Info           Info            `json:"info"`
	Apis           []Api           `json:"apis,omitempty"`
	Models         ModelList       `json:"models,omitempty"`
	Produces       []string        `json:"produces,omitempty"`
	Consumes       []string        `json:"consumes,omitempty"`
	Authorizations []Authorization `json:"authorizations,omitempty"`
}

5.2 API Declaration

type ApiDeclarationList added in v1.0.2

type ApiDeclarationList struct {
	List []ApiDeclaration
}

ApiDeclarationList maintains an ordered list of ApiDeclaration.

func (*ApiDeclarationList) At added in v1.0.2

func (l *ApiDeclarationList) At(path string) (a ApiDeclaration, ok bool)

At returns the ApiDeclaration by its path unless absent, then ok is false

func (*ApiDeclarationList) Do added in v1.0.2

func (l *ApiDeclarationList) Do(block func(path string, decl ApiDeclaration))

Do enumerates all the properties, each with its assigned name

func (ApiDeclarationList) MarshalJSON added in v1.0.2

func (l ApiDeclarationList) MarshalJSON() ([]byte, error)

MarshalJSON writes the ModelPropertyList as if it was a map[string]ModelProperty

func (*ApiDeclarationList) Put added in v1.0.2

func (l *ApiDeclarationList) Put(path string, a ApiDeclaration)

Put adds or replaces a ApiDeclaration with this name

type Authorization

type Authorization struct {
	Type       string      `json:"type"`
	PassAs     string      `json:"passAs"`
	Keyname    string      `json:"keyname"`
	Scopes     []Scope     `json:"scopes"`
	GrantTypes []GrantType `json:"grandTypes"`
}

5.1.5

type AuthorizationCode

type AuthorizationCode struct {
	TokenRequestEndpoint TokenRequestEndpoint `json:"tokenRequestEndpoint"`
	TokenEndpoint        TokenEndpoint        `json:"tokenEndpoint"`
}

5.1.9 Authorization Code Object

type Authorizations

type Authorizations map[string]Authorization

5.2.10

type Config

type Config struct {
	// url where the services are available, e.g. http://localhost:8080
	// if left empty then the basePath of Swagger is taken from the actual request
	WebServicesUrl string
	// path where the JSON api is avaiable , e.g. /apidocs
	ApiPath string
	// [optional] path where the swagger UI will be served, e.g. /swagger
	SwaggerPath string
	// [optional] location of folder containing Swagger HTML5 application index.html
	SwaggerFilePath string
	// api listing is constructed from this list of restful WebServices.
	WebServices []*restful.WebService
	// will serve all static content (scripts,pages,images)
	StaticHandler http.Handler
	// [optional] on default CORS (Cross-Origin-Resource-Sharing) is enabled.
	DisableCORS bool
	// Top-level API version. Is reflected in the resource listing.
	ApiVersion string
	// If set then call this handler after building the complete ApiDeclaration Map
	PostBuildHandler PostBuildDeclarationMapFunc
	// Swagger global info struct
	Info Info
}

type DataTypeFields

type DataTypeFields struct {
	Type         *string  `json:"type,omitempty"` // if Ref not used
	Ref          *string  `json:"$ref,omitempty"` // if Type not used
	Format       string   `json:"format,omitempty"`
	DefaultValue Special  `json:"defaultValue,omitempty"`
	Enum         []string `json:"enum,omitempty"`
	Minimum      string   `json:"minimum,omitempty"`
	Maximum      string   `json:"maximum,omitempty"`
	Items        *Item    `json:"items,omitempty"`
	UniqueItems  *bool    `json:"uniqueItems,omitempty"`
}

4.3.3 Data Type Fields

type GrantType

type GrantType struct {
	Implicit          Implicit          `json:"implicit"`
	AuthorizationCode AuthorizationCode `json:"authorization_code"`
}

5.1.7

type Implicit

type Implicit struct {

	// An optional alternative name to standard "access_token" OAuth2 parameter.
	TokenName string `json:"tokenName"`
	// contains filtered or unexported fields
}

5.1.8 Implicit Object

type Info

type Info struct {
	Title             string `json:"title"`
	Description       string `json:"description"`
	TermsOfServiceUrl string `json:"termsOfServiceUrl,omitempty"`
	Contact           string `json:"contact,omitempty"`
	License           string `json:"license,omitempty"`
	LicenseUrl        string `json:"licenseUrl,omitempty"`
}

5.1.3 Info Object

type Item

type Item struct {
	Type   *string `json:"type,omitempty"`
	Ref    *string `json:"$ref,omitempty"`
	Format string  `json:"format,omitempty"`
}

4.3.4 Items Object

type LoginEndpoint

type LoginEndpoint struct {
	// Required. The URL of the authorization endpoint for the implicit grant flow. The value SHOULD be in a URL format.
	Url string `json:"url"`
}

5.1.10 Login Endpoint Object

type Model

type Model struct {
	Id            string            `json:"id"`
	Description   string            `json:"description,omitempty"`
	Required      []string          `json:"required,omitempty"`
	Properties    ModelPropertyList `json:"properties"`
	SubTypes      []string          `json:"subTypes,omitempty"`
	Discriminator string            `json:"discriminator,omitempty"`
}

5.2.6, 5.2.7 Models Object

type ModelBuildable

type ModelBuildable interface {
	PostBuildModel(m *Model) *Model
}

ModelBuildable is used for extending Structs that need more control over how the Model appears in the Swagger api declaration.

type ModelList added in v1.0.2

type ModelList struct {
	List []NamedModel
}

ModelList encapsulates a list of NamedModel (association)

func (*ModelList) At added in v1.0.2

func (l *ModelList) At(name string) (m Model, ok bool)

At returns a Model by its name, ok is false if absent

func (*ModelList) Do added in v1.0.2

func (l *ModelList) Do(block func(name string, value Model))

Do enumerates all the models, each with its assigned name

func (ModelList) MarshalJSON added in v1.0.2

func (l ModelList) MarshalJSON() ([]byte, error)

MarshalJSON writes the ModelList as if it was a map[string]Model

func (*ModelList) Put added in v1.0.2

func (l *ModelList) Put(name string, model Model)

Put adds or replaces a Model by its name

func (*ModelList) UnmarshalJSON added in v1.0.2

func (l *ModelList) UnmarshalJSON(data []byte) error

UnmarshalJSON reads back a ModelList. This is an expensive operation.

type ModelProperty

type ModelProperty struct {
	DataTypeFields
	Description string `json:"description,omitempty"`
}

5.2.8 Properties Object

type ModelPropertyList added in v1.0.2

type ModelPropertyList struct {
	List []NamedModelProperty
}

ModelPropertyList encapsulates a list of NamedModelProperty (association)

func (*ModelPropertyList) At added in v1.0.2

func (l *ModelPropertyList) At(name string) (p ModelProperty, ok bool)

At returns the ModelPropety by its name unless absent, then ok is false

func (*ModelPropertyList) Do added in v1.0.2

func (l *ModelPropertyList) Do(block func(name string, value ModelProperty))

Do enumerates all the properties, each with its assigned name

func (ModelPropertyList) MarshalJSON added in v1.0.2

func (l ModelPropertyList) MarshalJSON() ([]byte, error)

MarshalJSON writes the ModelPropertyList as if it was a map[string]ModelProperty

func (*ModelPropertyList) Put added in v1.0.2

func (l *ModelPropertyList) Put(name string, prop ModelProperty)

Put adds or replaces a ModelProperty with this name

func (*ModelPropertyList) UnmarshalJSON added in v1.0.2

func (l *ModelPropertyList) UnmarshalJSON(data []byte) error

UnmarshalJSON reads back a ModelPropertyList. This is an expensive operation.

type NamedModel added in v1.0.2

type NamedModel struct {
	Name  string
	Model Model
}

NamedModel associates a name with a Model (not using its Id)

type NamedModelProperty added in v1.0.2

type NamedModelProperty struct {
	Name     string
	Property ModelProperty
}

NamedModelProperty associates a name to a ModelProperty

type Operation

type Operation struct {
	DataTypeFields
	Method           string            `json:"method"`
	Summary          string            `json:"summary,omitempty"`
	Notes            string            `json:"notes,omitempty"`
	Nickname         string            `json:"nickname"`
	Authorizations   []Authorization   `json:"authorizations,omitempty"`
	Parameters       []Parameter       `json:"parameters"`
	ResponseMessages []ResponseMessage `json:"responseMessages,omitempty"` // optional
	Produces         []string          `json:"produces,omitempty"`
	Consumes         []string          `json:"consumes,omitempty"`
	Deprecated       string            `json:"deprecated,omitempty"`
}

5.2.3 Operation Object

type Parameter

type Parameter struct {
	DataTypeFields
	ParamType     string `json:"paramType"` // path,query,body,header,form
	Name          string `json:"name"`
	Description   string `json:"description"`
	Required      bool   `json:"required"`
	AllowMultiple bool   `json:"allowMultiple"`
}

5.2.4 Parameter Object

type PostBuildDeclarationMapFunc

type PostBuildDeclarationMapFunc func(apiDeclarationMap *ApiDeclarationList)

PostBuildDeclarationMapFunc can be used to modify the api declaration map.

type Resource

type Resource struct {
	Path        string `json:"path"` // relative or absolute, must start with /
	Description string `json:"description"`
}

5.1.2 Resource Object

type ResourceListing

type ResourceListing struct {
	SwaggerVersion string          `json:"swaggerVersion"` // e.g 1.2
	Apis           []Resource      `json:"apis"`
	ApiVersion     string          `json:"apiVersion"`
	Info           Info            `json:"info"`
	Authorizations []Authorization `json:"authorizations,omitempty"`
}

5.1 Resource Listing

type ResponseMessage

type ResponseMessage struct {
	Code          int    `json:"code"`
	Message       string `json:"message"`
	ResponseModel string `json:"responseModel,omitempty"`
}

5.2.5 Response Message Object

type Scope

type Scope struct {
	// Required. The name of the scope.
	Scope string `json:"scope"`
	// Recommended. A short description of the scope.
	Description string `json:"description"`
}

5.1.6, 5.2.11

type Special

type Special string

type SwaggerBuilder added in v1.1.2

type SwaggerBuilder struct {
	SwaggerService
}

func NewSwaggerBuilder added in v1.1.2

func NewSwaggerBuilder(config Config) *SwaggerBuilder

func (SwaggerBuilder) ProduceAllDeclarations added in v1.1.2

func (sb SwaggerBuilder) ProduceAllDeclarations() map[string]ApiDeclaration

func (SwaggerBuilder) ProduceDeclarations added in v1.1.2

func (sb SwaggerBuilder) ProduceDeclarations(route string) (*ApiDeclaration, bool)

func (SwaggerBuilder) ProduceListing added in v1.1.2

func (sb SwaggerBuilder) ProduceListing() ResourceListing

type SwaggerService

type SwaggerService struct {
	// contains filtered or unexported fields
}

type TokenEndpoint

type TokenEndpoint struct {
	// Required. The URL of the token endpoint for the authentication code grant flow. The value SHOULD be in a URL format.
	Url string `json:"url"`
	// An optional alternative name to standard "access_token" OAuth2 parameter.
	TokenName string `json:"tokenName"`
}

5.1.12 Token Endpoint Object

type TokenRequestEndpoint

type TokenRequestEndpoint struct {
	// Required. The URL of the authorization endpoint for the authentication code grant flow. The value SHOULD be in a URL format.
	Url string `json:"url"`
	// An optional alternative name to standard "client_id" OAuth2 parameter.
	ClientIdName string `json:"clientIdName"`
	// An optional alternative name to the standard "client_secret" OAuth2 parameter.
	ClientSecretName string `json:"clientSecretName"`
}

5.1.11 Token Request Endpoint Object

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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