Automatically generate RESTful API documentation with Swagger 2.0 for Go.

swag

🌍 English ∙ įŽ€äŊ“中文

Travis Status Coverage Status Go Report Card codebeat badge Go Doc Backers on Open Collective Sponsors on Open Collective FOSSA Status Release

Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popular Go web frameworks. This allows you to quickly integrate with an existing Go project (using Swagger UI).

Contents

Getting started

  1. Add comments to your API source code, See Declarative Comments Format.

  2. Download swag by using:

$ go get -u github.com/swaggo/swag/cmd/swag

To build from source you need Go (1.9 or newer).

Or download a pre-compiled binary from the release page.

  1. Run swag init in the project's root folder which contains the main.go file. This will parse your comments and generate the required files (docs folder and docs/docs.go).
$ swag init

Make sure to import the generated docs/docs.go so that your specific configuration gets init'ed. If your General API annotations do not live in main.go, you can let swag know with -g flag.

swag init -g http/api.go

swag cli

$ swag init -h
NAME:
   swag init - Create docs.go

USAGE:
   swag init [command options] [arguments...]

OPTIONS:
   --generalInfo value, -g value          Go file path in which 'swagger general API Info' is written (default: "main.go")
   --dir value, -d value                  Directory you want to parse (default: "./")
   --exclude value                        Exclude directories and files when searching, comma separated
   --propertyStrategy value, -p value     Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
   --output value, -o value               Output directory for all the generated files(swagger.json, swagger.yaml and doc.go) (default: "./docs")
   --parseVendor                          Parse go files in 'vendor' folder, disabled by default (default: false)
   --parseDependency                      Parse go files in outside dependency folder, disabled by default (default: false)
   --markdownFiles value, --md value      Parse folder containing markdown files to use as description, disabled by default
   --codeExampleFiles value, --cef value  Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
   --parseInternal                        Parse go files in internal packages, disabled by default (default: false)
   --generatedTime                        Generate timestamp at the top of docs.go, disabled by default (default: false)
   --parseDepth value                     Dependency parse depth (default: 100)
   --help, -h                             show help (default: false)

Supported Web Frameworks

How to use it with Gin

Find the example source code here.

  1. After using swag init to generate Swagger 2.0 docs, import the following packages:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
  1. Add General API annotations in main.go code:
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /api/v1
// @query.collection.format multi

// @securityDefinitions.basic BasicAuth

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization

// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.implicit OAuth2Implicit
// @authorizationurl https://example.com/oauth/authorize
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.password OAuth2Password
// @tokenUrl https://example.com/oauth/token
// @scope.read Grants read access
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
// @tokenUrl https://example.com/oauth/token
// @authorizationurl https://example.com/oauth/authorize
// @scope.admin Grants read and write access to administrative information

// @x-extension-openapi {"example": "value on a json format"}

func main() {
	r := gin.Default()

	c := controller.NewController()

	v1 := r.Group("/api/v1")
	{
		accounts := v1.Group("/accounts")
		{
			accounts.GET(":id", c.ShowAccount)
			accounts.GET("", c.ListAccounts)
			accounts.POST("", c.AddAccount)
			accounts.DELETE(":id", c.DeleteAccount)
			accounts.PATCH(":id", c.UpdateAccount)
			accounts.POST(":id/images", c.UploadAccountImage)
		}
    //...
	}
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	r.Run(":8080")
}
//...

Additionally some general API info can be set dynamically. The generated code package docs exports SwaggerInfo variable which we can use to set the title, description, version, host and base path programmatically. Example using Gin:

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/swaggo/files"
	"github.com/swaggo/gin-swagger"
	
	"./docs" // docs is generated by Swag CLI, you have to import it.
)

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @termsOfService http://swagger.io/terms/

func main() {

	// programmatically set swagger info
	docs.SwaggerInfo.Title = "Swagger Example API"
	docs.SwaggerInfo.Description = "This is a sample server Petstore server."
	docs.SwaggerInfo.Version = "1.0"
	docs.SwaggerInfo.Host = "petstore.swagger.io"
	docs.SwaggerInfo.BasePath = "/v2"
	docs.SwaggerInfo.Schemes = []string{"http", "https"}
		
	r := gin.New()

	// use ginSwagger middleware to serve the API docs
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	r.Run()
}
  1. Add API Operation annotations in controller code
package controller

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/swaggo/swag/example/celler/httputil"
	"github.com/swaggo/swag/example/celler/model"
)

// ShowAccount godoc
// @Summary Show a account
// @Description get string by ID
// @ID get-string-by-int
// @Accept  json
// @Produce  json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Header 200 {string} Token "qwerty"
// @Failure 400,404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Failure default {object} httputil.DefaultError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
	id := ctx.Param("id")
	aid, err := strconv.Atoi(id)
	if err != nil {
		httputil.NewError(ctx, http.StatusBadRequest, err)
		return
	}
	account, err := model.AccountOne(aid)
	if err != nil {
		httputil.NewError(ctx, http.StatusNotFound, err)
		return
	}
	ctx.JSON(http.StatusOK, account)
}

// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Accept  json
// @Produce  json
// @Param q query string false "name search by q"
// @Success 200 {array} model.Account
// @Header 200 {string} Token "qwerty"
// @Failure 400,404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Failure default {object} httputil.DefaultError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
	q := ctx.Request.URL.Query().Get("q")
	accounts, err := model.AccountsAll(q)
	if err != nil {
		httputil.NewError(ctx, http.StatusNotFound, err)
		return
	}
	ctx.JSON(http.StatusOK, accounts)
}

//...
$ swag init
  1. Run your app, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:

swagger_index.html

Implementation Status

Swagger 2.0 document

  • Basic Structure
  • API Host and Base Path
  • Paths and Operations
  • Describing Parameters
  • Describing Request Body
  • Describing Responses
  • MIME Types
  • Authentication
    • Basic Authentication
    • API Keys
  • Adding Examples
  • File Upload
  • Enums
  • Grouping Operations With Tags
  • Swagger Extensions

Declarative Comments Format

General API Info

Example celler/main.go

annotation description example
title Required. The title of the application. // @title Swagger Example API
version Required. Provides the version of the application API. // @version 1.0
description A short description of the application. // @description This is a sample server celler server.
tag.name Name of a tag. // @tag.name This is the name of the tag
tag.description Description of the tag // @tag.description Cool Description
tag.docs.url Url of the external Documentation of the tag // @tag.docs.url https://example.com
tag.docs.description Description of the external Documentation of the tag // @tag.docs.description Best example documentation
termsOfService The Terms of Service for the API. // @termsOfService http://swagger.io/terms/
contact.name The contact information for the exposed API. // @contact.name API Support
contact.url The URL pointing to the contact information. MUST be in the format of a URL. // @contact.url http://www.swagger.io/support
contact.email The email address of the contact person/organization. MUST be in the format of an email address. // @contact.email [email protected]
license.name Required. The license name used for the API. // @license.name Apache 2.0
license.url A URL to the license used for the API. MUST be in the format of a URL. // @license.url http://www.apache.org/licenses/LICENSE-2.0.html
host The host (name or ip) serving the API. // @host localhost:8080
BasePath The base path on which the API is served. // @BasePath /api/v1
query.collection.format The default collection(array) param format in query,enums:csv,multi,pipes,tsv,ssv. If not set, csv is the default. // @query.collection.format multi
schemes The transfer protocol for the operation that separated by spaces. // @schemes http https
x-name The extension key, must be start by x- and take only json value // @x-example-key {"key": "value"}

Using markdown descriptions

When a short string in your documentation is insufficient, or you need images, code examples and things like that you may want to use markdown descriptions. In order to use markdown descriptions use the following annotations.

annotation description example
title Required. The title of the application. // @title Swagger Example API
version Required. Provides the version of the application API. // @version 1.0
description.markdown A short description of the application. Parsed from the api.md file. This is an alternative to @description // @description.markdown No value needed, this parses the description from api.md
tag.name Name of a tag. // @tag.name This is the name of the tag
tag.description.markdown Description of the tag this is an alternative to tag.description. The description will be read from a file named like tagname.md // @tag.description.markdown

API Operation

Example celler/controller

annotation description
description A verbose explanation of the operation behavior.
description.markdown A short description of the application. The description will be read from a file named like endpointname.md
id A unique string used to identify the operation. Must be unique among all API operations.
tags A list of tags to each API operation that separated by commas.
summary A short summary of what the operation does.
accept A list of MIME types the APIs can consume. Value MUST be as described under Mime Types.
produce A list of MIME types the APIs can produce. Value MUST be as described under Mime Types.
param Parameters that separated by spaces. param name,param type,data type,is mandatory?,comment attribute(optional)
security Security to each API operation.
success Success response that separated by spaces. return code or default,{param type},data type,comment
failure Failure response that separated by spaces. return code or default,{param type},data type,comment
response As same as success and failure
header Header in response that separated by spaces. return code,{param type},data type,comment
router Path definition that separated by spaces. path,[httpMethod]
x-name The extension key, must be start by x- and take only json value.
x-codeSample Optional Markdown usage. take file as parameter. This will then search for a file named like the summary in the given folder.
deprecated Mark endpoint as deprecated.

Mime Types

swag accepts all MIME Types which are in the correct format, that is, match */*. Besides that, swag also accepts aliases for some MIME Types as follows:

Alias MIME Type
json application/json
xml text/xml
plain text/plain
html text/html
mpfd multipart/form-data
x-www-form-urlencoded application/x-www-form-urlencoded
json-api application/vnd.api+json
json-stream application/x-json-stream
octet-stream application/octet-stream
png image/png
jpeg image/jpeg
gif image/gif

Param Type

  • query
  • path
  • header
  • body
  • formData

Data Type

  • string (string)
  • integer (int, uint, uint32, uint64)
  • number (float32)
  • boolean (bool)
  • user defined struct

Security

annotation description parameters example
securitydefinitions.basic Basic auth. // @securityDefinitions.basic BasicAuth
securitydefinitions.apikey API key auth. in, name // @securityDefinitions.apikey ApiKeyAuth
securitydefinitions.oauth2.application OAuth2 application auth. tokenUrl, scope // @securitydefinitions.oauth2.application OAuth2Application
securitydefinitions.oauth2.implicit OAuth2 implicit auth. authorizationUrl, scope // @securitydefinitions.oauth2.implicit OAuth2Implicit
securitydefinitions.oauth2.password OAuth2 password auth. tokenUrl, scope // @securitydefinitions.oauth2.password OAuth2Password
securitydefinitions.oauth2.accessCode OAuth2 access code auth. tokenUrl, authorizationUrl, scope // @securitydefinitions.oauth2.accessCode OAuth2AccessCode
parameters annotation example
in // @in header
name // @name Authorization
tokenUrl // @tokenUrl https://example.com/oauth/token
authorizationurl // @authorizationurl https://example.com/oauth/authorize
scope.hoge // @scope.write Grants write access

Attribute

// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param collection query []string false "string collection" collectionFormat(multi)

It also works for the struct fields:

type Foo struct {
    Bar string `minLength:"4" maxLength:"16"`
    Baz int `minimum:"10" maximum:"20" default:"15"`
    Qux []string `enums:"foo,bar,baz"`
}

Available

Field Name Type Description
validate string Determines the validation for the parameter. Possible values are: required.
default * Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined type for this parameter.
maximum number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimum number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
maxLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
enums [*] See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
format string The extending format for the previously mentioned type. See Data Type Formats for further details.
collectionFormat string Determines the format of the array if type array is used. Possible values are:
  • csv - comma separated values foo,bar.
  • ssv - space separated values foo bar.
  • tsv - tab separated values foo\tbar.
  • pipes - pipe separated values foo|bar.
  • multi - corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in "query" or "formData".
Default value is csv.

Future

Field Name Type Description
multipleOf number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
pattern string See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItems boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.

Examples

Descriptions over multiple lines

You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:

// @description This is the first line
// @description This is the second line
// @description And so forth.

User defined structure with an array type

// @Success 200 {array} model.Account <-- This is a user defined struct.
package model

type Account struct {
    ID   int    `json:"id" example:"1"`
    Name string `json:"name" example:"account name"`
}

Model composition in response

// JSONResult's data field will be overridden by the specific type proto.Order
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
type JSONResult struct {
    Code    int          `json:"code" `
    Message string       `json:"message"`
    Data    interface{}  `json:"data"`
}

type Order struct { //in `proto` package
    Id  uint            `json:"id"`
    Data  interface{}   `json:"data"`
}
  • also support array of objects and primitive types as nested response
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
  • overriding multiple fields. field will be added if not exists
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
  • overriding deep-level fields
type DeepObject struct { //in `proto` package
	...
}
@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"

Add a headers in response

// @Success 200 {string} string	"ok"
// @failure 400 {string} string	"error"
// @response default {string} string	"other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"

Use multiple path params

/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]

Example value of struct

type Account struct {
    ID   int    `json:"id" example:"1"`
    Name string `json:"name" example:"account name"`
    PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}

Description of struct

type Account struct {
	// ID this is userid
	ID   int    `json:"id"`
	Name string `json:"name"` // This is Name
}

Use swaggertype tag to supported custom type

#201

type TimestampTime struct {
    time.Time
}

///implement encoding.JSON.Marshaler interface
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
    bin := make([]byte, 16)
    bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
    return bin, nil
}

func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
    v, err := strconv.ParseInt(string(bin), 10, 64)
    if err != nil {
        return err
    }
    t.Time = time.Unix(v, 0)
    return nil
}
///

type Account struct {
    // Override primitive type by simply specifying it via `swaggertype` tag
    ID     sql.NullInt64 `json:"id" swaggertype:"integer"`

    // Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
    RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`

    // Array types can be overridden using "array," format
    Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}

#379

type CerticateKeyPair struct {
	Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
	Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}

generated swagger doc as follows:

"api.MyBinding": {
  "type":"object",
  "properties":{
    "crt":{
      "type":"string",
      "format":"base64",
      "example":"U3dhZ2dlciByb2Nrcw=="
    },
    "key":{
      "type":"string",
      "format":"base64",
      "example":"U3dhZ2dlciByb2Nrcw=="
    }
  }
}

Use swaggerignore tag to exclude a field

type Account struct {
    ID   string    `json:"id"`
    Name string     `json:"name"`
    Ignored int     `swaggerignore:"true"`
}

Add extension info to struct field

type Account struct {
    ID   string    `json:"id"   extensions:"x-nullable,x-abc=def"` // extensions fields must start with "x-"
}

generate swagger doc as follows:

"Account": {
    "type": "object",
    "properties": {
        "id": {
            "type": "string",
            "x-nullable": true,
            "x-abc": "def"
        }
    }
}

Rename model to display

type Resp struct {
	Code int
}//@name Response

How to using security annotations

General API info.

// @securityDefinitions.basic BasicAuth

// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

Each API operation.

// @Security ApiKeyAuth

Make it AND condition

// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]

About the Project

This project was inspired by yvasiyarov/swagger but we simplified the usage and added support a variety of web frameworks. Gopher image source is tenntenn/gopher-stickers. It has licenses creative commons licensing.

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

FOSSA Status

Owner
Swaggo
Automatically generate RESTful API documentation with Swagger 2.0 for Go
Swaggo
Comments
  • panic: runtime error: negative shift amount

    panic: runtime error: negative shift amount

    Describe the bug While running the init command with master it panics

    To Reproduce Steps to reproduce the behavior:

    1. with the following definition:
    type Type string
    
    const (
    	TypePerson   Type = "person"
    	TypeBusiness Type = "business"
    )
    
    type customerIn struct {
    	ClientId string `json:"client_id"`
    	Type     string `json:"type"`
    }
    
    type customerOut struct {
    	Id        string    `json:"id"`
    	ClientId  string    `json:"client_id"`
    	Type      string    `json:"type"`
    	CreatedAt time.Time `json:"created_at"`
    	UpdatedAt time.Time `json:"updated_at"`
    }
    
    type customersOut struct {
    	Result []customerOut
    }
    

    run:

    swag init -g service/server/server.go --pd
    swag fmt -g service/server/server.go
    

    Throws the error:

    swag init -g service/server/server.go --pd
    2022/11/22 08:09:45 Generate swagger docs....
    2022/11/22 08:09:45 Generate general API Info, search dir:./
    2022/11/22 08:09:45 warning: failed to get package name in dir: ./, error: execute go list command, exit status 1, stdout:, stderr:no Go files in /Users/nicolas.sassi/dev/soul/acaiah
    panic: runtime error: negative shift amount
    
    goroutine 1 [running]:
    github.com/swaggo/swag.(*PackageDefinitions).evaluateConstValue(0xc00607e870, 0xc0068aa2d0?, 0xc00665ef60?, {0x165bee0?, 0xc005cecf90?}, {0x165a460, 0xc0001b1800}, 0x1c?)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/package.go:146 +0x102b
    github.com/swaggo/swag.(*PackagesDefinitions).EvaluateConstValue(0xc00479f698?, 0xc00607e870, 0xc00682de00, 0x0)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/packages.go:282 +0x19d
    github.com/swaggo/swag.(*PackagesDefinitions).evaluateAllConstVariables(...)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/packages.go:265
    github.com/swaggo/swag.(*PackagesDefinitions).ParseTypes(0xc0001b1800)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/packages.go:110 +0x254
    github.com/swaggo/swag.(*Parser).ParseAPIMultiSearchDir(0xc00027c000, {0xc0002780e0?, 0x1?, 0x0?}, {0x7ff7bfeff555?, 0x18?}, 0x64)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/parser.go:375 +0x3bf
    github.com/swaggo/swag/gen.(*Gen).Build(0xc000249950, 0xc0002502a0)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/gen/gen.go:182 +0x637
    main.initAction(0xc000266780?)
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/cmd/swag/main.go:158 +0x7bd
    github.com/urfave/cli/v2.(*Command).Run(0xc000220ea0, 0xc000262300)
            /Users/nicolas.sassi/go/pkg/mod/github.com/urfave/cli/[email protected]/command.go:163 +0x5dc
    github.com/urfave/cli/v2.(*App).RunContext(0xc000195d40, {0x165cef0?, 0xc000196008}, {0xc00019c000, 0x5, 0x5})
            /Users/nicolas.sassi/go/pkg/mod/github.com/urfave/cli/[email protected]/app.go:313 +0xb7d
    github.com/urfave/cli/v2.(*App).Run(...)
            /Users/nicolas.sassi/go/pkg/mod/github.com/urfave/cli/[email protected]/app.go:224
    main.main()
            /Users/nicolas.sassi/go/pkg/mod/github.com/swaggo/[email protected]/cmd/swag/main.go:229 +0x5c5
    make: *** [swagger] Error 2
    

    Expected behavior Swagger created

    Your swag version go install github.com/swaggo/swag/cmd/swag@e5d507dd472777bec3a3744f7f9cc86065037530

    Your go version 1.19.1

    Desktop (please complete the following information):

    • OS: macOS Monterey 12.6.1
  • Imporve performance when generating spec with external dependencies

    Imporve performance when generating spec with external dependencies

    Describe the PR

    Directly use go list command instead of depth, because depth use go standard library build.Import and call the build.Import too many times, it will spent too many times when the large dependencies.

    Because swag only needs to know which files are dependent, and does not need to get the level of dependencies, all dependencies can be directly through go list command, and swag not need to go through deep loop again, but if use depth, swag still need to loop too many times, so i refactor the swag get ast files code.

    Relation issue

    Fixes: https://github.com/swaggo/swag/issues/1032

    Additional context

    Added the --parseGoList flag, the default value is true default. If someone does not want to enable it, it can be set to false when init, if it's set to false, swag still use depth for dependency parser.

  • undefined:

    undefined: "github.com/swaggo/swag".Spec

    hi, i have been using this repo for a while now. just a few hours ago, it suddenly threw out the error below:

    docs/docs.go:11152:28: undefined: "github.com/swaggo/swag".Spec

    may i know how to get rid of this error? thank you.

  • swag init command not running

    swag init command not running

    Describe the bug Swag init is not working.

    To Reproduce Steps to reproduce the behavior:

    1. Extract swaggo/swag
    2. run swag init in the root folder Expected behavior Command:swag not found

    Screenshots If applicable, add screenshots to help explain your problem.

    Your swag version e.g. v1.2.0

    Desktop (please complete the following information):

    • Ubuntu
    • Mozilla

    Additional context Add any other context about the problem here.

  • Swag init no longer works after updating to 1.5.1

    Swag init no longer works after updating to 1.5.1

    Describe the bug Previously used Swaggo/Swag 1.5.0. No longer works after updating to 1.5.1. Getting the following output:

    2019/07/01 10:31:18 Generate swagger docs....
    2019/07/01 10:31:18 Generate general API Info
    2019/07/01 10:31:18 execute go list command, exit status 1
    

    To Reproduce Not entirely sure. Using a standard layout with cmd, pkg and internal folders. Running swag init from project root folder.

    Steps to reproduce the behavior:

    1. Use swag 1.5.1
    2. Run swag init.

    Expected behavior Swag generates swagger docs in docs-folder.

    Your swag version 1.5.1

    Your go version 1.12.6

  • Doesn't working with import alias for struct fields

    Doesn't working with import alias for struct fields

    Describe the bug When we add import alias for custom type of struct field with this custom type that is not working.

    To Reproduce Put the struct with custom type from other package and add alias for this custom type:

    package build
    
    import (
           	domainapp "domain/application"
    )
    
    type ListResponse struct {
    	BuildInfos []domainapp.BuildInfo `json:"data"`
    	Err        error                 `json:"-"`
    }
    

    And some handler with comment

    // @Success 200 {object} build.ListResponse
    

    Run yaml:

    swag init -g ./main.go --parseDependency --parseVendor
    

    Result:

    build.ListResponse:
        properties:
          data:
            type: string
        type: object
    

    Expected behavior Expected result yaml:

    build.ListResponse:
        properties:
          data:
            items:
              $ref: '#/definitions/application.BuildInfo'
            type: array
        type: object
    

    Your swag version swag version v1.6.2

    Your go version go version go1.12.5 linux/amd64

  • swag init --parseDependency is throwing negative shift amount or interface conversion error

    swag init --parseDependency is throwing negative shift amount or interface conversion error

    Describe the bug Recently when I tried to use swag init --parseDependency, I got 2 different errors - "runtime error: negative shift amount" and "interface conversion: interface {} is a string, not int". Both the errors are throwing at .evaluateConstValue in package.go

    I tried creating a separate small project and while initializing I got the similar issue but intermittently (not getting repeatedly)

    To Reproduce Steps to reproduce the behavior:

    1. Create a package that has a function that calls interface
       For Example: func BindContextandResetBindContext(c echo.Context, i interface{}) error {
    }
    
    1. Use this package in swagger params For Example: @Failure 400 {object} httputil.HTTPError Above function is implemented in httputil module,

    Screenshots image

    image

    Your swag version v1.8.1

    Your go version 1.19.1

    Desktop (please complete the following information):

    • OS: Windows

    Additional context I am currently using Swaggo with Echo Framework

  • Cannot update to 1.6.6: checksum mismatch

    Cannot update to 1.6.6: checksum mismatch

    Describe the bug I can't update to version 1.6.6.

    To Reproduce

    go get -u github.com/swaggo/swag
    

    will return the following error message:

    go: downloading github.com/swaggo/swag v1.6.6
    verifying github.com/swaggo/[email protected]: checksum mismatch
            downloaded: h1:ujSziE+CfBxr5eIsVJgjGNbDxq1zPfLHxlu5NJmRFSQ=
            sum.golang.org: h1:3YX5hmuUyCMT/OqqnjW92gULAfHg3hVjpcPm53N64RY=
    
    SECURITY ERROR
    This download does NOT match the one reported by the checksum server.
    The bits may have been replaced on the origin server, or an attacker may
    have intercepted the download attempt.
    
    For more information, see 'go help module-auth'.
    

    Expected behavior

    Package updates without issues.

    Your swag version 1.6.6

    Your go version go version go1.13.5 linux/amd64

  • Can't install swag

    Can't install swag

    Describe the bug I'm unable to install swag given the instructions on the README

    To Reproduce Steps to reproduce the behavior:

    1. Execute go get github.com/swaggo/swag/cmd/swag on the command line
    2. See the following error:
    go get github.com/swaggo/swag/cmd/swag
    # github.com/ghodss/yaml
    ./yaml.go:102:28: undefined: yaml.UnmarshalStrict
    
    1. Try to run swag
    2. See the following error:
    zsh: command not found: swag
    

    Expected behavior swag should be installed properly on my machine.

    Desktop (please complete the following information):

    • OS: macOS High Sierra
    • Version: go version go1.10.3 darwin/amd64

    @pei0804

  • Version 1.6.9 - cannot find type definition

    Version 1.6.9 - cannot find type definition

    Go version : 1.15.2 (1.15.3 gives installation error) Swag version: 1.6.9

    Error : ParseComment error in file app/services/api/v1/models.go :cannot find type definition: models.ResponseType

    Import: import models "rest-api/app/models/api/v1"

    Usage : // @Failure 400 {object} models.ResponseType

    This works fine on version 1.6.8.

  • Alias typecould not resolve

    Alias typecould not resolve

    Describe the bug Resolver error at paths./ad/all.get.responses.200.schema.items.properties.status.$ref Could not resolve reference because of: Could not resolve pointer: /definitions/web.T does not exist in document

    To Reproduce

    // APIError example
    type APIError struct {
    	ErrorCode    int
    	ErrorMessage string
    	CreatedAt    time.Time
    	Type         APIType
    }
    type T uint8
    
    type APIType 
    

    Expected behavior generate

    "web.T": {
                "type": "integer"
            },
    

    Your swag version 1.6.5

    Your go version go1.13.5 darwin/amd64

    Desktop (please complete the following information):

    • OS: macOS 10.15.4
  • Docs generations doesn't work

    Docs generations doesn't work

    Describe the bug I'm using a non-common scaffolding for my project. Where everything is separated by entities. With this, the entrypoint is in one place and the controller in another.

    Something like this:

    projectRoot:
      - cmd:
          - main.go
      - internal:
          - app:
              - infra:
                 # The Routes declaration (Gin) And the general info declaration
                  - routes.go 
              - app.go
          - entityFoo:
              - infra:
                  - http:
                     # The controller of the route (Gin Handler)
                      - controller.go 
    

    To Reproduce Steps to reproduce the behavior:

    1. Use swag init -g .\internal\server\infra\routes.go. Only parse that specific file. Of course because the controller doesn't belong to the "infra" module.
    2. Use the -d to add the directory. swag init -g .\internal\server\infra\routes.go -d .\internal\entityFoo\infra\http
    3. See the error
    Generate swagger docs....
    Generate general API Info, search dir:.\internal\entityFoo\infra\http\
    cannot parse source files ~\internal\entityFoo\infra\http\internal\server\infra\routes.go: 
    open ~\internal\entityFoo\infra\http\internal\server\infra\routes.go: The system cannot find the path specified.
    
    1. See error

    Expected behavior I expect the swag parses the routes.go as General Info and then parse the additional directory.

    Your swag version v1.8.9

    Your go version 1.19

    Desktop:

    • Windows 10.

    Additional context I don't understand why swag concatenates the two paths. But if I trick this like swag init -g .\internal\server\infra\routes.go -d .\,.\internal\entityFoo\infra\http\. It works only for the General Info but not for the Controller.

  • Error while generic type not explicitly declared in code: cannot find type definition

    Error while generic type not explicitly declared in code: cannot find type definition

    Describe the bug Got error cannot find type definition, while generic type is not explicitly declared To Reproduce Steps to reproduce the behavior:

    // Got a generic function
    func NewSvResponse[T interface{}](body T) *SvResponse[T] {
    	return &SvResponse[T]{Body: body, Code: "200"}
    }
    
    // Got error : cannot find type definition, while model.Enterprise is not explicitly declared in code
    // @BasePath /enterprise
    // @Summary Create Enterprise
    // @Schemes
    // @Description Create Enterprise
    // @Tags        enterprise
    // @Accept      json
    // @Produce     json
    // @Param       req body     requests.EnterpriseCreateRequest true "req"
    // @Success     200 {object} responses.SvResponse[model.Enterprise]
    // @Router      /create [post]
    func (c *EnterpriseController) Create(ctx *gin.Context) {
             ret := service.BuildEnterprise()  
     	ctx.JSON(http.StatusOK, responses.NewSvResponse(ret))
    }
    
    //  Everything runs well while model.Enterprise is explicitly declared in code
    // @BasePath /enterprise
    // @Summary Create Enterprise
    // @Schemes
    // @Description Create Enterprise
    // @Tags        enterprise
    // @Accept      json
    // @Produce     json
    // @Param       req body     requests.EnterpriseCreateRequest true "req"
    // @Success     200 {object} responses.SvResponse[model.Enterprise]
    // @Router      /create [post]
    func (c *EnterpriseController) Create(ctx *gin.Context) {
            ret := service.BuildEnterprise()  
     	ctx.JSON(http.StatusOK, responses.NewSvResponse[*model.Enterprise](ret))
    }
    

    Expected behavior Generic type should have been parsed correctly

    Your swag version 1.8.9

    Your go version 1.18.9

    Desktop (please complete the following information):

    • OS: MacOs Big Sur version 11.4
  • 'Missing required param comment parameters' on external library that not I need

    'Missing required param comment parameters' on external library that not I need

    I'm trying to create swagger using Swaggo with command

    swag init --parseDependency (I have struct on shared library so I have to use this option)

    unfortunately, I got this error Screenshot_20221222_050546

    Is there any option better than I copy the struct to my project? How to use exclude the library?

    thank you

    Hope it goes well normally

    swag version is v1.8.9 go version is v1.19

  • A way to explicitly include a struct into a definition

    A way to explicitly include a struct into a definition

    Is your feature request related to a problem? Please describe. Is there a way to include a struct into a definition even if it is not mentioned in any controller description? I have an interface{} property in a model, and I would like to include a number of specific structs into a definition for that property, so they can be used from a client side afterwards.

    Describe the solution you'd like Something similat to https://goswagger.io/use/spec/model.html maybe.

    Describe alternatives you've considered An alternative would ne to add them manually but this is hard when the amount of models is large.

  • Added file data type

    Added file data type

    The file data type will add the file input to the swagger ui when making a form data request with a file

    Describe the PR e.g. add cool parser.

    Relation issue e.g. https://github.com/swaggo/swag/pull/118/files

    Additional context Add any other context about the problem here.

Generate code for any language, with any language.

gocog - generate code for any language, with any language gocog v1.0 build 20130206 Binaries for popular OSes are available on the Downloads page of t

Aug 5, 2022
GAPID: Graphics API Debugger
GAPID: Graphics API Debugger

GAPID: Graphics API Debugger

Dec 24, 2022
Template project to get started with a simple API skeleton in Go and Docker

A template project to create a Docker image for a Go application. The example application exposes an HTTP endpoint through a REST API packaged as a static binary.

Apr 4, 2022
đŸ§Ŧ fiber middleware to automatically generate RESTful API documentation with Swagger

Swagger fiber middleware to automatically generate RESTful API documentation with Swagger Usage Add comments to your API source code, See Declarative

Jan 1, 2023
crud is a cobra based CLI utility which helps in scaffolding a simple go based micro-service along with build scripts, api documentation, micro-service documentation and k8s deployment manifests

crud crud is a CLI utility which helps in scaffolding a simple go based micro-service along with build scripts, api documentation, micro-service docum

Nov 29, 2021
Swagger-go-chi - Generate a go-chi server from swagger

swagger-go-chi Install go install github.com/cugu/swagger-go-chi@main Run swagge

Nov 5, 2022
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger

Swagger + Gin = SwaGin Introduction SwaGin is a web framework based on Gin and Swagger, which wraps Gin and provides built-in swagger api docs and req

Dec 30, 2022
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger

Swagger + Gin = SwaGin Introduction SwaGin is a web framework based on Gin and Swagger, which wraps Gin and provides built-in swagger api docs and req

Dec 30, 2022
📖 Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.
📖 Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.

?? Tutorial: Build a RESTful API on Go Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers. ?? The full article is published on Marc

Dec 27, 2022
An example repo for RESTful API with swagger docs & unit testing

go REST API An example repo for RESTful API with swagger docs & unit testing Starting development server Copy .env.example to .env in the same directo

Nov 5, 2021
RESTful-JSON-API - RESTful-JSON-API using Go

RESTful-JSON-API using Go This basic REST-API principle establishes a one-to-one

Feb 15, 2022
Utilities to generate (reference) documentation for the docker CLI

About This is a library containing utilities to generate (reference) documentation for the docker CLI on docs.docker.com. Disclaimer This library is i

Dec 28, 2022
go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface

go-whatsapp-rest-API go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface Multi-devices (MD) Support. This ver

Dec 15, 2022
CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger
CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API Server of Clean Architecture Go(echo) gorm mysql docker swagger build docker-compose up -d --build API Postman and Fiddler is recommended to

May 14, 2022
CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger
CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API Server of Clean Architecture Go(echo) gorm mysql docker swagger build docker-compose up -d --build API Postman and Fiddler is recommended to

May 30, 2021
Go WhatsApp REST API Implementation Using Fiber And Swagger
Go WhatsApp REST API Implementation Using Fiber And Swagger

Go WhatsApp REST API Implementation Using Fiber And Swagger Package cooljar/go-whatsapp-fiber Implements the WhatsApp Web API using Fiber web framewor

May 9, 2022
generated go client for grafanas http api, based on swagger-codegen

Go API client for go_client The Grafana backend exposes an HTTP API, the same API is used by the frontend to do everything from saving dashboards, cre

Dec 2, 2021
A Go API project using Beego(Go Framework) with Swagger UI

Beego_API_with_swagger_UI Descriptions This is a Go API project using Beego(Go F

Dec 20, 2021
Godaddy-domains-client-go - Godaddy domains api Client golang - Write automaticly from swagger codegen

Go API client for swagger Overview This API client was generated by the swagger-codegen project. By using the swagger-spec from a remote server, you c

Jan 9, 2022