swaggos

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2022 License: MIT Imports: 12 Imported by: 0

README

Swaggos

English | 简体中文

swaggos is a tool for build swagger docs for golang. it generates docs from native golang code.

Installation

    go get -u github.com/clearcodecn/swaggos

Usage

New instance

basic config set host name and api prefix

    doc := swaggos.Default()
    doc.HostInfo("www.github.com","/api/v1")
    
    // default is application/json
    doc.Produces("application/json")
    
    // default is application/json
    doc.Consumes("application/json")
Authorization

swagger support oauth2, basic auth, apiKey and this project is full implement.

Oauth2
    var scopes = []string{"openid"}
    var tokenURL = "https://yourtokenurl"
    var authURL = "https://yourAuthURL"

    // config password flow
    doc.Oauth2Password(tokenURL,scopes)
    // access code
    doc.Oauth2AccessCode(authURL,tokenURL,scopes)
    // client 
    doc.Oauth2Client(tokenURL,scopes)
    // implicit
    doc.Oauth2Implicit(authURL,scopes)
Basic Auth
    doc.Basic()
Custom token
    // will create header param
    // access_token: your token
    doc.JWT("access_token")
Common Params
    // will create header param in each request
    doc.Header("name","description",true)
    doc.Query("name","description",true)
    doc.Form("name","description",true)
Paths

you can change every thing in path.

Tips: It's better to create struct for every params.

    path := doc.Get("user_information")
    // now you can access path apis
    
    path.
        Tag("tagName"). // create a tag 
        Summary("summary"). // summary the request
        Description("...."). // create description
        ContentType("application/json","text/html"). // set content type

    // path params 
    path.Form("key",swaggos.Attribute{})
  
    // form files
    path.FormFile("file",swaggos.Attribute{Required:true})
    
    // form object reference
    path.FormObject(new(User))

    // query object
    path.QueryObject(new(User))
    
    // body
    path.Body(new(User))
    // json response
    path.JSON(new(User))

    // Attribute rules: 
    type Attribute struct {
    	Model       string      `json:"model"`          // key name
    	Description string      `json:"description"`    // description 
    	Required    bool        `json:"required"`       // if it's required 
    	Type        string      `json:"type"`           // the param type
    	Example     interface{} `json:"example"`        // example value
    
    	Nullable  bool          `json:"nullable,omitempty"`     // if it's nullable
    	Format    string        `json:"format,omitempty"`       // format 
    	Title     string        `json:"title,omitempty"`        // title 
    	Default   interface{}   `json:"default,omitempty"`      // default value
    	Maximum   *float64      `json:"maximum,omitempty"`       // max num
    	Minimum   *float64      `json:"minimum,omitempty"`       // min num
    	MaxLength *int64        `json:"maxLength,omitempty"`    // max length
    	MinLength *int64        `json:"minLength,omitempty"`    // min length
    	Pattern   string        `json:"pattern,omitempty"`      // regexp pattern
    	MaxItems  *int64        `json:"maxItems,omitempty"`     // max array length
    	MinItems  *int64        `json:"minItems,omitempty"`     // min array length
    	Enum      []interface{} `json:"enum,omitempty"`         // enum values
    	Ignore    bool          `json:"ignore"`                 // if it's ignore
    	Json      string        `json:"json"`                   // key name
    }


Groups

group will add the common params to each path item below the group.

    	g := doc.Group("/api/v2")
    	g.Get("/user") // --> /api/v2/user
        // ... other methods
        g.Form ...
        g.Query ...
        g.Header ...
path Response
    // will provide a example response
    // 400 
    path.BadRequest(map[string]interface{
            "data": nil,
            "code": 400,
    })
    // 401
    path.UnAuthorization(v)
    // 403
    path.Forbidden(v)
    // 500 
    path.ServerError(v)
Global Response
    doc.Response(200, new(Success))
    doc.Response(400, new(Fail))
    doc.Response(500, new(ServerError))
Object Rules

swaggos will parse object tag to create swagger rules.follow options are supported:

type RuleUser struct {
	// Model for field name
	// this example field name will be m1
	ModelName string `model:"m1" json:"m2"`
	// field name will be username
	Username string `json:"username"`
	//  field name will be Password
	Password string
	//  will be ignore
	Ignored string `json:"-"`
	//  true will be required field, false or empty will be not required
	Required string `required:"true"`
	// create description
	Description string `description:"this is description"`
	// a time type
	Type string `type:"time"`
	// default is abc
	DefaultValue string `default:"abc"`
	// max value is: 100
	Max float64 `maximum:"100"`
	// min value is: 0
	Min float64 `min:"0"`
	// MaxLength is 20
	MaxLength string `maxLength:"20"`
	// MinLength is 10
	MinLength string `minLength:"10"`
	// Pattern for regexp rules
	Pattern string `pattern:"\d{0,9}"`
	// array.length must <= 3
	MaxItems []int `maxItems:"3"`
	// array.length must >= 3
	MinItem []int `minItems:"3"`
	// Enum values
	EnumValue int `enum:"a,b,c,d"`
	// ignore
	IgnoreField string `ignore:"true"`
}
Build
    data,_ := doc.Build()
    fmt.Println(string(data))
    => this is the swagger schema in json format

    data,_ := doc.Yaml()
    fmt.Println(string(data))
    => yaml format
Serve HTTP
    http.Handle("/swagger",doc)

Contact Me

QQ Group: 642154119 wechat

Documentation

Overview

package swaggos

Index

Constants

View Source
const (
	// AccessCodeFlow accessCode flow
	AccessCodeFlow Oauth2Flow = "accessCode"
	// ImplicitFlow implicit flow
	ImplicitFlow = "implicit"
	// PasswordFlow password flow
	PasswordFlow = "password"
	// ApplicationFlow application flow
	ApplicationFlow = "application"
)

Variables

This section is empty.

Functions

func UI added in v0.0.4

func UI(prefix string, baseURL string) http.Handler

Types

type Attribute

type Attribute struct {
	Model       string      `json:"model"`
	Description string      `json:"description"`
	Required    bool        `json:"required"`
	Type        string      `json:"type"`
	Example     interface{} `json:"example"`

	Nullable  bool          `json:"nullable,omitempty"`
	Format    string        `json:"format,omitempty"`
	Title     string        `json:"title,omitempty"`
	Default   interface{}   `json:"default,omitempty"`
	Maximum   *float64      `json:"maximum,omitempty"`
	Minimum   *float64      `json:"minimum,omitempty"`
	MaxLength *int64        `json:"maxLength,omitempty"`
	MinLength *int64        `json:"minLength,omitempty"`
	Pattern   string        `json:"pattern,omitempty"`
	MaxItems  *int64        `json:"maxItems,omitempty"`
	MinItems  *int64        `json:"minItems,omitempty"`
	Enum      []interface{} `json:"enum,omitempty"`
	Ignore    bool          `json:"ignore"`
	JSON      string        `json:"json"`
}

Attribute defines field attribute

func DescRequired

func DescRequired(desc string, required bool) Attribute

DescRequired description and required

func DescRequiredDefault

func DescRequiredDefault(desc string, required bool, def interface{}) Attribute

DescRequiredDefault description and default value

type Group

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

Group is a path group for same prefix

func NewGroup

func NewGroup(prefix string, swaggos *Swaggos) *Group

NewGroup returns a new Group

func (*Group) Delete

func (g *Group) Delete(path string) *Path

Delete create a path with group's prefix and given path of Delete method

func (*Group) Form added in v0.0.2

func (g *Group) Form(name string, desc string, required bool) *Group

Form add form param to the group

func (*Group) Get

func (g *Group) Get(path string) *Path

Get create a path with group's prefix and given path of Get method

func (*Group) Group added in v0.0.4

func (g *Group) Group(prefix string) *Group

Group returns a new group based on current group

func (*Group) Header

func (g *Group) Header(name string, desc string, required bool) *Group

Header defines a header param

func (*Group) Options

func (g *Group) Options(path string) *Path

Options create a path with group's prefix and given path of Options method

func (*Group) Patch

func (g *Group) Patch(path string) *Path

Patch create a path with group's prefix and given path of Patch method

func (*Group) Post

func (g *Group) Post(path string) *Path

Post create a path with group's prefix and given path of Post method

func (*Group) Put

func (g *Group) Put(path string) *Path

Put create a path with group's prefix and given path of Put method

func (*Group) Query added in v0.0.2

func (g *Group) Query(name string, desc string, required bool) *Group

Query add query param to the group

func (*Group) Swaggos

func (g *Group) Swaggos() *Swaggos

Swaggos returns instance of Swaggos

func (*Group) Tag added in v0.0.5

func (g *Group) Tag(t string) *Group

type Oauth2Config added in v0.0.2

type Oauth2Config struct {
	Flow             Oauth2Flow
	AuthorizationURL string
	TokenURL         string
	Scopes           []string
}

Oauth2Config is config for oauth2

type Oauth2Flow added in v0.0.2

type Oauth2Flow string

Oauth2Flow is the type of oauth2

type Option

type Option func(o *Swaggos)

Option option is swaggos option

func DefaultOptions

func DefaultOptions() []Option

DefaultOptions is the default option with: request Content-Type - application/json response Content-Type - application/json default schemas http/https

func WithHTTP added in v0.0.4

func WithHTTP() Option

WithHTTP provide a HTTP protocol

func WithHTTPS added in v0.0.4

func WithHTTPS() Option

WithHTTPS provide a HTTPS protocol

func WithJSON

func WithJSON() Option

WithJSON provide a json response

type Path

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

Path defines a router spec

func (*Path) BadRequest

func (p *Path) BadRequest(v interface{}) *Path

BadRequest serve BadRequest to path

func (*Path) Body

func (p *Path) Body(v interface{}) *Path

Body create body to path

func (*Path) ContentType

func (p *Path) ContentType(req, resp string)

ContentType create request and response Content-Type

func (*Path) Description

func (p *Path) Description(s string) *Path

Description create description of the path

func (*Path) Forbidden

func (p *Path) Forbidden(v interface{}) *Path

Forbidden create 403 to path

func (*Path) Form

func (p *Path) Form(name string, attribute Attribute) *Path

Form create form Params

func (*Path) FormFile

func (p *Path) FormFile(name string, attribute Attribute) *Path

FormFile add file param to the path

func (*Path) FormObject

func (p *Path) FormObject(v interface{}) *Path

FormObject create form object params

func (*Path) Header

func (p *Path) Header(name string, attribute Attribute) *Path

Header create a header to path

func (*Path) JSON

func (p *Path) JSON(v interface{}) *Path

JSON create json response to path

func (*Path) Query

func (p *Path) Query(name string, attribute Attribute) *Path

Query create a query param to path

func (*Path) QueryObject

func (p *Path) QueryObject(v interface{}) *Path

QueryObject parse an object to query

func (*Path) ServerError

func (p *Path) ServerError(v interface{}) *Path

ServerError serve 500 to path

func (*Path) Summary

func (p *Path) Summary(v string) *Path

Summary create summary of the path

func (*Path) Tag

func (p *Path) Tag(v ...string) *Path

Tag set the path tag

func (*Path) UnAuthorization

func (p *Path) UnAuthorization(v interface{}) *Path

UnAuthorization create 401 to path

type Swaggos

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

Swaggos is the base builder

func Default

func Default() *Swaggos

Default create a default swaggo instanence.

func NewSwaggo

func NewSwaggo(option ...Option) *Swaggos

NewSwaggo returns a new Swaggos instanence

func (*Swaggos) APIKeyAuth added in v0.0.5

func (swaggos *Swaggos) APIKeyAuth(name string, position string) *Swaggos

APIKeyAuth set api-key auth support name is the key name position is the key position such as: header/cookie/query

func (*Swaggos) BasicAuth added in v0.0.4

func (swaggos *Swaggos) BasicAuth() *Swaggos

BasicAuth set basic auth support

func (*Swaggos) Build

func (swaggos *Swaggos) Build() ([]byte, error)

Build return json data of swagger doc

func (*Swaggos) Consumes

func (swaggos *Swaggos) Consumes(s ...string)

Consumes create global consumes header

func (*Swaggos) Define

func (swaggos *Swaggos) Define(v interface{}) spec.Ref

Define defines a object or a array to swagger definitions area. it will find all sub-items and build them into swagger tree. it returns the definitions ref.

func (*Swaggos) Delete

func (swaggos *Swaggos) Delete(path string) *Path

Delete add a delete operation

func (*Swaggos) Extend

func (swaggos *Swaggos) Extend(url string, desc string)

Extend extend the swagger docs.

func (*Swaggos) Form added in v0.0.2

func (swaggos *Swaggos) Form(name string, desc string, required bool) *Swaggos

Form add form param to the group

func (*Swaggos) Get

func (swaggos *Swaggos) Get(path string) *Path

Get add a get path operation.

func (*Swaggos) Group

func (swaggos *Swaggos) Group(path string) *Group

Group setup the group of swaggos

func (*Swaggos) Header

func (swaggos *Swaggos) Header(name string, desc string, required bool)

Header add a custom header

func (*Swaggos) HostInfo

func (swaggos *Swaggos) HostInfo(host string, basePath string) *Swaggos

HostInfo add host info to documents

func (*Swaggos) JWT

func (swaggos *Swaggos) JWT(keyName string) *Swaggos

JWT create a jwt header

func (*Swaggos) Oauth2AccessCode added in v0.0.2

func (swaggos *Swaggos) Oauth2AccessCode(authURL string, tokURL string, scopes []string) *Swaggos

Oauth2AccessCode setup swagger oauth2 by access code

func (*Swaggos) Oauth2Client added in v0.0.2

func (swaggos *Swaggos) Oauth2Client(tokURL string, scopes []string) *Swaggos

Oauth2Client setup swagger oauth2 by client

func (*Swaggos) Oauth2Config added in v0.0.2

func (swaggos *Swaggos) Oauth2Config(config Oauth2Config) *Swaggos

Oauth2Config setup oauth2 access type

func (*Swaggos) Oauth2Implicit added in v0.0.2

func (swaggos *Swaggos) Oauth2Implicit(authURL string, scopes []string) *Swaggos

Oauth2Implicit setup swagger oauth2 by implicit

func (*Swaggos) Oauth2Password added in v0.0.2

func (swaggos *Swaggos) Oauth2Password(tokenURL string, scopes []string) *Swaggos

Oauth2Password setup swagger oauth2 by password

func (*Swaggos) Options

func (swaggos *Swaggos) Options(path string) *Path

Options add a options operation

func (*Swaggos) Patch

func (swaggos *Swaggos) Patch(path string) *Path

Patch add a patch operation.

func (*Swaggos) Post

func (swaggos *Swaggos) Post(path string) *Path

Post add a post path operation.

func (*Swaggos) Produces

func (swaggos *Swaggos) Produces(s ...string)

Produces create global produces header

func (*Swaggos) Put

func (swaggos *Swaggos) Put(path string) *Path

Put add a put operation

func (*Swaggos) Query added in v0.0.2

func (swaggos *Swaggos) Query(name string, desc string, required bool) *Swaggos

Query add query param to the group

func (*Swaggos) Response

func (swaggos *Swaggos) Response(status int, v interface{}) *Swaggos

Response setup response object and build a example

func (*Swaggos) ServeHTTP added in v0.0.2

func (swaggos *Swaggos) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP export a http handler for serve document.

func (*Swaggos) Yaml

func (swaggos *Swaggos) Yaml() ([]byte, error)

Yaml build yaml data of swagger doc

Jump to

Keyboard shortcuts

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