swgen

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2017 License: Apache-2.0 Imports: 11 Imported by: 0

README

Swagger Generator (swgen)

Build Status Coverage Status GoDoc

Swagger Generator is a library which helps to generate Swagger Specification in JSON format on-the-fly.

Installation

You can use go get to install the swgen package

go get github.com/lazada/swgen

Then import it into your own code

import "github.com/lazada/swgen"

Example

package main

import (
    "fmt"

    "github.com/lazada/swgen"
)

// PetsRequest defines all params for /pets request
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"`
}

// Pet contains information of a pet
type Pet struct {
    ID   int64  `json:"id"`
    Name string `json:"name"`
    Tag  string `json:"tag"`
}

func main() {
    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.SetPathItem(
        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,
        },
        PetsRequest{}, // request object
        nil,           // body data if any
        []Pet{},       // response object
    )

    docData, _ := gen.GenDocument()
    fmt.Println(string(docData))

    // output:
    // {"swagger":"2.0","x-service-type":"","x-uppercase-version":false,"x-attach-version-to-head":false,"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","required":false},{"name":"limit","in":"query","type":"integer","format":"int32","description":"maximum number of results to return","required":false}],"responses":{"200":{"description":"request success","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}}},"deprecated":false}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}}}
}

License

Distributed under the Apache License, version 2.0. Please see license file in code for more details.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenDocument

func GenDocument() ([]byte, error)

GenDocument returns document specification in JSON string (in []byte)

func ResetDefinitions

func ResetDefinitions()

ResetDefinitions will remove all exists definitions and init again

func ResetPaths

func ResetPaths()

ResetPaths remove all current paths

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"`
}

ContactObj contains contact information for the exposed API

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"`       // The base path on which the API is served, which is relative to the host
	Schemes     []string             `json:"schemes"`        // 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
	// 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

func (s Document) MarshalJSON() ([]byte, error)

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 AddTypeMap

func AddTypeMap(src interface{}, dst interface{}) *Generator

AddTypeMap add rule to use dst interface instead of src

func NewGenerator

func NewGenerator() *Generator

NewGenerator create a new Generator

func SetAttachVersionToHead

func SetAttachVersionToHead(attachToHead bool) *Generator

SetAttachVersionToHead set version position

func SetBasePath

func SetBasePath(basePath string) *Generator

SetBasePath set host info for swagger specification

func SetContact

func SetContact(name, url, email string) *Generator

SetContact set contact information for API

func SetHost

func SetHost(host string) *Generator

SetHost set host info for swagger specification

func SetInfo

func SetInfo(title, description, term, version string) *Generator

SetInfo set information about API

func SetLicense

func SetLicense(name, url string) *Generator

SetLicense set license information for API

func SetType

func SetType(serviceType ServiceType) *Generator

SetType set service type

func SetUppercaseVersion

func SetUppercaseVersion(uppercase bool) *Generator

SetUppercaseVersion set uppercase version

func (*Generator) AddTypeMap

func (g *Generator) AddTypeMap(src interface{}, dst interface{}) *Generator

AddTypeMap add rule to use dst interface instead of src

func (*Generator) GenDocument

func (g *Generator) GenDocument() ([]byte, error)

GenDocument returns document specification in JSON string (in []byte)

Example
package main

import (
	"fmt"

	"github.com/lazada/swgen"
)

func main() {
	// PetsRequest defines all params for /pest request
	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"`
	}

	// 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")

	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,
	}
	pathInf.AddExtendedField("x-example", "example")

	gen.SetPathItem(
		pathInf,
		PetsRequest{}, // request object
		nil,           // body data if any
		[]Pet{},       // response object
	)

	// extended field
	gen.SetUppercaseVersion(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","required":false},{"name":"limit","in":"query","type":"integer","format":"int32","description":"maximum number of results to return","required":false}],"responses":{"200":{"description":"request success","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}}},"deprecated":false,"x-example":"example"}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"x-uppercase-version":true}

func (*Generator) ParseDefinition

func (g *Generator) ParseDefinition(i interface{}) (schema SchemaObj, err error)

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

func (g *Generator) ParseParameter(i interface{}) (name string, params []ParamObj, err error)

ParseParameter parse input struct to swagger parameter object

func (*Generator) ResetDefinitions

func (g *Generator) ResetDefinitions()

ResetDefinitions will remove all exists definitions and init again

func (*Generator) ResetPaths

func (g *Generator) ResetPaths()

ResetPaths remove all current paths

func (*Generator) ServeHTTP

func (g *Generator) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler to server swagger.json document

func (*Generator) SetAttachVersionToHead

func (g *Generator) SetAttachVersionToHead(attachToHead bool) *Generator

SetAttachVersionToHead set version position

func (*Generator) SetBasePath

func (g *Generator) SetBasePath(basePath string) *Generator

SetBasePath set host info for swagger specification

func (*Generator) SetContact

func (g *Generator) SetContact(name, url, email string) *Generator

SetContact set contact information for API

func (*Generator) SetHost

func (g *Generator) SetHost(host string) *Generator

SetHost set host info for swagger specification

func (*Generator) SetInfo

func (g *Generator) SetInfo(title, description, term, version string) *Generator

SetInfo set information about API

func (*Generator) SetLicense

func (g *Generator) SetLicense(name, url string) *Generator

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) SetType

func (g *Generator) SetType(serviceType ServiceType) *Generator

SetType set service type

func (*Generator) SetUppercaseVersion

func (g *Generator) SetUppercaseVersion(uppercase bool) *Generator

SetUppercaseVersion set uppercase version

type IDefinition

type IDefinition interface {
	SwgenDefinition() (typeName string, typeDef SchemaObj, err error)
}

IDefinition allows to return custom definitions

type IParameter

type IParameter interface {
	SwgenParameter() (name string, params []ParamObj, err error)
}

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

type LicenseObj struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

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"`
	Deprecated  bool       `json:"deprecated"`
	// 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"`
	Enum
}

ParamObj describes a single operation parameter see http://swagger.io/specification/#parameterObject

func ParseParameter

func ParseParameter(i interface{}) (name string, params []ParamObj, err error)

ParseParameter parse input struct to swagger parameter object

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

func (PathItem) HasMethod

func (pi PathItem) HasMethod(method string) bool

HasMethod returns true if in path item already have operation for given method

type PathItemInfo

type PathItemInfo struct {
	Path        string
	Method      string
	Title       string
	Description string
	Tag         string
	Deprecated  bool
	// 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 Responses

type Responses map[string]ResponseObj

Responses list of response object

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
}

SchemaObj describes a schema for json format

func ParseDefinition

func ParseDefinition(i interface{}) (typeDef SchemaObj, err error)

ParseDefinition create a DefObj from input object, it should be a pointer to a struct, it reuse schema/json tag for property name.

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"
)

Jump to

Keyboard shortcuts

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