swgen

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2018 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/Halfi/swgen

Then import it into your own code

import "github.com/Halfi/swgen"

Example

package main

import (
    "fmt"

    "github.com/Halfi/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.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}
}
Generate swagger docs for RPC service

You even can use swgen to generate swagger document for a JSON-RPC service as below example

package main

import (
	"fmt"

	"github.com/Halfi/swgen"
)

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

func main()  {
	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",   // JSON-RPC always use POST method
		Title:       "Add new Pet",
		Description: "Add a new pet to the store",
		Tag:         "v1",
		Deprecated:  false,
	}

	gen.SetPathItem(
		pathInf,
		nil,   // no param, all in body
		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"}
}

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

View Source
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"
)
View Source
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"
)
View Source
const (
	// APIKeyInHeader defines API key in header
	APIKeyInHeader apiKeyIn = "header"
	// APIKeyInQuery defines API key in query parameter
	APIKeyInQuery apiKeyIn = "query"
)
View Source
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"
)
View Source
const (
	AuthenticationSchemeBasic  authenticationScheme = "basic"
	AuthenticationSchemeBearer authenticationScheme = "bearer"
	AuthenticationSchemeDigest authenticationScheme = "digest"
	AuthenticationSchemeHOBA   authenticationScheme = "hoba"
)
View Source
const (
	BearerFormatJWT bearerFormat = "JWT"
)

Variables

This section is empty.

Functions

func GenDocument

func GenDocument() ([]byte, error)

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

func ReflectTypeHash added in v0.3.0

func ReflectTypeHash(t reflect.Type) uint32

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

func ReflectTypeReliableName(t reflect.Type) string

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

ContactObj contains contact information for the exposed API

type Definition added in v0.2.0

type Definition struct {
	SchemaObj
	TypeName string
}

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

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 AddExtendedField added in v0.2.0

func AddExtendedField(name string, value interface{}) *Generator

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

func EnableCORS(b bool, allowHeaders ...string) *Generator

EnableCORS enable HTTP handler support CORS

func NewGenerator

func NewGenerator() *Generator

NewGenerator create a new Generator

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 (*Generator) AddExtendedField added in v0.2.0

func (g *Generator) AddExtendedField(name string, value interface{}) *Generator

AddExtendedField add vendor extension field to document

func (*Generator) AddSecurityDefinition added in v0.3.0

func (g *Generator) AddSecurityDefinition(name