• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H25-Oct-2021-

assets/H03-May-2022-

cmd/swag/H25-Oct-2021-

example/H25-Oct-2021-

gen/H25-Oct-2021-

testdata/H25-Oct-2021-

.gitignoreH A D25-Oct-2021300

.goreleaser.ymlH A D25-Oct-2021475

CODE_OF_CONDUCT.mdH A D25-Oct-20213.2 KiB

CONTRIBUTING.mdH A D25-Oct-2021613

DockerfileH A D25-Oct-2021779

MakefileH A D25-Oct-20212 KiB

PULL_REQUEST_TEMPLATE.mdH A D25-Oct-2021183

README.mdH A D25-Oct-202134.2 KiB

README_zh-CN.mdH A D25-Oct-202136.5 KiB

doc.goH A D25-Oct-2021189

go.modH A D25-Oct-2021331

go.sumH A D25-Oct-20219.3 KiB

licenseH A D25-Oct-20211 KiB

operation.goH A D25-Oct-202129.6 KiB

operation_test.goH A D25-Oct-202160.2 KiB

packages.goH A D25-Oct-20218.6 KiB

parser.goH A D25-Oct-202145.7 KiB

parser_test.goH A D25-Oct-202194.6 KiB

schema.goH A D25-Oct-20214.2 KiB

schema_test.goH A D25-Oct-20214.9 KiB

swagger.goH A D25-Oct-20211.2 KiB

swagger_test.goH A D25-Oct-20215.7 KiB

types.goH A D25-Oct-20211.4 KiB

version.goH A D25-Oct-202159

README.md

1# swag
2
3�� *[English](README.md) ∙ [简体中文](README_zh-CN.md)*
4
5<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
6
7[![Build Status](https://github.com/swaggo/swag/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/features/actions)
8[![Coverage Status](https://img.shields.io/codecov/c/github/swaggo/swag/master.svg)](https://codecov.io/gh/swaggo/swag)
9[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
10[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
11[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
12[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
13[![Sponsors on Open Collective](https://opencollective.com/swag/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
14[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)
15
16
17Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popular [Go web frameworks](#supported-web-frameworks). This allows you to quickly integrate with an existing Go project (using Swagger UI).
18
19## Contents
20 - [Getting started](#getting-started)
21 - [Supported Web Frameworks](#supported-web-frameworks)
22 - [How to use it with Gin](#how-to-use-it-with-gin)
23 - [Implementation Status](#implementation-status)
24 - [Declarative Comments Format](#declarative-comments-format)
25	- [General API Info](#general-api-info)
26	- [API Operation](#api-operation)
27	- [Security](#security)
28 - [Examples](#examples)
29	- [Descriptions over multiple lines](#descriptions-over-multiple-lines)
30	- [User defined structure with an array type](#user-defined-structure-with-an-array-type)
31	- [Model composition in response](#model-composition-in-response)
32	- [Add a headers in response](#add-a-headers-in-response)
33	- [Use multiple path params](#use-multiple-path-params)
34	- [Example value of struct](#example-value-of-struct)
35	- [Description of struct](#description-of-struct)
36	- [Use swaggertype tag to supported custom type](#use-swaggertype-tag-to-supported-custom-type)
37	- [Use swaggerignore tag to exclude a field](#use-swaggerignore-tag-to-exclude-a-field)
38	- [Add extension info to struct field](#add-extension-info-to-struct-field)
39	- [Rename model to display](#rename-model-to-display)
40	- [How to using security annotations](#how-to-using-security-annotations)
41	- [Add a description for enum items](#add-a-description-for-enum-items)
42- [About the Project](#about-the-project)
43
44## Getting started
45
461. Add comments to your API source code, See [Declarative Comments Format](#declarative-comments-format).
47
482. Download swag by using:
49```sh
50$ go get -u github.com/swaggo/swag/cmd/swag
51
52# 1.16 or newer
53$ go install github.com/swaggo/swag/cmd/swag@latest
54```
55To build from source you need [Go](https://golang.org/dl/) (1.13 or newer).
56
57Or download a pre-compiled binary from the [release page](https://github.com/swaggo/swag/releases).
58
593. 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`).
60```sh
61$ swag init
62```
63
64  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.
65  ```sh
66  swag init -g http/api.go
67  ```
68
69## swag cli
70
71```sh
72$ swag init -h
73NAME:
74   swag init - Create docs.go
75
76USAGE:
77   swag init [command options] [arguments...]
78
79OPTIONS:
80   --generalInfo value, -g value          Go file path in which 'swagger general API Info' is written (default: "main.go")
81   --dir value, -d value                  Directory you want to parse (default: "./")
82   --exclude value                        Exclude directories and files when searching, comma separated
83   --propertyStrategy value, -p value     Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
84   --output value, -o value               Output directory for all the generated files(swagger.json, swagger.yaml and doc.go) (default: "./docs")
85   --parseVendor                          Parse go files in 'vendor' folder, disabled by default (default: false)
86   --parseDependency                      Parse go files in outside dependency folder, disabled by default (default: false)
87   --markdownFiles value, --md value      Parse folder containing markdown files to use as description, disabled by default
88   --codeExampleFiles value, --cef value  Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
89   --parseInternal                        Parse go files in internal packages, disabled by default (default: false)
90   --generatedTime                        Generate timestamp at the top of docs.go, disabled by default (default: false)
91   --parseDepth value                     Dependency parse depth (default: 100)
92   --instanceName value                   Set the swagger document instance name (default: "swagger")
93   --help, -h                             show help (default: false)
94```
95
96## Supported Web Frameworks
97
98- [gin](http://github.com/swaggo/gin-swagger)
99- [echo](http://github.com/swaggo/echo-swagger)
100- [buffalo](https://github.com/swaggo/buffalo-swagger)
101- [net/http](https://github.com/swaggo/http-swagger)
102- [flamingo](https://github.com/i-love-flamingo/swagger)
103- [fiber](https://github.com/arsmn/fiber-swagger)
104- [atreugo](https://github.com/Nerzal/atreugo-swagger)
105
106## How to use it with Gin
107
108Find the example source code [here](https://github.com/swaggo/swag/tree/master/example/celler).
109
1101. After using `swag init` to generate Swagger 2.0 docs, import the following packages:
111```go
112import "github.com/swaggo/gin-swagger" // gin-swagger middleware
113import "github.com/swaggo/files" // swagger embed files
114```
115
1162. Add [General API](#general-api-info) annotations in `main.go` code:
117
118```go
119// @title Swagger Example API
120// @version 1.0
121// @description This is a sample server celler server.
122// @termsOfService http://swagger.io/terms/
123
124// @contact.name API Support
125// @contact.url http://www.swagger.io/support
126// @contact.email support@swagger.io
127
128// @license.name Apache 2.0
129// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
130
131// @host localhost:8080
132// @BasePath /api/v1
133// @query.collection.format multi
134
135// @securityDefinitions.basic BasicAuth
136
137// @securityDefinitions.apikey ApiKeyAuth
138// @in header
139// @name Authorization
140
141// @securitydefinitions.oauth2.application OAuth2Application
142// @tokenUrl https://example.com/oauth/token
143// @scope.write Grants write access
144// @scope.admin Grants read and write access to administrative information
145
146// @securitydefinitions.oauth2.implicit OAuth2Implicit
147// @authorizationurl https://example.com/oauth/authorize
148// @scope.write Grants write access
149// @scope.admin Grants read and write access to administrative information
150
151// @securitydefinitions.oauth2.password OAuth2Password
152// @tokenUrl https://example.com/oauth/token
153// @scope.read Grants read access
154// @scope.write Grants write access
155// @scope.admin Grants read and write access to administrative information
156
157// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
158// @tokenUrl https://example.com/oauth/token
159// @authorizationurl https://example.com/oauth/authorize
160// @scope.admin Grants read and write access to administrative information
161
162// @x-extension-openapi {"example": "value on a json format"}
163
164func main() {
165	r := gin.Default()
166
167	c := controller.NewController()
168
169	v1 := r.Group("/api/v1")
170	{
171		accounts := v1.Group("/accounts")
172		{
173			accounts.GET(":id", c.ShowAccount)
174			accounts.GET("", c.ListAccounts)
175			accounts.POST("", c.AddAccount)
176			accounts.DELETE(":id", c.DeleteAccount)
177			accounts.PATCH(":id", c.UpdateAccount)
178			accounts.POST(":id/images", c.UploadAccountImage)
179		}
180    //...
181	}
182	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
183	r.Run(":8080")
184}
185//...
186```
187
188Additionally 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:
189
190```go
191package main
192
193import (
194	"github.com/gin-gonic/gin"
195	"github.com/swaggo/files"
196	"github.com/swaggo/gin-swagger"
197
198	"./docs" // docs is generated by Swag CLI, you have to import it.
199)
200
201// @contact.name API Support
202// @contact.url http://www.swagger.io/support
203// @contact.email support@swagger.io
204
205// @license.name Apache 2.0
206// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
207
208// @termsOfService http://swagger.io/terms/
209
210func main() {
211
212	// programmatically set swagger info
213	docs.SwaggerInfo.Title = "Swagger Example API"
214	docs.SwaggerInfo.Description = "This is a sample server Petstore server."
215	docs.SwaggerInfo.Version = "1.0"
216	docs.SwaggerInfo.Host = "petstore.swagger.io"
217	docs.SwaggerInfo.BasePath = "/v2"
218	docs.SwaggerInfo.Schemes = []string{"http", "https"}
219
220	r := gin.New()
221
222	// use ginSwagger middleware to serve the API docs
223	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
224
225	r.Run()
226}
227```
228
2293. Add [API Operation](#api-operation) annotations in `controller` code
230
231``` go
232package controller
233
234import (
235	"fmt"
236	"net/http"
237	"strconv"
238
239	"github.com/gin-gonic/gin"
240	"github.com/swaggo/swag/example/celler/httputil"
241	"github.com/swaggo/swag/example/celler/model"
242)
243
244// ShowAccount godoc
245// @Summary Show a account
246// @Description get string by ID
247// @ID get-string-by-int
248// @Accept  json
249// @Produce  json
250// @Param id path int true "Account ID"
251// @Success 200 {object} model.Account
252// @Header 200 {string} Token "qwerty"
253// @Failure 400,404 {object} httputil.HTTPError
254// @Failure 500 {object} httputil.HTTPError
255// @Failure default {object} httputil.DefaultError
256// @Router /accounts/{id} [get]
257func (c *Controller) ShowAccount(ctx *gin.Context) {
258	id := ctx.Param("id")
259	aid, err := strconv.Atoi(id)
260	if err != nil {
261		httputil.NewError(ctx, http.StatusBadRequest, err)
262		return
263	}
264	account, err := model.AccountOne(aid)
265	if err != nil {
266		httputil.NewError(ctx, http.StatusNotFound, err)
267		return
268	}
269	ctx.JSON(http.StatusOK, account)
270}
271
272// ListAccounts godoc
273// @Summary List accounts
274// @Description get accounts
275// @Accept  json
276// @Produce  json
277// @Param q query string false "name search by q"
278// @Success 200 {array} model.Account
279// @Header 200 {string} Token "qwerty"
280// @Failure 400,404 {object} httputil.HTTPError
281// @Failure 500 {object} httputil.HTTPError
282// @Failure default {object} httputil.DefaultError
283// @Router /accounts [get]
284func (c *Controller) ListAccounts(ctx *gin.Context) {
285	q := ctx.Request.URL.Query().Get("q")
286	accounts, err := model.AccountsAll(q)
287	if err != nil {
288		httputil.NewError(ctx, http.StatusNotFound, err)
289		return
290	}
291	ctx.JSON(http.StatusOK, accounts)
292}
293
294//...
295```
296
297```console
298$ swag init
299```
300
3014. Run your app, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:
302
303![swagger_index.html](https://raw.githubusercontent.com/swaggo/swag/master/assets/swagger-image.png)
304
305## Implementation Status
306
307[Swagger 2.0 document](https://swagger.io/docs/specification/2-0/basic-structure/)
308
309- [x] Basic Structure
310- [x] API Host and Base Path
311- [x] Paths and Operations
312- [x] Describing Parameters
313- [x] Describing Request Body
314- [x] Describing Responses
315- [x] MIME Types
316- [x] Authentication
317  - [x] Basic Authentication
318  - [x] API Keys
319- [x] Adding Examples
320- [x] File Upload
321- [x] Enums
322- [x] Grouping Operations With Tags
323- [ ] Swagger Extensions
324
325# Declarative Comments Format
326
327## General API Info
328
329**Example**
330[celler/main.go](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
331
332| annotation  | description                                | example                         |
333|-------------|--------------------------------------------|---------------------------------|
334| title       | **Required.** The title of the application.| // @title Swagger Example API   |
335| version     | **Required.** Provides the version of the application API.| // @version 1.0  |
336| description | A short description of the application.    |// @description This is a sample server celler server.         																 |
337| tag.name    | Name of a tag.| // @tag.name This is the name of the tag                     |
338| tag.description   | Description of the tag  | // @tag.description Cool Description         |
339| tag.docs.url      | Url of the external Documentation of the tag | // @tag.docs.url https://example.com|
340| tag.docs.description  | Description of the external Documentation of the tag| // @tag.docs.description Best example documentation |
341| termsOfService | The Terms of Service for the API.| // @termsOfService http://swagger.io/terms/                     |
342| contact.name | The contact information for the exposed API.| // @contact.name API Support  |
343| contact.url  | The URL pointing to the contact information. MUST be in the format of a URL.  | // @contact.url http://www.swagger.io/support|
344| contact.email| The email address of the contact person/organization. MUST be in the format of an email address.| // @contact.email support@swagger.io                                   |
345| license.name | **Required.** The license name used for the API.|// @license.name Apache 2.0|
346| 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 |
347| host        | The host (name or ip) serving the API.     | // @host localhost:8080         |
348| BasePath    | The base path on which the API is served. | // @BasePath /api/v1             |
349| accept      | A 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 under [Mime Types](#mime-types).                     | // @accept json |
350| produce     | A list of MIME types the APIs can produce. Value MUST be as described under [Mime Types](#mime-types).                     | // @produce json |
351| 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
352| schemes     | The transfer protocol for the operation that separated by spaces. | // @schemes http https |
353| x-name      | The extension key, must be start by x- and take only json value | // @x-example-key {"key": "value"} |
354
355### Using markdown descriptions
356When 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.
357
358
359| annotation  | description                                | example                         |
360|-------------|--------------------------------------------|---------------------------------|
361| title       | **Required.** The title of the application.| // @title Swagger Example API   |
362| version     | **Required.** Provides the version of the application API.| // @version 1.0  |
363| 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         																 |
364| tag.name    | Name of a tag.| // @tag.name This is the name of the tag                     |
365| 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         |
366
367
368## API Operation
369
370**Example**
371[celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
372
373
374| annotation  | description                                                                                                                |
375|-------------|----------------------------------------------------------------------------------------------------------------------------|
376| description | A verbose explanation of the operation behavior.                                                                           |
377| description.markdown     |  A short description of the application. The description will be read from a file named like endpointname.md| // @description.file endpoint.description.markdown  |
378| id          | A unique string used to identify the operation. Must be unique among all API operations.                                   |
379| tags        | A list of tags to each API operation that separated by commas.                                                             |
380| summary     | A short summary of what the operation does.                                                                                |
381| accept      | A 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 under [Mime Types](#mime-types).                     |
382| produce     | A list of MIME types the APIs can produce. Value MUST be as described under [Mime Types](#mime-types).                     |
383| param       | Parameters that separated by spaces. `param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
384| security    | [Security](#security) to each API operation.                                                                               |
385| success     | Success response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment`                   |
386| failure     | Failure response that separated by spaces. `return code or default`,`{param type}`,`data type`,`comment`                    |
387| response    | As same as `success` and `failure` |
388| header      | Header in response that separated by spaces. `return code`,`{param type}`,`data type`,`comment`                            |
389| router      | Path definition that separated by spaces. `path`,`[httpMethod]`                                                            |
390| x-name      | The extension key, must be start by x- and take only json value.                                                           |
391| x-codeSample      | Optional Markdown usage. take `file` as parameter. This will then search for a file named like the summary in the given folder.                                      |
392| deprecated  | Mark endpoint as deprecated.                                                                                               |
393
394
395
396## Mime Types
397
398`swag` accepts all MIME Types which are in the correct format, that is, match `*/*`.
399Besides that, `swag` also accepts aliases for some MIME Types as follows:
400
401| Alias                 | MIME Type                         |
402|-----------------------|-----------------------------------|
403| json                  | application/json                  |
404| xml                   | text/xml                          |
405| plain                 | text/plain                        |
406| html                  | text/html                         |
407| mpfd                  | multipart/form-data               |
408| x-www-form-urlencoded | application/x-www-form-urlencoded |
409| json-api              | application/vnd.api+json          |
410| json-stream           | application/x-json-stream         |
411| octet-stream          | application/octet-stream          |
412| png                   | image/png                         |
413| jpeg                  | image/jpeg                        |
414| gif                   | image/gif                         |
415
416
417
418## Param Type
419
420- query
421- path
422- header
423- body
424- formData
425
426## Data Type
427
428- string (string)
429- integer (int, uint, uint32, uint64)
430- number (float32)
431- boolean (bool)
432- user defined struct
433
434## Security
435| annotation | description | parameters | example |
436|------------|-------------|------------|---------|
437| securitydefinitions.basic  | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth.  |                                   | // @securityDefinitions.basic BasicAuth                      |
438| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth.            | in, name                          | // @securityDefinitions.apikey ApiKeyAuth                    |
439| securitydefinitions.oauth2.application  | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth.       | tokenUrl, scope                   | // @securitydefinitions.oauth2.application OAuth2Application |
440| securitydefinitions.oauth2.implicit     | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth.          | authorizationUrl, scope           | // @securitydefinitions.oauth2.implicit OAuth2Implicit       |
441| securitydefinitions.oauth2.password     | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth.          | tokenUrl, scope                   | // @securitydefinitions.oauth2.password OAuth2Password       |
442| securitydefinitions.oauth2.accessCode   | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth.       | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode   |
443
444
445| parameters annotation | example                                                  |
446|-----------------------|----------------------------------------------------------|
447| in                    | // @in header                                            |
448| name                  | // @name Authorization                                   |
449| tokenUrl              | // @tokenUrl https://example.com/oauth/token             |
450| authorizationurl      | // @authorizationurl https://example.com/oauth/authorize |
451| scope.hoge            | // @scope.write Grants write access                      |
452
453
454## Attribute
455
456```go
457// @Param enumstring query string false "string enums" Enums(A, B, C)
458// @Param enumint query int false "int enums" Enums(1, 2, 3)
459// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
460// @Param string query string false "string valid" minlength(5) maxlength(10)
461// @Param int query int false "int valid" minimum(1) maximum(10)
462// @Param default query string false "string default" default(A)
463// @Param collection query []string false "string collection" collectionFormat(multi)
464// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
465
466```
467
468It also works for the struct fields:
469
470```go
471type Foo struct {
472    Bar string `minLength:"4" maxLength:"16"`
473    Baz int `minimum:"10" maximum:"20" default:"15"`
474    Qux []string `enums:"foo,bar,baz"`
475}
476```
477
478### Available
479
480Field Name | Type | Description
481---|:---:|---
482<a name="validate"></a>validate | `string` | 	Determines the validation for the parameter. Possible values are: `required`.
483<a name="parameterDefault"></a>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`](#parameterType) for this parameter.
484<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
485<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
486<a name="parameterMultipleOf"></a>multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
487<a name="parameterMaxLength"></a>maxLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
488<a name="parameterMinLength"></a>minLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
489<a name="parameterEnums"></a>enums | [\*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
490<a name="parameterFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) for further details.
491<a name="parameterCollectionFormat"></a>collectionFormat | `string` |Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo&#124;bar</code>. <li>`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`](#parameterIn) "query" or "formData". </ul> Default value is `csv`.
492<a name="parameterExtensions"></a>extensions | `string` | Add extension to parameters.
493
494### Future
495
496Field Name | Type | Description
497---|:---:|---
498<a name="parameterPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
499<a name="parameterMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
500<a name="parameterMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
501<a name="parameterUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.
502
503## Examples
504
505### Descriptions over multiple lines
506
507You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:
508
509```go
510// @description This is the first line
511// @description This is the second line
512// @description And so forth.
513```
514
515### User defined structure with an array type
516
517```go
518// @Success 200 {array} model.Account <-- This is a user defined struct.
519```
520
521```go
522package model
523
524type Account struct {
525    ID   int    `json:"id" example:"1"`
526    Name string `json:"name" example:"account name"`
527}
528```
529
530### Model composition in response
531```go
532// JSONResult's data field will be overridden by the specific type proto.Order
533@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
534```
535
536```go
537type JSONResult struct {
538    Code    int          `json:"code" `
539    Message string       `json:"message"`
540    Data    interface{}  `json:"data"`
541}
542
543type Order struct { //in `proto` package
544    Id  uint            `json:"id"`
545    Data  interface{}   `json:"data"`
546}
547```
548
549- also support array of objects and primitive types as nested response
550```go
551@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
552@success 200 {object} jsonresult.JSONResult{data=string} "desc"
553@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
554```
555
556- overriding multiple fields. field will be added if not exists
557```go
558@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
559```
560- overriding deep-level fields
561```go
562type DeepObject struct { //in `proto` package
563	...
564}
565@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"
566```
567### Add a headers in response
568
569```go
570// @Success 200 {string} string	"ok"
571// @failure 400 {string} string	"error"
572// @response default {string} string	"other error"
573// @Header 200 {string} Location "/entity/1"
574// @Header 200,400,default {string} Token "token"
575// @Header all {string} Token2 "token2"
576```
577
578### Use multiple path params
579
580```go
581/// ...
582// @Param group_id path int true "Group ID"
583// @Param account_id path int true "Account ID"
584// ...
585// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
586```
587
588### Add multiple paths
589
590```go
591/// ...
592// @Param group_id path int true "Group ID"
593// @Param user_id path int true "User ID"
594// ...
595// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
596// @Router /examples/user/{user_id}/address [put]
597```
598
599### Example value of struct
600
601```go
602type Account struct {
603    ID   int    `json:"id" example:"1"`
604    Name string `json:"name" example:"account name"`
605    PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
606}
607```
608
609### Description of struct
610
611```go
612type Account struct {
613	// ID this is userid
614	ID   int    `json:"id"`
615	Name string `json:"name"` // This is Name
616}
617```
618
619### Use swaggertype tag to supported custom type
620[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
621
622```go
623type TimestampTime struct {
624    time.Time
625}
626
627///implement encoding.JSON.Marshaler interface
628func (t *TimestampTime) MarshalJSON() ([]byte, error) {
629    bin := make([]byte, 16)
630    bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
631    return bin, nil
632}
633
634func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
635    v, err := strconv.ParseInt(string(bin), 10, 64)
636    if err != nil {
637        return err
638    }
639    t.Time = time.Unix(v, 0)
640    return nil
641}
642///
643
644type Account struct {
645    // Override primitive type by simply specifying it via `swaggertype` tag
646    ID     sql.NullInt64 `json:"id" swaggertype:"integer"`
647
648    // Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
649    RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
650
651    // Array types can be overridden using "array,<prim_type>" format
652    Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
653}
654```
655
656[#379](https://github.com/swaggo/swag/issues/379)
657```go
658type CerticateKeyPair struct {
659	Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
660	Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
661}
662```
663generated swagger doc as follows:
664```go
665"api.MyBinding": {
666  "type":"object",
667  "properties":{
668    "crt":{
669      "type":"string",
670      "format":"base64",
671      "example":"U3dhZ2dlciByb2Nrcw=="
672    },
673    "key":{
674      "type":"string",
675      "format":"base64",
676      "example":"U3dhZ2dlciByb2Nrcw=="
677    }
678  }
679}
680
681```
682
683
684### Use swaggerignore tag to exclude a field
685
686```go
687type Account struct {
688    ID   string    `json:"id"`
689    Name string     `json:"name"`
690    Ignored int     `swaggerignore:"true"`
691}
692```
693
694### Add extension info to struct field
695
696```go
697type Account struct {
698    ID   string    `json:"id"   extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
699}
700```
701
702generate swagger doc as follows:
703
704```go
705"Account": {
706    "type": "object",
707    "properties": {
708        "id": {
709            "type": "string",
710            "x-nullable": true,
711            "x-abc": "def",
712            "x-omitempty": false
713        }
714    }
715}
716```
717### Rename model to display
718
719```golang
720type Resp struct {
721	Code int
722}//@name Response
723```
724
725### How to using security annotations
726
727General API info.
728
729```go
730// @securityDefinitions.basic BasicAuth
731
732// @securitydefinitions.oauth2.application OAuth2Application
733// @tokenUrl https://example.com/oauth/token
734// @scope.write Grants write access
735// @scope.admin Grants read and write access to administrative information
736```
737
738Each API operation.
739
740```go
741// @Security ApiKeyAuth
742```
743
744Make it AND condition
745
746```go
747// @Security ApiKeyAuth
748// @Security OAuth2Application[write, admin]
749```
750
751### Add a description for enum items
752
753```go
754type Example struct {
755	// Sort order:
756	// * asc - Ascending, from A to Z.
757	// * desc - Descending, from Z to A.
758	Order string `enums:"asc,desc"`
759}
760```
761
762## About the Project
763This project was inspired by [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) but we simplified the usage and added support a variety of [web frameworks](#supported-web-frameworks). Gopher image source is [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). It has licenses [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
764## Contributors
765
766This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
767<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
768
769
770## Backers
771
772Thank you to all our backers! �� [[Become a backer](https://opencollective.com/swag#backer)]
773
774<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
775
776
777## Sponsors
778
779Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
780
781<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
782<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
783<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
784<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
785<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
786<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
787<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
788<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
789<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
790<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
791
792
793
794
795## License
796[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)
797

README_zh-CN.md

1# swag
2
3�� *[English](README.md) ∙ [简体中文](README_zh-CN.md)*
4
5<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
6
7[![Travis Status](https://img.shields.io/travis/swaggo/swag/master.svg)](https://travis-ci.org/swaggo/swag)
8[![Coverage Status](https://img.shields.io/codecov/c/github/swaggo/swag/master.svg)](https://codecov.io/gh/swaggo/swag)
9[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
10[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
11[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
12[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
13[![Sponsors on Open Collective](https://opencollective.com/swag/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
14[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)
15
16Swag将Go的注释转换为Swagger2.0文档。我们为流行的 [Go Web Framework](#支持的Web框架) 创建了各种插件,这样可以与现有Go项目快速集成(使用Swagger UI)。
17
18## 目录
19
20- [快速开始](#快速开始)
21- [支持的Web框架](#支持的web框架)
22- [如何与Gin集成](#如何与gin集成)
23- [开发现状](#开发现状)
24- [声明式注释格式](#声明式注释格式)
25    - [通用API信息](#通用api信息)
26    - [API操作](#api操作)
27    - [安全性](#安全性)
28- [样例](#样例)
29    - [多行的描述](#多行的描述)
30    - [用户自定义的具有数组类型的结构](#用户自定义的具有数组类型的结构)
31    - [响应对象中的模型组合](#响应对象中的模型组合)
32    - [在响应中增加头字段](#在响应中增加头字段)
33    - [使用多路径参数](#使用多路径参数)
34    - [结构体的示例值](#结构体的示例值)
35    - [结构体描述](#结构体描述)
36    - [使用`swaggertype`标签更改字段类型](#使用`swaggertype`标签更改字段类型)
37    - [使用`swaggerignore`标签排除字段](#使用swaggerignore标签排除字段)
38    - [将扩展信息添加到结构字段](#将扩展信息添加到结构字段)
39    - [对展示的模型重命名](#对展示的模型重命名)
40    - [如何使用安全性注释](#如何使用安全性注释)
41- [项目相关](#项目相关)
42
43## 快速开始
44
451. 将注释添加到API源代码中,请参阅声明性注释格式。
462. 使用如下命令下载swag:
47
48```bash
49$ go get -u github.com/swaggo/swag/cmd/swag
50
51# 1.16 及以上版本
52$ go install github.com/swaggo/swag/cmd/swag@latest
53```
54
55从源码开始构建的话,需要有Go环境(1.13及以上版本)。
56
57或者从github的release页面下载预编译好的二进制文件。
58
593. 在包含`main.go`文件的项目根目录运行`swag init`。这将会解析注释并生成需要的文件(`docs`文件夹和`docs/docs.go`)。
60
61```bash
62swag init
63```
64
65确保导入了生成的`docs/docs.go`文件,这样特定的配置文件才会被初始化。如果通用API指数没有写在`main.go`中,可以使用`-g`标识符来告知swag。
66
67```bash
68swag init -g http/api.go
69```
70
71## swag cli
72
73```bash
74swag init -h
75NAME:
76   swag init - Create docs.go
77
78USAGE:
79   swag init [command options] [arguments...]
80
81OPTIONS:
82   --generalInfo value, -g value       API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
83   --dir value, -d value               API解析目录 (默认: "./")
84   --propertyStrategy value, -p value  结构体字段命名规则,三种:snakecase,camelcase,pascalcase (默认: "camelcase")
85   --output value, -o value            文件(swagger.json, swagger.yaml and doc.go)输出目录 (默认: "./docs")
86   --parseVendor                       是否解析vendor目录里的go源文件,默认不
87   --parseDependency                   是否解析依赖目录中的go源文件,默认不
88   --markdownFiles value, --md value   指定API的描述信息所使用的markdown文件所在的目录
89   --generatedTime                     是否输出时间到输出文件docs.go的顶部,默认是
90```
91
92## 支持的Web框架
93
94- [gin](http://github.com/swaggo/gin-swagger)
95- [echo](http://github.com/swaggo/echo-swagger)
96- [buffalo](https://github.com/swaggo/buffalo-swagger)
97- [net/http](https://github.com/swaggo/http-swagger)
98
99## 如何与Gin集成
100
101[点击此处](https://github.com/swaggo/swag/tree/master/example/celler)查看示例源代码。
102
1031. 使用`swag init`生成Swagger2.0文档后,导入如下代码包:
104
105```go
106import "github.com/swaggo/gin-swagger" // gin-swagger middleware
107import "github.com/swaggo/files" // swagger embed files
108```
109
1102. 在`main.go`源代码中添加通用的API注释:
111
112```go
113// @title Swagger Example API
114// @version 1.0
115// @description This is a sample server celler server.
116// @termsOfService http://swagger.io/terms/
117
118// @contact.name API Support
119// @contact.url http://www.swagger.io/support
120// @contact.email support@swagger.io
121
122// @license.name Apache 2.0
123// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
124
125// @host localhost:8080
126// @BasePath /api/v1
127// @query.collection.format multi
128
129// @securityDefinitions.basic BasicAuth
130
131// @securityDefinitions.apikey ApiKeyAuth
132// @in header
133// @name Authorization
134
135// @securitydefinitions.oauth2.application OAuth2Application
136// @tokenUrl https://example.com/oauth/token
137// @scope.write Grants write access
138// @scope.admin Grants read and write access to administrative information
139
140// @securitydefinitions.oauth2.implicit OAuth2Implicit
141// @authorizationurl https://example.com/oauth/authorize
142// @scope.write Grants write access
143// @scope.admin Grants read and write access to administrative information
144
145// @securitydefinitions.oauth2.password OAuth2Password
146// @tokenUrl https://example.com/oauth/token
147// @scope.read Grants read access
148// @scope.write Grants write access
149// @scope.admin Grants read and write access to administrative information
150
151// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
152// @tokenUrl https://example.com/oauth/token
153// @authorizationurl https://example.com/oauth/authorize
154// @scope.admin Grants read and write access to administrative information
155
156// @x-extension-openapi {"example": "value on a json format"}
157
158func main() {
159    r := gin.Default()
160
161    c := controller.NewController()
162
163    v1 := r.Group("/api/v1")
164    {
165        accounts := v1.Group("/accounts")
166        {
167            accounts.GET(":id", c.ShowAccount)
168            accounts.GET("", c.ListAccounts)
169            accounts.POST("", c.AddAccount)
170            accounts.DELETE(":id", c.DeleteAccount)
171            accounts.PATCH(":id", c.UpdateAccount)
172            accounts.POST(":id/images", c.UploadAccountImage)
173        }
174    //...
175    }
176    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
177    r.Run(":8080")
178}
179//...
180```
181
182此外,可以动态设置一些通用的API信息。生成的代码包`docs`导出`SwaggerInfo`变量,使用该变量可以通过编码的方式设置标题、描述、版本、主机和基础路径。使用Gin的示例:
183
184```go
185package main
186
187import (
188    "github.com/gin-gonic/gin"
189    "github.com/swaggo/files"
190    "github.com/swaggo/gin-swagger"
191
192    "./docs" // docs is generated by Swag CLI, you have to import it.
193)
194
195// @contact.name API Support
196// @contact.url http://www.swagger.io/support
197// @contact.email support@swagger.io
198
199// @license.name Apache 2.0
200// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
201
202// @termsOfService http://swagger.io/terms/
203
204func main() {
205
206    // programatically set swagger info
207    docs.SwaggerInfo.Title = "Swagger Example API"
208    docs.SwaggerInfo.Description = "This is a sample server Petstore server."
209    docs.SwaggerInfo.Version = "1.0"
210    docs.SwaggerInfo.Host = "petstore.swagger.io"
211    docs.SwaggerInfo.BasePath = "/v2"
212    docs.SwaggerInfo.Schemes = []string{"http", "https"}
213
214    r := gin.New()
215
216    // use ginSwagger middleware to serve the API docs
217    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
218
219    r.Run()
220}
221```
222
2233. 在`controller`代码中添加API操作注释:
224
225```go
226package controller
227
228import (
229    "fmt"
230    "net/http"
231    "strconv"
232
233    "github.com/gin-gonic/gin"
234    "github.com/swaggo/swag/example/celler/httputil"
235    "github.com/swaggo/swag/example/celler/model"
236)
237
238// ShowAccount godoc
239// @Summary Show a account
240// @Description get string by ID
241// @ID get-string-by-int
242// @Accept  json
243// @Produce  json
244// @Param id path int true "Account ID"
245// @Success 200 {object} model.Account
246// @Header 200 {string} Token "qwerty"
247// @Failure 400,404 {object} httputil.HTTPError
248// @Failure 500 {object} httputil.HTTPError
249// @Failure default {object} httputil.DefaultError
250// @Router /accounts/{id} [get]
251func (c *Controller) ShowAccount(ctx *gin.Context) {
252    id := ctx.Param("id")
253    aid, err := strconv.Atoi(id)
254    if err != nil {
255        httputil.NewError(ctx, http.StatusBadRequest, err)
256        return
257    }
258    account, err := model.AccountOne(aid)
259    if err != nil {
260        httputil.NewError(ctx, http.StatusNotFound, err)
261        return
262    }
263    ctx.JSON(http.StatusOK, account)
264}
265
266// ListAccounts godoc
267// @Summary List accounts
268// @Description get accounts
269// @Accept  json
270// @Produce  json
271// @Param q query string false "name search by q"
272// @Success 200 {array} model.Account
273// @Header 200 {string} Token "qwerty"
274// @Failure 400,404 {object} httputil.HTTPError
275// @Failure 500 {object} httputil.HTTPError
276// @Failure default {object} httputil.DefaultError
277// @Router /accounts [get]
278func (c *Controller) ListAccounts(ctx *gin.Context) {
279    q := ctx.Request.URL.Query().Get("q")
280    accounts, err := model.AccountsAll(q)
281    if err != nil {
282        httputil.NewError(ctx, http.StatusNotFound, err)
283        return
284    }
285    ctx.JSON(http.StatusOK, accounts)
286}
287
288//...
289```
290
291```bash
292swag init
293```
294
2954. 运行程序,然后在浏览器中访问 http://localhost:8080/swagger/index.html 。将看到Swagger 2.0 Api文档,如下所示:
296
297![swagger_index.html](https://raw.githubusercontent.com/swaggo/swag/master/assets/swagger-image.png)
298
299## 开发现状
300
301[Swagger 2.0 文档](https://swagger.io/docs/specification/2-0/basic-structure/)
302
303- [x] Basic Structure
304- [x] API Host and Base Path
305- [x] Paths and Operations
306- [x] Describing Parameters
307- [x] Describing Request Body
308- [x] Describing Responses
309- [x] MIME Types
310- [x] Authentication
311  - [x] Basic Authentication
312  - [x] API Keys
313- [x] Adding Examples
314- [x] File Upload
315- [x] Enums
316- [x] Grouping Operations With Tags
317- [ ] Swagger Extensions
318
319## 声明式注释格式
320
321## 通用API信息
322
323**示例** [`celler/main.go`](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
324
325| 注释                    | 说明                                                                                            | 示例                                                            |
326| ----------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
327| title                   | **必填** 应用程序的名称。                                                                       | // @title Swagger Example API                                   |
328| version                 | **必填** 提供应用程序API的版本。                                                                | // @version 1.0                                                 |
329| description             | 应用程序的简短描述。                                                                            | // @description This is a sample server celler server.          |
330| tag.name                | 标签的名称。                                                                                    | // @tag.name This is the name of the tag                        |
331| tag.description         | 标签的描述。                                                                                    | // @tag.description Cool Description                            |
332| tag.docs.url            | 标签的外部文档的URL。                                                                           | // @tag.docs.url https://example.com                            |
333| tag.docs.description    | 标签的外部文档说明。                                                                            | // @tag.docs.description Best example documentation             |
334| termsOfService          | API的服务条款。                                                                                 | // @termsOfService http://swagger.io/terms/                     |
335| contact.name            | 公开的API的联系信息。                                                                           | // @contact.name API Support                                    |
336| contact.url             | 联系信息的URL。 必须采用网址格式。                                                              | // @contact.url http://www.swagger.io/support                   |
337| contact.email           | 联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。                                        | // @contact.email support@swagger.io                            |
338| license.name            | **必填** 用于API的许可证名称。                                                                  | // @license.name Apache 2.0                                     |
339| license.url             | 用于API的许可证的URL。 必须采用网址格式。                                                       | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
340| host                    | 运行API的主机(主机名或IP地址)。                                                               | // @host localhost:8080                                         |
341| BasePath                | 运行API的基本路径。                                                                             | // @BasePath /api/v1                                            |
342| accept                  | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime-types)”中所述。                                  | // @accept json |
343| produce                 | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime-types)”中所述。                                  | // @produce json |
344| query.collection.format | 请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。 | // @query.collection.format multi                               |
345| schemes                 | 用空格分隔的请求的传输协议。                                                                    | // @schemes http https                                          |
346| x-name                  | 扩展的键必须以x-开头,并且只能使用json值                                                        | // @x-example-key {"key": "value"}                              |
347
348### 使用Markdown描述
349
350如果文档中的短字符串不足以完整表达,或者需要展示图片,代码示例等类似的内容,则可能需要使用Markdown描述。要使用Markdown描述,请使用一下注释。
351
352| 注释                     | 说明                                                                                 | 示例                                                                              |
353| ------------------------ | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
354| title                    | **必填** 应用程序的名称。                                                            | // @title Swagger Example API                                                     |
355| version                  | **必填** 提供应用程序API的版本。                                                     | // @version 1.0                                                                   |
356| description.markdown     | 应用程序的简短描述。 从`api.md`文件中解析。 这是`@description`的替代用法。           | // @description.markdown No value needed, this parses the description from api.md |
357| tag.name                 | 标签的名称。                                                                         | // @tag.name This is the name of the tag                                          |
358| tag.description.markdown | 标签说明,这是`tag.description`的替代用法。 该描述将从名为`tagname.md的`文件中读取。 | // @tag.description.markdown                                                      |
359
360## API操作
361
362Example [celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
363
364| 注释                 | 描述                                                                                                    |
365| -------------------- | ------------------------------------------------------------------------------------------------------- |
366| description          | 操作行为的详细说明。                                                                                    |
367| description.markdown | 应用程序的简短描述。该描述将从名为`endpointname.md`的文件中读取。                                       |
368| id                   | 用于标识操作的唯一字符串。在所有API操作中必须唯一。                                                     |
369| tags                 | 每个API操作的标签列表,以逗号分隔。                                                                     |
370| summary              | 该操作的简短摘要。                                                                                      |
371| accept               | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime-types)”中所述。                                  |
372| produce              | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime-types)”中所述。                                  |
373| param                | 用空格分隔的参数。`param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
374| security             | 每个API操作的[安全性](#安全性)。                                                                      |
375| success              | 以空格分隔的成功响应。`return code`,`{param type}`,`data type`,`comment`                                |
376| failure              | 以空格分隔的故障响应。`return code`,`{param type}`,`data type`,`comment`                                |
377| response             | 与success、failure作用相同                                                                               |
378| header               | 以空格分隔的头字段。 `return code`,`{param type}`,`data type`,`comment`                                 |
379| router               | 以空格分隔的路径定义。 `path`,`[httpMethod]`                                                            |
380| x-name               | 扩展字段必须以`x-`开头,并且只能使用json值。                                                            |
381
382## Mime类型
383
384`swag` 接受所有格式正确的MIME类型, 即使匹配 `*/*`。除此之外,`swag`还接受某些MIME类型的别名,如下所示:
385
386| Alias                 | MIME Type                         |
387| --------------------- | --------------------------------- |
388| json                  | application/json                  |
389| xml                   | text/xml                          |
390| plain                 | text/plain                        |
391| html                  | text/html                         |
392| mpfd                  | multipart/form-data               |
393| x-www-form-urlencoded | application/x-www-form-urlencoded |
394| json-api              | application/vnd.api+json          |
395| json-stream           | application/x-json-stream         |
396| octet-stream          | application/octet-stream          |
397| png                   | image/png                         |
398| jpeg                  | image/jpeg                        |
399| gif                   | image/gif                         |
400
401## 参数类型
402
403- query
404- path
405- header
406- body
407- formData
408
409## 数据类型
410
411- string (string)
412- integer (int, uint, uint32, uint64)
413- number (float32)
414- boolean (bool)
415- user defined struct
416
417## 安全性
418
419| 注释                                   | 描述                                                                                          | 参数                              | 示例                                                         |
420| -------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------ |
421| securitydefinitions.basic              | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. |                                   | // @securityDefinitions.basic BasicAuth                      |
422| securitydefinitions.apikey             | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth.           | in, name                          | // @securityDefinitions.apikey ApiKeyAuth                    |
423| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth.      | tokenUrl, scope                   | // @securitydefinitions.oauth2.application OAuth2Application |
424| securitydefinitions.oauth2.implicit    | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth.         | authorizationUrl, scope           | // @securitydefinitions.oauth2.implicit OAuth2Implicit       |
425| securitydefinitions.oauth2.password    | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth.         | tokenUrl, scope                   | // @securitydefinitions.oauth2.password OAuth2Password       |
426| securitydefinitions.oauth2.accessCode  | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth.      | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode   |
427
428| 参数注释         | 示例                                                     |
429| ---------------- | -------------------------------------------------------- |
430| in               | // @in header                                            |
431| name             | // @name Authorization                                   |
432| tokenUrl         | // @tokenUrl https://example.com/oauth/token             |
433| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
434| scope.hoge       | // @scope.write Grants write access                      |
435
436## 属性
437
438```go
439// @Param enumstring query string false "string enums" Enums(A, B, C)
440// @Param enumint query int false "int enums" Enums(1, 2, 3)
441// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
442// @Param string query string false "string valid" minlength(5) maxlength(10)
443// @Param int query int false "int valid" minimum(1) maximum(10)
444// @Param default query string false "string default" default(A)
445// @Param collection query []string false "string collection" collectionFormat(multi)
446```
447
448也适用于结构体字段:
449
450```go
451type Foo struct {
452    Bar string `minLength:"4" maxLength:"16"`
453    Baz int `minimum:"10" maximum:"20" default:"15"`
454    Qux []string `enums:"foo,bar,baz"`
455}
456```
457
458### 当前可用的
459
460| 字段名           | 类型      | 描述                                                                                                                                                                                                                                                                                                                                                                  |
461| ---------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
462| default          | *         | 声明如果未提供任何参数,则服务器将使用的默认参数值,例如,如果请求中的客户端未提供该参数,则用于控制每页结果数的“计数”可能默认为100。 (注意:“default”对于必需的参数没有意义)。参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2。 与JSON模式不同,此值务必符合此参数的定义[类型](#parameterType)。                                  |
463| maximum          | `number`  | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.                                                                                                                                                                                                                                                                                   |
464| minimum          | `number`  | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.                                                                                                                                                                                                                                                                                   |
465| maxLength        | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.                                                                                                                                                                                                                                                                                   |
466| minLength        | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.                                                                                                                                                                                                                                                                                   |
467| enums            | [\*]      | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.                                                                                                                                                                                                                                                                                   |
468| format           | `string`  | 上面提到的[类型](#parameterType)的扩展格式。有关更多详细信息,请参见[数据类型格式](https://swagger.io/specification/v2/#dataTypeFormat)。                                                                                                                                                                                                                             |
469| collectionFormat | `string`  | 指定query数组参数的格式。 可能的值为: <ul><li>`csv` - 逗号分隔值 `foo,bar`. <li>`ssv` - 空格分隔值 `foo bar`. <li>`tsv` - 制表符分隔值 `foo\tbar`. <li>`pipes` - 管道符分隔值 <code>foo&#124;bar</code>. <li>`multi` - 对应于多个参数实例,而不是单个实例 `foo=bar&foo=baz` 的多个值。这仅对“`query`”或“`formData`”中的参数有效。 </ul> 默认值是 `csv`。 |
470
471### 进一步的
472
473| 字段名      |   类型    | 描述                                                                               |
474| ----------- | :-------: | ---------------------------------------------------------------------------------- |
475| multipleOf  | `number`  | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
476| pattern     | `string`  | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. |
477| maxItems    | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. |
478| minItems    | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. |
479| uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. |
480
481## 样例
482
483### 多行的描述
484
485可以在常规api描述或路由定义中添加跨越多行的描述,如下所示:
486
487```go
488// @description This is the first line
489// @description This is the second line
490// @description And so forth.
491```
492
493### 用户自定义的具有数组类型的结构
494
495```go
496// @Success 200 {array} model.Account <-- This is a user defined struct.
497```
498
499```go
500package model
501
502type Account struct {
503    ID   int    `json:"id" example:"1"`
504    Name string `json:"name" example:"account name"`
505}
506```
507
508### 响应对象中的模型组合
509
510```go
511// JSONResult的data字段类型将被proto.Order类型替换
512@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
513```
514
515```go
516type JSONResult struct {
517    Code    int          `json:"code" `
518    Message string       `json:"message"`
519    Data    interface{}  `json:"data"`
520}
521
522type Order struct { //in `proto` package
523    ...
524}
525```
526
527- 还支持对象数组和原始类型作为嵌套响应
528
529```go
530@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
531@success 200 {object} jsonresult.JSONResult{data=string} "desc"
532@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
533```
534
535- 替换多个字段的类型。如果某字段不存在,将添加该字段。
536
537```go
538@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
539```
540
541### 在响应中增加头字段
542
543```go
544// @Success 200 {string} string	"ok"
545// @failure 400 {string} string	"error"
546// @response default {string} string	"other error"
547// @Header 200 {string} Location "/entity/1"
548// @Header 200,400,default {string} Token "token"
549// @Header all {string} Token2 "token2"
550```
551
552### 使用多路径参数
553
554```go
555/// ...
556// @Param group_id path int true "Group ID"
557// @Param account_id path int true "Account ID"
558// ...
559// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
560```
561
562### 结构体的示例值
563
564```go
565type Account struct {
566    ID   int    `json:"id" example:"1"`
567    Name string `json:"name" example:"account name"`
568    PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
569}
570```
571
572### 结构体描述
573
574```go
575type Account struct {
576    // ID this is userid
577    ID   int    `json:"id"`
578    Name string `json:"name"` // This is Name
579}
580```
581
582### 使用`swaggertype`标签更改字段类型
583
584[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
585
586```go
587type TimestampTime struct {
588    time.Time
589}
590
591///实现encoding.JSON.Marshaler接口
592func (t *TimestampTime) MarshalJSON() ([]byte, error) {
593    bin := make([]byte, 16)
594    bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
595    return bin, nil
596}
597
598///实现encoding.JSON.Unmarshaler接口
599func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
600    v, err := strconv.ParseInt(string(bin), 10, 64)
601    if err != nil {
602        return err
603    }
604    t.Time = time.Unix(v, 0)
605    return nil
606}
607///
608
609type Account struct {
610    // 使用`swaggertype`标签将别名类型更改为内置类型integer
611    ID     sql.NullInt64 `json:"id" swaggertype:"integer"`
612
613    // 使用`swaggertype`标签更改struct类型为内置类型integer
614    RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
615
616    // Array types can be overridden using "array,<prim_type>" format
617    Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
618}
619```
620
621[#379](https://github.com/swaggo/swag/issues/379)
622
623```go
624type CerticateKeyPair struct {
625    Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
626    Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
627}
628```
629
630生成的swagger文档如下:
631
632```go
633"api.MyBinding": {
634  "type":"object",
635  "properties":{
636    "crt":{
637      "type":"string",
638      "format":"base64",
639      "example":"U3dhZ2dlciByb2Nrcw=="
640    },
641    "key":{
642      "type":"string",
643      "format":"base64",
644      "example":"U3dhZ2dlciByb2Nrcw=="
645    }
646  }
647}
648```
649
650### 使用`swaggerignore`标签排除字段
651
652```go
653type Account struct {
654    ID   string    `json:"id"`
655    Name string     `json:"name"`
656    Ignored int     `swaggerignore:"true"`
657}
658```
659
660### 将扩展信息添加到结构字段
661
662```go
663type Account struct {
664    ID   string    `json:"id"   extensions:"x-nullable,x-abc=def,!x-omitempty"` // 扩展字段必须以"x-"开头
665}
666```
667
668生成swagger文档,如下所示:
669
670```go
671"Account": {
672    "type": "object",
673    "properties": {
674        "id": {
675            "type": "string",
676            "x-nullable": true,
677            "x-abc": "def",
678            "x-omitempty": false
679        }
680    }
681}
682```
683
684### 对展示的模型重命名
685
686```go
687type Resp struct {
688    Code int
689}//@name Response
690```
691
692### 如何使用安全性注释
693
694通用API信息。
695
696```go
697// @securityDefinitions.basic BasicAuth
698
699// @securitydefinitions.oauth2.application OAuth2Application
700// @tokenUrl https://example.com/oauth/token
701// @scope.write Grants write access
702// @scope.admin Grants read and write access to administrative information
703```
704
705每个API操作。
706
707```go
708// @Security ApiKeyAuth
709```
710
711使用AND条件。
712
713```go
714// @Security ApiKeyAuth
715// @Security OAuth2Application[write, admin]
716```
717
718## 项目相关
719
720This project was inspired by [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) but we simplified the usage and added support a variety of [web frameworks](#supported-web-frameworks). Gopher image source is [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). It has licenses [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
721
722## 贡献者
723
724This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
725<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
726
727## 支持者
728
729Thank you to all our backers! �� [[Become a backer](https://opencollective.com/swag#backer)]
730
731<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
732
733## 赞助商
734
735Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
736
737<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
738<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
739<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
740<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
741<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
742<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
743<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
744<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
745<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
746<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
747
748## License
749
750[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)
751