Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

molior-dbs/golang-github-swaggo-swag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

🌍English简体中文Português

Build StatusCoverage StatusGo Report Cardcodebeat badgeGo DocBackers on Open CollectiveSponsors on Open CollectiveFOSSA StatusRelease

Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popularGo 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, SeeDeclarative Comments Format.

  2. Install swag by using:

go install github.com/swaggo/swag/cmd/swag@latest

To build from source you needGo (1.18 or newer).

Alternatively you can run the docker image:

docker run --rm -v$(pwd):/code ghcr.io/swaggo/swag:latest

Or download a pre-compiled binary from therelease page.

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

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

import _"example-module-name/docs"
swag init -g http/api.go
  1. (optional) Useswag fmt format the SWAG comment. (Please upgrade to the latest version)
swag fmt

swag cli

swag init -hNAME:   swag init - Create docs.goUSAGE:   swag init [command options] [arguments...]OPTIONS:   --quiet, -q                            Make the logger quiet. (default: false)   --generalInfo value, -g value          Go file pathin which'swagger general API Info' is written (default:"main.go")   --dir value, -d value                  Directories you want to parse,comma separated and general-info file must bein the first one (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 directoryfor all the generated files(swagger.json, swagger.yaml and docs.go) (default:"./docs")   --outputTypes value, --ot value        Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml (default:"go,json,yaml")   --parseVendor                          Parse go filesin'vendor' folder, disabled by default (default: false)   --parseDependency, --pd                Parse go files inside 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 usefor the x-codeSamples extension, disabled by default   --parseInternal                        Parse go filesin 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)   --requiredByDefault                    Set validation requiredfor all fields by default (default: false)   --instanceName value                   This parameter can be used to name different swagger document instances. It is optional.   --overridesFile value                  File toread globaltype overrides from. (default:".swaggo")   --parseGoList                          Parse dependency via'go list' (default: true)   --tags value, -t value                 A comma-separated list of tags to filter the APIsfor which the documentation is generated.Specialcaseif the tag is prefixed with the'!' characterthen the APIs with that tag will be excluded   --templateDelims value, --td value     Provide custom delimetersfor Go template generation. The format is leftDelim,rightDelim. For example:"[[,]]"   --collectionFormat value, --cf value   Set default collection format (default:"csv")   --state value                          Initial stateforthe state machine (default:""), @HostStatein root file, @Statein other files   --help, -h                             showhelp (default: false)
swag fmt -hNAME:   swag fmt - format swag commentsUSAGE:   swag fmt [command options] [arguments...]OPTIONS:   --dir value, -d value          Directories you want to parse,comma separated and general-info file must bein the first one (default:"./")   --exclude value                Exclude directories and files when searching, comma separated   --generalInfo value, -g value  Go file pathin which'swagger general API Info' is written (default:"main.go")   --help, -h                     showhelp (default: false)

Supported Web Frameworks

How to use it with Gin

Find the example source codehere.

Finish the steps inGetting started

  1. After usingswag init to generate Swagger 2.0 docs, import the following packages:
import"github.com/swaggo/gin-swagger"// gin-swagger middlewareimport"github.com/swaggo/files"// swagger embed files
  1. AddGeneral API annotations inmain.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  support@swagger.io// @license.name  Apache 2.0// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html// @host      localhost:8080// @BasePath  /api/v1// @securityDefinitions.basic  BasicAuth// @externalDocs.description  OpenAPI// @externalDocs.url          https://swagger.io/resources/open-api/funcmain() {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 packagedocs exportsSwaggerInfo variable which we can use to set the title, description, version, host and base path programmatically. Example using Gin:

package mainimport ("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  support@swagger.io// @license.name  Apache 2.0// @license.url   http://www.apache.org/licenses/LICENSE-2.0.htmlfuncmain() {// programmatically set swagger infodocs.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 docsr.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))r.Run()}
  1. AddAPI Operation annotations incontroller code
package controllerimport ("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 an account// @Description  get string by ID// @Tags         accounts// @Accept       json// @Produce      json// @Param        id   path      int  true  "Account ID"// @Success      200  {object}  model.Account// @Failure      400  {object}  httputil.HTTPError// @Failure      404  {object}  httputil.HTTPError// @Failure      500  {object}  httputil.HTTPError// @Router       /accounts/{id} [get]func (c*Controller)ShowAccount(ctx*gin.Context) {id:=ctx.Param("id")aid,err:=strconv.Atoi(id)iferr!=nil {httputil.NewError(ctx,http.StatusBadRequest,err)return  }account,err:=model.AccountOne(aid)iferr!=nil {httputil.NewError(ctx,http.StatusNotFound,err)return  }ctx.JSON(http.StatusOK,account)}// ListAccounts godoc// @Summary      List accounts// @Description  get accounts// @Tags         accounts// @Accept       json// @Produce      json// @Param        q    query     string  false  "name search by q"  Format(email)// @Success      200  {array}   model.Account// @Failure      400  {object}  httputil.HTTPError// @Failure      404  {object}  httputil.HTTPError// @Failure      500  {object}  httputil.HTTPError// @Router       /accounts [get]func (c*Controller)ListAccounts(ctx*gin.Context) {q:=ctx.Request.URL.Query().Get("q")accounts,err:=model.AccountsAll(q)iferr!=nil {httputil.NewError(ctx,http.StatusNotFound,err)return  }ctx.JSON(http.StatusOK,accounts)}//...
swag init
  1. Run your app, and browse tohttp://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:

swagger_index.html

The swag formatter

The Swag Comments can be automatically formatted, just like 'go fmt'.Find the result of formattinghere.

Usage:

swag fmt

Exclude folder:

swag fmt -d ./ --exclude ./internal

When usingswag fmt, you need to ensure that you have a doc comment for the function to ensure correct formatting.This is due toswag fmt indenting swag comments with tabs, which is only allowedafter a standard doc comment.

For example, use

// ListAccounts lists all existing accounts////  @Summary      List accounts//  @Description  get accounts//  @Tags         accounts//  @Accept       json//  @Produce      json//  @Param        q    query     string  false  "name search by q"  Format(email)//  @Success      200  {array}   model.Account//  @Failure      400  {object}  httputil.HTTPError//  @Failure      404  {object}  httputil.HTTPError//  @Failure      500  {object}  httputil.HTTPError//  @Router       /accounts [get]func (c*Controller)ListAccounts(ctx*gin.Context) {

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

Exampleceller/main.go

annotationdescriptionexample
titleRequired. The title of the application.// @title Swagger Example API
versionRequired. Provides the version of the application API.// @version 1.0
descriptionA short description of the application.// @description This is a sample server celler server.
tag.nameName of a tag.// @tag.name This is the name of the tag
tag.descriptionDescription of the tag// @tag.description Cool Description
tag.docs.urlUrl of the external Documentation of the tag// @tag.docs.urlhttps://example.com
tag.docs.descriptionDescription of the external Documentation of the tag// @tag.docs.description Best example documentation
termsOfServiceThe Terms of Service for the API.// @termsOfServicehttp://swagger.io/terms/
contact.nameThe contact information for the exposed API.// @contact.name API Support
contact.urlThe URL pointing to the contact information. MUST be in the format of a URL.// @contact.urlhttp://www.swagger.io/support
contact.emailThe email address of the contact person/organization. MUST be in the format of an email address.// @contact.emailsupport@swagger.io
license.nameRequired. The license name used for the API.// @license.name Apache 2.0
license.urlA URL to the license used for the API. MUST be in the format of a URL.// @license.urlhttp://www.apache.org/licenses/LICENSE-2.0.html
hostThe host (name or ip) serving the API.// @host localhost:8080
BasePathThe base path on which the API is served.// @BasePath /api/v1
acceptA list of MIME types the APIs can consume. Note that Accept only affects operations with a request body, such as POST, PUT and PATCH. Value MUST be as described underMime Types.// @accept json
produceA list of MIME types the APIs can produce. Value MUST be as described underMime Types.// @produce json
query.collection.formatThe default collection(array) param format in query,enums:csv,multi,pipes,tsv,ssv. If not set, csv is the default.// @query.collection.format multi
schemesThe transfer protocol for the operation that separated by spaces.// @schemes http https
externalDocs.descriptionDescription of the external document.// @externalDocs.description OpenAPI
externalDocs.urlURL of the external document.// @externalDocs.urlhttps://swagger.io/resources/open-api/
x-nameThe 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.

annotationdescriptionexample
titleRequired. The title of the application.// @title Swagger Example API
versionRequired. Provides the version of the application API.// @version 1.0
description.markdownA 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.nameName of a tag.// @tag.name This is the name of the tag
tag.description.markdownDescription 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

Exampleceller/controller

annotationdescription
descriptionA verbose explanation of the operation behavior.
description.markdownA short description of the application. The description will be read from a file. E.g.@description.markdown details will loaddetails.md
idA unique string used to identify the operation. Must be unique among all API operations.
tagsA list of tags to each API operation that separated by commas.
summaryA short summary of what the operation does.
acceptA list of MIME types the APIs can consume. Note that Accept only affects operations with a request body, such as POST, PUT and PATCH. Value MUST be as described underMime Types.
produceA list of MIME types the APIs can produce. Value MUST be as described underMime Types.
paramParameters that separated by spaces.param name,param type,data type,is mandatory?,commentattribute(optional)
securitySecurity to each API operation.
successSuccess response that separated by spaces.return code or default,{param type},data type,comment
failureFailure response that separated by spaces.return code or default,{param type},data type,comment
responseAs same assuccess andfailure
headerHeader in response that separated by spaces.return code,{param type},data type,comment
routerPath definition that separated by spaces.path,[httpMethod]
deprecatedrouterAs same as router, but deprecated.
x-nameThe extension key, must be start by x- and take only json value.
x-codeSampleOptional Markdown usage. takefile as parameter. This will then search for a file named like the summary in the given folder.
deprecatedMark 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:

AliasMIME Type
jsonapplication/json
xmltext/xml
plaintext/plain
htmltext/html
mpfdmultipart/form-data
x-www-form-urlencodedapplication/x-www-form-urlencoded
json-apiapplication/vnd.api+json
json-streamapplication/x-json-stream
octet-streamapplication/octet-stream
pngimage/png
jpegimage/jpeg
gifimage/gif

Param Type

  • query
  • path
  • header
  • body
  • formData

Data Type

  • string (string)
  • integer (int, uint, uint32, uint64)
  • number (float32)
  • boolean (bool)
  • file (param data type when uploading)
  • user defined struct

Security

annotationdescriptionparametersexample
securitydefinitions.basicBasic auth.// @securityDefinitions.basic BasicAuth
securitydefinitions.apikeyAPI key auth.in, name, description// @securityDefinitions.apikey ApiKeyAuth
securitydefinitions.oauth2.applicationOAuth2 application auth.tokenUrl, scope, description// @securitydefinitions.oauth2.application OAuth2Application
securitydefinitions.oauth2.implicitOAuth2 implicit auth.authorizationUrl, scope, description// @securitydefinitions.oauth2.implicit OAuth2Implicit
securitydefinitions.oauth2.passwordOAuth2 password auth.tokenUrl, scope, description// @securitydefinitions.oauth2.password OAuth2Password
securitydefinitions.oauth2.accessCodeOAuth2 access code auth.tokenUrl, authorizationUrl, scope, description// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
parameters annotationexample
in// @in header
name// @name Authorization
tokenUrl// @tokenUrlhttps://example.com/oauth/token
authorizationurl// @authorizationurlhttps://example.com/oauth/authorize
scope.hoge// @scope.write Grants write access
description// @description OAuth protects our entity endpoints

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   example     query     string     false  "string example"     example(string)// @Param   collection  query     []string   false  "string collection"  collectionFormat(multi)// @Param   extensions  query     []string   false  "string collection"  extensions(x-example=test,x-nullable)

It also works for the struct fields:

typeFoostruct {Barstring`minLength:"4" maxLength:"16" example:"random string"`Bazint`minimum:"10" maximum:"20" default:"15"`Qux []string`enums:"foo,bar,baz"`}

Available

Field NameTypeDescription
validatestringDetermines the validation for the parameter. Possible values are:required,optional.
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.) Seehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the definedtype for this parameter.
maximumnumberSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimumnumberSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
multipleOfnumberSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
maxLengthintegerSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLengthintegerSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
enums[*]Seehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
formatstringThe extending format for the previously mentionedtype. SeeData Type Formats for further details.
collectionFormatstringDetermines the format of the array if type array is used. Possible values are:
  • csv - comma separated valuesfoo,bar.
  • ssv - space separated valuesfoo bar.
  • tsv - tab separated valuesfoo\tbar.
  • pipes - pipe separated valuesfoo|bar.
  • multi - corresponds to multiple parameter instances instead of multiple values for a single instancefoo=bar&foo=baz. This is valid only for parametersin "query" or "formData".
Default value iscsv.
example*Declares the example for the parameter value
extensionsstringAdd extension to parameters.

Future

Field NameTypeDescription
patternstringSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItemsintegerSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItemsintegerSeehttps://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItemsbooleanSeehttps://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 modeltypeAccountstruct {IDint`json:"id" example:"1"`Namestring`json:"name" example:"account name"`}

Function scoped struct declaration

You can declare your request response structs inside a function body.You must have to follow the naming convention<package-name>.<function-name>.<struct-name>.

package main// @Param request body main.MyHandler.request true "query params"// @Success 200 {object} main.MyHandler.response// @Router /test [post]funcMyHandler() {typerequeststruct {RequestFieldstring}typeresponsestruct {ResponseFieldstring}}

Model composition in response

// JSONResult's data field will be overridden by the specific type proto.Order@success200 {object} jsonresult.JSONResult{data=proto.Order}"desc"
typeJSONResultstruct {Codeint`json:"code" `Messagestring`json:"message"`Datainterface{}`json:"data"`}typeOrderstruct {//in `proto` packageIduint`json:"id"`Datainterface{}`json:"data"`}
  • also support array of objects and primitive types as nested response
@success200 {object} jsonresult.JSONResult{data=[]proto.Order}"desc"@success200 {object} jsonresult.JSONResult{data=string}"desc"@success200 {object} jsonresult.JSONResult{data=[]string}"desc"
  • overriding multiple fields. field will be added if not exists
@success200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order}"desc"
  • overriding deep-level fields
typeDeepObjectstruct {//in `proto` package...}@success200 {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]

Add multiple paths

/// ...// @Param group_id path int true "Group ID"// @Param user_id  path int true "User ID"// ...// @Router /examples/groups/{group_id}/user/{user_id}/address [put]// @Router /examples/user/{user_id}/address [put]

Example value of struct

typeAccountstruct {IDint`json:"id" example:"1"`Namestring`json:"name" example:"account name"`PhotoUrls []string`json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`}

SchemaExample of body

// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)

Description of struct

// Account model info// @Description User account information// @Description with user id and usernametypeAccountstruct {// ID this is useridIDint`json:"id"`Namestring`json:"name"`// This is Name}

#708 The parser handles only struct comments starting with@Description attribute.But it writes all struct field comments as is.

So, generated swagger doc as follows:

"Account": {"type":"object","description":"User account information with user id and username""properties": {"id": {"type":"integer","description":"ID this is userid"    },"name": {"type":"string","description":"This is Name"    }  }}

Use swaggertype tag to supported custom type

#201

typeTimestampTimestruct {    time.Time}///implement encoding.JSON.Marshaler interfacefunc (t*TimestampTime)MarshalJSON() ([]byte,error) {bin:=make([]byte,16)bin=strconv.AppendInt(bin[:0],t.Time.Unix(),10)returnbin,nil}func (t*TimestampTime)UnmarshalJSON(bin []byte)error {v,err:=strconv.ParseInt(string(bin),10,64)iferr!=nil {returnerr    }t.Time=time.Unix(v,0)returnnil}///typeAccountstruct {// Override primitive type by simply specifying it via `swaggertype` tagID     sql.NullInt64`json:"id" swaggertype:"integer"`// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tagRegisterTimeTimestampTime`json:"register_time" swaggertype:"primitive,integer"`// Array types can be overridden using "array,<prim_type>" formatCoeffs []big.Float`json:"coeffs" swaggertype:"array,number"`}

#379

typeCerticateKeyPairstruct {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 global overrides to support a custom type

If you are using generated files, theswaggertype orswaggerignore tags may not be possible.

By passing a mapping to swag with--overridesFile you can tell swag to use one type in place of another wherever it appears. By default, if a.swaggo file is present in the current directory it will be used.

Go code:

typeMyStructstruct {ID     sql.NullInt64`json:"id"`Name   sql.NullString`json:"name"`}

.swaggo:

// Replace all NullInt64 with intreplace database/sql.NullInt64 int// Don't include any fields of type database/sql.NullString in the swagger docsskip    database/sql.NullString

Possible directives are comments (beginning with//),replace path/to/a.type path/to/b.type, andskip path/to/a.type.

(Note that the full paths to any named types must be provided to prevent problems when multiple packages define a type with the same name)

Rendered:

"types.MyStruct": {"id":"integer"}

Use swaggerignore tag to exclude a field

typeAccountstruct {IDstring`json:"id"`Namestring`json:"name"`Ignoredint`swaggerignore:"true"`}

Add extension info to struct field

typeAccountstruct {IDstring`json:"id"   extensions:"x-nullable,x-abc=def,!x-omitempty"`// extensions fields must start with "x-"}

generate swagger doc as follows:

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

Rename model to display

typeRespstruct {Codeint}//@name Response

How to use 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]

Make it OR condition

// @Security ApiKeyAuth || firebase// @Security OAuth2Application[write, admin] || APIKeyAuth

Add a description for enum items

typeExamplestruct {// Sort order:// * asc - Ascending, from A to Z.// * desc - Descending, from Z to A.Orderstring`enums:"asc,desc"`}

Generate only specific docs file types

By defaultswag command generates Swagger specification in three different files/file types:

  • docs.go
  • swagger.json
  • swagger.yaml

If you would like to limit a set of file types which should be generated you can use--outputTypes (short-ot) flag. Default value isgo,json,yaml - output types separated with comma. To limit output only togo andyaml files, you would writego,yaml. With complete command that would beswag init --outputTypes go,yaml.

How to use Generics

// @Success 200 {object} web.GenericNestedResponse[types.Post]// @Success 204 {object} web.GenericNestedResponse[types.Post, Types.AnotherOne]// @Success 201 {object} web.GenericNestedResponse[web.GenericInnerType[types.Post]]funcGetPosts(w http.ResponseWriter,r*http.Request) {_= web.GenericNestedResponse[types.Post]{}}

Seethis file for more detailsand other examples.

Change the default Go Template action delimiters

#980#1177

If your swagger annotations or struct fields contain "{{" or "}}", the template generation will most likely fail, as these are the default delimiters forgo templates.

To make the generation work properly, you can change the default delimiters with-td. For example:

swag init -g http/api.go -td "[[,]]"

The new delimiter is a string with the format "<left delimiter>,<right delimiter>".

About the Project

This project was inspired byyvasiyarov/swagger but we simplified the usage and added support a variety ofweb frameworks. Gopher image source istenntenn/gopher-stickers. It has licensescreative 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

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors202

Languages


[8]ページ先頭

©2009-2025 Movatter.jp