Skip to content

Commit

Permalink
Merge branch 'master' into default-required
Browse files Browse the repository at this point in the history
  • Loading branch information
andrey.lukin committed Jun 12, 2022
2 parents c972235 + 67cb768 commit 9710887
Show file tree
Hide file tree
Showing 54 changed files with 2,411 additions and 1,469 deletions.
8 changes: 4 additions & 4 deletions Makefile
Expand Up @@ -13,7 +13,7 @@ GOPATH:=$(shell $(GOCMD) env GOPATH)
u := $(if $(update),-u)

BINARY_NAME:=swag
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag github.com/swaggo/swag/cmd/swag github.com/swaggo/swag/gen)
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag github.com/swaggo/swag/cmd/swag github.com/swaggo/swag/gen github.com/swaggo/swag/format)
GOFILES:=$(shell find . -name "*.go" -type f)

export GO111MODULE := on
Expand Down Expand Up @@ -63,9 +63,9 @@ deps:
$(GOGET) golang.org/x/tools/go/loader

.PHONY: devel-deps
devel-deps:
devel-deps:
GO111MODULE=off $(GOGET) -v -u \
golang.org/x/lint/golint
golang.org/x/lint/golint

.PHONY: lint
lint: devel-deps
Expand All @@ -91,4 +91,4 @@ fmt-check:
.PHONY: view-covered
view-covered:
$(GOTEST) -coverprofile=cover.out $(TARGET)
$(GOCMD) tool cover -html=cover.out
$(GOCMD) tool cover -html=cover.out
54 changes: 28 additions & 26 deletions README.md
Expand Up @@ -9,7 +9,7 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![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)
[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)

Expand All @@ -30,7 +30,7 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie
- [Descriptions over multiple lines](#descriptions-over-multiple-lines)
- [User defined structure with an array type](#user-defined-structure-with-an-array-type)
- [Model composition in response](#model-composition-in-response)
- [Add a headers in response](#add-a-headers-in-response)
- [Add a headers in response](#add-a-headers-in-response)
- [Use multiple path params](#use-multiple-path-params)
- [Example value of struct](#example-value-of-struct)
- [SchemaExample of body](#schemaexample-of-body)
Expand Down Expand Up @@ -194,7 +194,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"

"./docs" // docs is generated by Swag CLI, you have to import it.
)

Expand All @@ -213,7 +213,7 @@ func main() {
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}

r := gin.New()

// use ginSwagger middleware to serve the API docs
Expand Down Expand Up @@ -299,10 +299,10 @@ $ swag init

## The swag formatter

The Swag Comments can be automatically formatted, just like 'go fmt'.
The Swag Comments can be automatically formatted, just like 'go fmt'.
Find the result of formatting [here](https://github.com/swaggo/swag/tree/master/example/celler).

Usage:
Usage:
```shell
swag fmt
```
Expand Down Expand Up @@ -445,21 +445,21 @@ Besides that, `swag` also accepts aliases for some MIME Types as follows:
| annotation | description | parameters | example |
|------------|-------------|------------|---------|
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basic BasicAuth |
| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |


| parameters annotation | example |
|-----------------------|----------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |

| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope, description | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |


| parameters annotation | example |
|---------------------------------|-------------------------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
| description | // @description OAuth protects our entity endpoints |

## Attribute

Expand All @@ -470,6 +470,7 @@ Besides that, `swag` also accepts aliases for some MIME Types as follows:
// @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)
```
Expand All @@ -478,7 +479,7 @@ It also works for the struct fields:

```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16"`
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
Expand All @@ -488,7 +489,7 @@ type Foo struct {

Field Name | Type | Description
---|:---:|---
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required,optional`.
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required,optional`.
<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.
<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
Expand All @@ -498,6 +499,7 @@ Field Name | Type | Description
<a name="parameterEnums"></a>enums | [\*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
<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.
<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`.
<a name="parameterExample"></a>example | * | Declares the example for the parameter value
<a name="parameterExtensions"></a>extensions | `string` | Add extension to parameters.

### Future
Expand All @@ -513,7 +515,7 @@ Field Name | Type | Description

### Descriptions over multiple lines

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

```go
// @description This is the first line
Expand Down Expand Up @@ -562,7 +564,7 @@ type Order struct { //in `proto` package
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```

- overriding multiple fields. field will be added if not exists
- overriding multiple fields. field will be added if not exists
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
Expand Down Expand Up @@ -752,7 +754,7 @@ Rendered:
"id": "integer"
}
```


### Use swaggerignore tag to exclude a field

Expand Down
2 changes: 1 addition & 1 deletion README_zh-CN.md
Expand Up @@ -63,7 +63,7 @@ $ go install github.com/swaggo/swag/cmd/swag@latest
swag init
```

确保导入了生成的`docs/docs.go`文件,这样特定的配置文件才会被初始化。如果通用API指数没有写在`main.go`中,可以使用`-g`标识符来告知swag。
确保导入了生成的`docs/docs.go`文件,这样特定的配置文件才会被初始化。如果通用API注释没有写在`main.go`中,可以使用`-g`标识符来告知swag。

```bash
swag init -g http/api.go
Expand Down
57 changes: 38 additions & 19 deletions cmd/swag/main.go
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
Expand Down Expand Up @@ -30,9 +31,16 @@ const (
parseDepthFlag = "parseDepth"
instanceNameFlag = "instanceName"
overridesFileFlag = "overridesFile"
parseGoListFlag = "parseGoList"
quietFlag = "quiet"
)

var initFlags = []cli.Flag{
&cli.BoolFlag{
Name: quietFlag,
Aliases: []string{"q"},
Usage: "Make the logger quiet.",
},
&cli.StringFlag{
Name: generalInfoFlag,
Aliases: []string{"g"},
Expand Down Expand Up @@ -115,39 +123,50 @@ var initFlags = []cli.Flag{
Value: gen.DefaultOverridesFile,
Usage: "File to read global type overrides from.",
},
&cli.BoolFlag{
Name: parseGoListFlag,
Value: true,
Usage: "Parse dependency via 'go list'",
},
}

func initAction(c *cli.Context) error {
strategy := c.String(propertyStrategyFlag)
func initAction(ctx *cli.Context) error {
strategy := ctx.String(propertyStrategyFlag)

switch strategy {
case swag.CamelCase, swag.SnakeCase, swag.PascalCase:
default:
return fmt.Errorf("not supported %s propertyStrategy", strategy)
}

outputTypes := strings.Split(c.String(outputTypesFlag), ",")
outputTypes := strings.Split(ctx.String(outputTypesFlag), ",")
if len(outputTypes) == 0 {
return fmt.Errorf("no output types specified")
}
var logger swag.Debugger
if ctx.Bool(quietFlag) {
logger = log.New(ioutil.Discard, "", log.LstdFlags)
}

return gen.New().Build(&gen.Config{
SearchDir: c.String(searchDirFlag),
Excludes: c.String(excludeFlag),
MainAPIFile: c.String(generalInfoFlag),
SearchDir: ctx.String(searchDirFlag),
Excludes: ctx.String(excludeFlag),
MainAPIFile: ctx.String(generalInfoFlag),
PropNamingStrategy: strategy,
OutputDir: c.String(outputFlag),
OutputDir: ctx.String(outputFlag),
OutputTypes: outputTypes,
ParseVendor: c.Bool(parseVendorFlag),
ParseDependency: c.Bool(parseDependencyFlag),
MarkdownFilesDir: c.String(markdownFilesFlag),
ParseInternal: c.Bool(parseInternalFlag),
GeneratedTime: c.Bool(generatedTimeFlag),
DefaultRequired: c.Bool(defaultRequiredFlag),
CodeExampleFilesDir: c.String(codeExampleFilesFlag),
ParseDepth: c.Int(parseDepthFlag),
InstanceName: c.String(instanceNameFlag),
OverridesFile: c.String(overridesFileFlag),
ParseVendor: ctx.Bool(parseVendorFlag),
ParseDependency: ctx.Bool(parseDependencyFlag),
MarkdownFilesDir: ctx.String(markdownFilesFlag),
ParseInternal: ctx.Bool(parseInternalFlag),
GeneratedTime: ctx.Bool(generatedTimeFlag),
DefaultRequired: ctx.Bool(defaultRequiredFlag),
CodeExampleFilesDir: ctx.String(codeExampleFilesFlag),
ParseDepth: ctx.Int(parseDepthFlag),
InstanceName: ctx.String(instanceNameFlag),
OverridesFile: ctx.String(overridesFileFlag),
ParseGoList: ctx.Bool(parseGoListFlag),
Debugger: logger,
})
}

Expand Down Expand Up @@ -198,8 +217,8 @@ func main() {
},
},
}
err := app.Run(os.Args)
if err != nil {

if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
10 changes: 5 additions & 5 deletions example/celler/controller/examples.go
Expand Up @@ -14,7 +14,7 @@ import (
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Produce plain
// @Success 200 {string} string "pong"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
Expand All @@ -29,7 +29,7 @@ func (c *Controller) PingExample(ctx *gin.Context) {
// @Description plus
// @Tags example
// @Accept json
// @Produce json
// @Produce plain
// @Param val1 query int true "used for calc"
// @Param val2 query int true "used for calc"
// @Success 200 {integer} string "answer"
Expand Down Expand Up @@ -57,7 +57,7 @@ func (c *Controller) CalcExample(ctx *gin.Context) {
// @Description path params
// @Tags example
// @Accept json
// @Produce json
// @Produce plain
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// @Success 200 {string} string "answer"
Expand All @@ -84,7 +84,7 @@ func (c *Controller) PathParamsExample(ctx *gin.Context) {
// @Description custome header
// @Tags example
// @Accept json
// @Produce json
// @Produce plain
// @Param Authorization header string true "Authentication header"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
Expand Down Expand Up @@ -117,7 +117,7 @@ func (c *Controller) SecuritiesExample(ctx *gin.Context) {
// @Description attribute
// @Tags example
// @Accept json
// @Produce json
// @Produce plain
// @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)
Expand Down
8 changes: 4 additions & 4 deletions example/celler/go.mod
Expand Up @@ -6,8 +6,8 @@ require (
github.com/gin-gonic/gin v1.7.7
github.com/gofrs/uuid v4.2.0+incompatible
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2
github.com/swaggo/gin-swagger v1.4.1
github.com/swaggo/swag v1.7.9
github.com/swaggo/gin-swagger v1.4.2
github.com/swaggo/swag v1.8.1
)

require (
Expand All @@ -31,10 +31,10 @@ require (
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.7 // indirect
golang.org/x/tools v0.1.10 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

0 comments on commit 9710887

Please sign in to comment.