diff --git a/go.mod b/go.mod
index fa2926c..c42ffeb 100644
--- a/go.mod
+++ b/go.mod
@@ -16,7 +16,7 @@ require (
github.com/spf13/viper v1.11.0
github.com/stretchr/testify v1.7.1
github.com/swaggo/echo-swagger v1.3.0
- github.com/swaggo/swag v1.8.1
+ github.com/swaggo/swag v1.8.3
github.com/theflyingcodr/govalidator v0.1.3
github.com/theflyingcodr/lathos v0.0.6
github.com/theflyingcodr/sockets v0.0.12-beta
@@ -60,11 +60,11 @@ require (
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
- golang.org/x/net v0.0.0-20220412020605-290c469a71a5 // indirect
+ golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect
- golang.org/x/tools v0.1.9 // indirect
+ golang.org/x/tools v0.1.10 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
diff --git a/go.sum b/go.sum
index 0513d58..bab9232 100644
--- a/go.sum
+++ b/go.sum
@@ -62,7 +62,6 @@ github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tN
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
-github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=
github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
@@ -351,7 +350,6 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
-github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE=
github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U=
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
@@ -441,8 +439,8 @@ github.com/swaggo/echo-swagger v1.3.0/go.mod h1:snY6MlGK+pQAfJNEfX5qaOzt/QuM/WIN
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU=
-github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=
-github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
+github.com/swaggo/swag v1.8.3 h1:3pZSSCQ//gAH88lfmxM3Cd1+JCsxV8Md6f36b9hrZ5s=
+github.com/swaggo/swag v1.8.3/go.mod h1:jMLeXOOmYyjk8PvHTsXBdrubsNd9gUJTTCzL5iBnseg=
github.com/theflyingcodr/govalidator v0.1.3 h1:eU8P2xZrU2s1FjbtoVW6yDgXG+g2xDM9p3eNPLFKmSk=
github.com/theflyingcodr/govalidator v0.1.3/go.mod h1:E6v0mkRcAVMTa7pC8VkUOtoE8WQ9zQ4/fOwrvtwhOM0=
github.com/theflyingcodr/lathos v0.0.6 h1:xIHMZTinurvodmFOgvSGD+OrDhSj42+Xz+FOXYwEr18=
@@ -530,8 +528,9 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
-golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
+golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
+golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -580,8 +579,9 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
-golang.org/x/net v0.0.0-20220412020605-290c469a71a5 h1:bRb386wvrE+oBNdF1d/Xh9mQrfQ4ecYhW5qJ5GvTGT4=
golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
+golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA=
+golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -771,8 +771,9 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
-golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
+golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
+golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/vendor/github.com/swaggo/swag/Dockerfile b/vendor/github.com/swaggo/swag/Dockerfile
index 65746bd..170d0c6 100644
--- a/vendor/github.com/swaggo/swag/Dockerfile
+++ b/vendor/github.com/swaggo/swag/Dockerfile
@@ -1,7 +1,7 @@
# Dockerfile References: https://docs.docker.com/engine/reference/builder/
# Start from the latest golang base image
-FROM golang:1.17-alpine as builder
+FROM golang:1.18.3-alpine as builder
# Set the Current Working Directory inside the container
WORKDIR /app
diff --git a/vendor/github.com/swaggo/swag/Makefile b/vendor/github.com/swaggo/swag/Makefile
index fa679d8..d1a9817 100644
--- a/vendor/github.com/swaggo/swag/Makefile
+++ b/vendor/github.com/swaggo/swag/Makefile
@@ -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
@@ -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
@@ -91,4 +91,4 @@ fmt-check:
.PHONY: view-covered
view-covered:
$(GOTEST) -coverprofile=cover.out $(TARGET)
- $(GOCMD) tool cover -html=cover.out
\ No newline at end of file
+ $(GOCMD) tool cover -html=cover.out
diff --git a/vendor/github.com/swaggo/swag/README.md b/vendor/github.com/swaggo/swag/README.md
index 8774db7..84239d1 100644
--- a/vendor/github.com/swaggo/swag/README.md
+++ b/vendor/github.com/swaggo/swag/README.md
@@ -9,7 +9,7 @@
[](https://goreportcard.com/report/github.com/swaggo/swag)
[](https://codebeat.co/projects/github-com-swaggo-swag-master)
[](https://godoc.org/github.com/swaggo/swag)
-[](#backers)
+[](#backers)
[](#sponsors) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[](https://github.com/swaggo/swag/releases)
@@ -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)
@@ -193,7 +193,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.
)
@@ -212,7 +212,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
@@ -298,10 +298,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
```
@@ -444,21 +444,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
@@ -469,6 +469,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)
```
@@ -477,7 +478,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"`
}
@@ -487,7 +488,7 @@ type Foo struct {
Field Name | Type | Description
---|:---:|---
-validate | `string` | Determines the validation for the parameter. Possible values are: `required`.
+validate | `string` | Determines the validation for the parameter. Possible values are: `required`.
default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter.
maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
@@ -497,6 +498,7 @@ Field Name | Type | Description
enums | [\*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) for further details.
collectionFormat | `string` |Determines the format of the array if type array is used. Possible values are:
- `csv` - comma separated values `foo,bar`.
- `ssv` - space separated values `foo bar`.
- `tsv` - tab separated values `foo\tbar`.
- `pipes` - pipe separated values
foo|bar. - `multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData".
Default value is `csv`.
+example | * | Declares the example for the parameter value
extensions | `string` | Add extension to parameters.
### Future
@@ -512,7 +514,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
@@ -561,7 +563,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"
```
@@ -751,7 +753,7 @@ Rendered:
"id": "integer"
}
```
-
+
### Use swaggerignore tag to exclude a field
diff --git a/vendor/github.com/swaggo/swag/README_zh-CN.md b/vendor/github.com/swaggo/swag/README_zh-CN.md
index 75dbbce..45a355f 100644
--- a/vendor/github.com/swaggo/swag/README_zh-CN.md
+++ b/vendor/github.com/swaggo/swag/README_zh-CN.md
@@ -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
diff --git a/vendor/github.com/swaggo/swag/field_parser.go b/vendor/github.com/swaggo/swag/field_parser.go
index b5cf262..bd4fa42 100644
--- a/vendor/github.com/swaggo/swag/field_parser.go
+++ b/vendor/github.com/swaggo/swag/field_parser.go
@@ -10,10 +10,17 @@ import (
"sync"
"unicode"
+ "github.com/go-openapi/jsonreference"
"github.com/go-openapi/spec"
)
-var _ FieldParser = &tagBaseFieldParser{}
+var _ FieldParser = &tagBaseFieldParser{p: nil, field: nil, tag: ""}
+
+const (
+ requiredLabel = "required"
+ swaggerTypeTag = "swaggertype"
+ swaggerIgnoreTag = "swaggerignore"
+)
type tagBaseFieldParser struct {
p *Parser
@@ -22,46 +29,47 @@ type tagBaseFieldParser struct {
}
func newTagBaseFieldParser(p *Parser, field *ast.Field) FieldParser {
- ps := &tagBaseFieldParser{
+ fieldParser := tagBaseFieldParser{
p: p,
field: field,
+ tag: "",
}
- if ps.field.Tag != nil {
- ps.tag = reflect.StructTag(strings.Replace(field.Tag.Value, "`", "", -1))
+ if fieldParser.field.Tag != nil {
+ fieldParser.tag = reflect.StructTag(strings.ReplaceAll(field.Tag.Value, "`", ""))
}
- return ps
+ return &fieldParser
}
-func (ps *tagBaseFieldParser) ShouldSkip() (bool, error) {
+func (ps *tagBaseFieldParser) ShouldSkip() bool {
// Skip non-exported fields.
if !ast.IsExported(ps.field.Names[0].Name) {
- return true, nil
+ return true
}
if ps.field.Tag == nil {
- return false, nil
+ return false
}
- ignoreTag := ps.tag.Get("swaggerignore")
+ ignoreTag := ps.tag.Get(swaggerIgnoreTag)
if strings.EqualFold(ignoreTag, "true") {
- return true, nil
+ return true
}
// json:"tag,hoge"
- name := strings.TrimSpace(strings.Split(ps.tag.Get("json"), ",")[0])
+ name := strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name == "-" {
- return true, nil
+ return true
}
- return false, nil
+ return false
}
func (ps *tagBaseFieldParser) FieldName() (string, error) {
var name string
if ps.field.Tag != nil {
// json:"tag,hoge"
- name = strings.TrimSpace(strings.Split(ps.tag.Get("json"), ",")[0])
+ name = strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name != "" {
return name, nil
@@ -79,34 +87,40 @@ func (ps *tagBaseFieldParser) FieldName() (string, error) {
}
func toSnakeCase(in string) string {
- runes := []rune(in)
- length := len(runes)
-
- var out []rune
- for i := 0; i < length; i++ {
- if i > 0 && unicode.IsUpper(runes[i]) &&
- ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
+ var (
+ runes = []rune(in)
+ length = len(runes)
+ out []rune
+ )
+
+ for idx := 0; idx < length; idx++ {
+ if idx > 0 && unicode.IsUpper(runes[idx]) &&
+ ((idx+1 < length && unicode.IsLower(runes[idx+1])) || unicode.IsLower(runes[idx-1])) {
out = append(out, '_')
}
- out = append(out, unicode.ToLower(runes[i]))
+
+ out = append(out, unicode.ToLower(runes[idx]))
}
return string(out)
}
func toLowerCamelCase(in string) string {
- runes := []rune(in)
+ var flag bool
- var out []rune
- flag := false
+ out := make([]rune, len(in))
+
+ runes := []rune(in)
for i, curr := range runes {
if (i == 0 && unicode.IsUpper(curr)) || (flag && unicode.IsUpper(curr)) {
- out = append(out, unicode.ToLower(curr))
+ out[i] = unicode.ToLower(curr)
flag = true
- } else {
- out = append(out, curr)
- flag = false
+
+ continue
}
+
+ out[i] = curr
+ flag = false
}
return string(out)
@@ -117,7 +131,7 @@ func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
return nil, nil
}
- typeTag := ps.tag.Get("swaggertype")
+ typeTag := ps.tag.Get(swaggerTypeTag)
if typeTag != "" {
return BuildCustomSchema(strings.Split(typeTag, ","))
}
@@ -126,7 +140,6 @@ func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
}
type structField struct {
- desc string
schemaType string
arrayType string
formatType string
@@ -138,11 +151,8 @@ type structField struct {
maxItems *int64
minItems *int64
exampleValue interface{}
- defaultValue interface{}
- extensions map[string]interface{}
enums []interface{}
enumVarNames []interface{}
- readOnly bool
unique bool
}
@@ -155,32 +165,42 @@ func splitNotWrapped(s string, sep rune) []string {
'{': '}',
}
- result := make([]string, 0)
- current := ""
- var openCount = 0
- var openChar rune
+ var (
+ result = make([]string, 0)
+ current = strings.Builder{}
+ openCount = 0
+ openChar rune
+ )
+
for _, char := range s {
- if openChar == 0 && openCloseMap[char] != 0 {
+ switch {
+ case openChar == 0 && openCloseMap[char] != 0:
openChar = char
+
openCount++
- current += string(char)
- } else if char == openChar {
+
+ current.WriteRune(char)
+ case char == openChar:
openCount++
- current = current + string(char)
- } else if openCount > 0 && char == openCloseMap[openChar] {
+
+ current.WriteRune(char)
+ case openCount > 0 && char == openCloseMap[openChar]:
openCount--
- current += string(char)
- } else if openCount == 0 && char == sep {
- result = append(result, current)
+
+ current.WriteRune(char)
+ case openCount == 0 && char == sep:
+ result = append(result, current.String())
+
openChar = 0
- current = ""
- } else {
- current += string(char)
+
+ current = strings.Builder{}
+ default:
+ current.WriteRune(char)
}
}
- if current != "" {
- result = append(result, current)
+ if current.String() != "" {
+ result = append(result, current.String())
}
return result
@@ -196,157 +216,110 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
if ps.field.Doc != nil {
schema.Description = strings.TrimSpace(ps.field.Doc.Text())
}
+
if schema.Description == "" && ps.field.Comment != nil {
schema.Description = strings.TrimSpace(ps.field.Comment.Text())
}
+
return nil
}
- structField := &structField{
+ field := &structField{
schemaType: types[0],
formatType: ps.tag.Get(formatTag),
- readOnly: ps.tag.Get(readOnlyTag) == "true",
}
if len(types) > 1 && (types[0] == ARRAY || types[0] == OBJECT) {
- structField.arrayType = types[1]
+ field.arrayType = types[1]
}
- if ps.field.Doc != nil {
- structField.desc = strings.TrimSpace(ps.field.Doc.Text())
- }
- if structField.desc == "" && ps.field.Comment != nil {
- structField.desc = strings.TrimSpace(ps.field.Comment.Text())
- }
+ jsonTagValue := ps.tag.Get(jsonTag)
- jsonTag := ps.tag.Get(jsonTag)
- // json:"name,string" or json:",string"
-
- exampleTag, ok := ps.tag.Lookup(exampleTag)
- if ok {
- structField.exampleValue = exampleTag
- if !strings.Contains(jsonTag, ",string") {
- example, err := defineTypeOfExample(structField.schemaType, structField.arrayType, exampleTag)
- if err != nil {
- return err
- }
- structField.exampleValue = example
- }
+ bindingTagValue := ps.tag.Get(bindingTag)
+ if bindingTagValue != "" {
+ parseValidTags(bindingTagValue, field)
}
- bindingTag := ps.tag.Get(bindingTag)
- if bindingTag != "" {
- ps.parseValidTags(bindingTag, structField)
+ validateTagValue := ps.tag.Get(validateTag)
+ if validateTagValue != "" {
+ parseValidTags(validateTagValue, field)
}
- validateTag := ps.tag.Get(validateTag)
- if validateTag != "" {
- ps.parseValidTags(validateTag, structField)
- }
-
- extensionsTag := ps.tag.Get(extensionsTag)
- if extensionsTag != "" {
- structField.extensions = map[string]interface{}{}
- for _, val := range splitNotWrapped(extensionsTag, ',') {
- parts := strings.SplitN(val, "=", 2)
- if len(parts) == 2 {
- structField.extensions[parts[0]] = parts[1]
- } else {
- if len(parts[0]) > 0 && string(parts[0][0]) == "!" {
- structField.extensions[parts[0][1:]] = false
- } else {
- structField.extensions[parts[0]] = true
- }
- }
- }
- }
-
- enumsTag := ps.tag.Get(enumsTag)
- if enumsTag != "" {
- enumType := structField.schemaType
- if structField.schemaType == ARRAY {
- enumType = structField.arrayType
- }
-
- structField.enums = nil
- for _, e := range strings.Split(enumsTag, ",") {
- value, err := defineType(enumType, e)
- if err != nil {
- return err
- }
- structField.enums = append(structField.enums, value)
- }
- }
- varnamesTag := ps.tag.Get("x-enum-varnames")
- if varnamesTag != "" {
- if structField.extensions == nil {
- structField.extensions = map[string]interface{}{}
- }
- varNames := strings.Split(varnamesTag, ",")
- if len(varNames) != len(structField.enums) {
- return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(structField.enums), len(varNames))
- }
- structField.enumVarNames = nil
- for _, v := range varNames {
- structField.enumVarNames = append(structField.enumVarNames, v)
- }
- structField.extensions["x-enum-varnames"] = structField.enumVarNames
- }
- defaultTag := ps.tag.Get(defaultTag)
- if defaultTag != "" {
- value, err := defineType(structField.schemaType, defaultTag)
+ enumsTagValue := ps.tag.Get(enumsTag)
+ if enumsTagValue != "" {
+ err := parseEnumTags(enumsTagValue, field)
if err != nil {
return err
}
- structField.defaultValue = value
}
- if IsNumericType(structField.schemaType) || IsNumericType(structField.arrayType) {
+ if IsNumericType(field.schemaType) || IsNumericType(field.arrayType) {
maximum, err := getFloatTag(ps.tag, maximumTag)
if err != nil {
return err
}
+
if maximum != nil {
- structField.maximum = maximum
+ field.maximum = maximum
}
minimum, err := getFloatTag(ps.tag, minimumTag)
if err != nil {
return err
}
+
if minimum != nil {
- structField.minimum = minimum
+ field.minimum = minimum
}
multipleOf, err := getFloatTag(ps.tag, multipleOfTag)
if err != nil {
return err
}
+
if multipleOf != nil {
- structField.multipleOf = multipleOf
+ field.multipleOf = multipleOf
}
}
- if structField.schemaType == STRING || structField.arrayType == STRING {
- maxLength, err := getIntTag(ps.tag, "maxLength")
+ if field.schemaType == STRING || field.arrayType == STRING {
+ maxLength, err := getIntTag(ps.tag, maxLengthTag)
if err != nil {
return err
}
+
if maxLength != nil {
- structField.maxLength = maxLength
+ field.maxLength = maxLength
}
- minLength, err := getIntTag(ps.tag, "minLength")
+ minLength, err := getIntTag(ps.tag, minLengthTag)
if err != nil {
return err
}
+
if minLength != nil {
- structField.minLength = minLength
+ field.minLength = minLength
+ }
+ }
+
+ // json:"name,string" or json:",string"
+ exampleTagValue, ok := ps.tag.Lookup(exampleTag)
+ if ok {
+ field.exampleValue = exampleTagValue
+
+ if !strings.Contains(jsonTagValue, ",string") {
+ example, err := defineTypeOfExample(field.schemaType, field.arrayType, exampleTagValue)
+ if err != nil {
+ return err
+ }
+
+ field.exampleValue = example
}
}
// perform this after setting everything else (min, max, etc...)
- if strings.Contains(jsonTag, ",string") { // @encoding/json: "It applies only to fields of string, floating point, integer, or boolean types."
+ if strings.Contains(jsonTagValue, ",string") {
+ // @encoding/json: "It applies only to fields of string, floating point, integer, or boolean types."
defaultValues := map[string]string{
// Zero Values as string
STRING: "",
@@ -355,51 +328,111 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
NUMBER: "0",
}
- defaultValue, ok := defaultValues[structField.schemaType]
+ defaultValue, ok := defaultValues[field.schemaType]
if ok {
- structField.schemaType = STRING
+ field.schemaType = STRING
+ *schema = *PrimitiveSchema(field.schemaType)
- if structField.exampleValue == nil {
+ if field.exampleValue == nil {
// if exampleValue is not defined by the user,
// we will force an example with a correct value
// (eg: int->"0", bool:"false")
- structField.exampleValue = defaultValue
+ field.exampleValue = defaultValue
}
}
}
- if structField.schemaType == STRING && types[0] != STRING {
- *schema = *PrimitiveSchema(structField.schemaType)
+ if ps.field.Doc != nil {
+ schema.Description = strings.TrimSpace(ps.field.Doc.Text())
+ }
+
+ if schema.Description == "" && ps.field.Comment != nil {
+ schema.Description = strings.TrimSpace(ps.field.Comment.Text())
}
- schema.Description = structField.desc
- schema.ReadOnly = structField.readOnly
+ schema.ReadOnly = ps.tag.Get(readOnlyTag) == "true"
+
if !reflect.ValueOf(schema.Ref).IsZero() && schema.ReadOnly {
schema.AllOf = []spec.Schema{*spec.RefSchema(schema.Ref.String())}
- schema.Ref = spec.Ref{} // clear out existing ref
+ schema.Ref = spec.Ref{
+ Ref: jsonreference.Ref{
+ HasFullURL: false,
+ HasURLPathOnly: false,
+ HasFragmentOnly: false,
+ HasFileScheme: false,
+ HasFullFilePath: false,
+ },
+ } // clear out existing ref
+ }
+
+ defaultTagValue := ps.tag.Get(defaultTag)
+ if defaultTagValue != "" {
+ value, err := defineType(field.schemaType, defaultTagValue)
+ if err != nil {
+ return err
+ }
+
+ schema.Default = value
+ }
+
+ schema.Example = field.exampleValue
+
+ if field.schemaType != ARRAY {
+ schema.Format = field.formatType
}
- schema.Default = structField.defaultValue
- schema.Example = structField.exampleValue
- if structField.schemaType != ARRAY {
- schema.Format = structField.formatType
+
+ extensionsTagValue := ps.tag.Get(extensionsTag)
+ if extensionsTagValue != "" {
+ schema.Extensions = setExtensionParam(extensionsTagValue)
}
- schema.Extensions = structField.extensions
+
+ varNamesTag := ps.tag.Get("x-enum-varnames")
+ if varNamesTag != "" {
+ varNames := strings.Split(varNamesTag, ",")
+ if len(varNames) != len(field.enums) {
+ return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(field.enums), len(varNames))
+ }
+
+ field.enumVarNames = nil
+
+ for _, v := range varNames {
+ field.enumVarNames = append(field.enumVarNames, v)
+ }
+
+ if field.schemaType == ARRAY {
+ // Add the var names in the items schema
+ if schema.Items.Schema.Extensions == nil {
+ schema.Items.Schema.Extensions = map[string]interface{}{}
+ }
+ schema.Items.Schema.Extensions["x-enum-varnames"] = field.enumVarNames
+ } else {
+ // Add to top level schema
+ if schema.Extensions == nil {
+ schema.Extensions = map[string]interface{}{}
+ }
+ schema.Extensions["x-enum-varnames"] = field.enumVarNames
+ }
+ }
+
eleSchema := schema
- if structField.schemaType == ARRAY {
+
+ if field.schemaType == ARRAY {
// For Array only
- schema.MaxItems = structField.maxItems
- schema.MinItems = structField.minItems
- schema.UniqueItems = structField.unique
+ schema.MaxItems = field.maxItems
+ schema.MinItems = field.minItems
+ schema.UniqueItems = field.unique
eleSchema = schema.Items.Schema
- eleSchema.Format = structField.formatType
- }
- eleSchema.Maximum = structField.maximum
- eleSchema.Minimum = structField.minimum
- eleSchema.MultipleOf = structField.multipleOf
- eleSchema.MaxLength = structField.maxLength
- eleSchema.MinLength = structField.minLength
- eleSchema.Enum = structField.enums
+ eleSchema.Format = field.formatType
+ }
+
+ eleSchema.Maximum = field.maximum
+ eleSchema.Minimum = field.minimum
+ eleSchema.MultipleOf = field.multipleOf
+ eleSchema.MaxLength = field.maxLength
+ eleSchema.MinLength = field.minLength
+ eleSchema.Enum = field.enums
+
return nil
}
@@ -439,7 +472,7 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
bindingTag := ps.tag.Get(bindingTag)
if bindingTag != "" {
for _, val := range strings.Split(bindingTag, ",") {
- if val == "required" {
+ if val == requiredLabel {
return true, nil
}
}
@@ -448,7 +481,7 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
validateTag := ps.tag.Get(validateTag)
if validateTag != "" {
for _, val := range strings.Split(validateTag, ",") {
- if val == "required" {
+ if val == requiredLabel {
return true, nil
}
}
@@ -457,27 +490,24 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
return false, nil
}
-func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
+func parseValidTags(validTag string, sf *structField) {
// `validate:"required,max=10,min=1"`
// ps. required checked by IsRequired().
for _, val := range strings.Split(validTag, ",") {
var (
- valKey string
valValue string
+ keyVal = strings.Split(val, "=")
)
- kv := strings.Split(val, "=")
- switch len(kv) {
+
+ switch len(keyVal) {
case 1:
- valKey = kv[0]
case 2:
- valKey = kv[0]
- valValue = kv[1]
+ valValue = strings.ReplaceAll(strings.ReplaceAll(keyVal[1], utf8HexComma, ","), utf8Pipe, "|")
default:
continue
}
- valValue = strings.Replace(strings.Replace(valValue, utf8HexComma, ",", -1), utf8Pipe, "|", -1)
- switch valKey {
+ switch keyVal[0] {
case "max", "lte":
sf.setMax(valValue)
case "min", "gte":
@@ -497,6 +527,26 @@ func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
}
}
+func parseEnumTags(enumTag string, field *structField) error {
+ enumType := field.schemaType
+ if field.schemaType == ARRAY {
+ enumType = field.arrayType
+ }
+
+ field.enums = nil
+
+ for _, e := range strings.Split(enumTag, ",") {
+ value, err := defineType(enumType, e)
+ if err != nil {
+ return err
+ }
+
+ field.enums = append(field.enums, value)
+ }
+
+ return nil
+}
+
func (sf *structField) setOneOf(valValue string) {
if len(sf.enums) != 0 {
return
@@ -513,6 +563,7 @@ func (sf *structField) setOneOf(valValue string) {
if err != nil {
continue
}
+
sf.enums = append(sf.enums, value)
}
}
@@ -522,6 +573,7 @@ func (sf *structField) setMin(valValue string) {
if err != nil {
return
}
+
switch sf.schemaType {
case INTEGER, NUMBER:
sf.minimum = &value
@@ -539,6 +591,7 @@ func (sf *structField) setMax(valValue string) {
if err != nil {
return
}
+
switch sf.schemaType {
case INTEGER, NUMBER:
sf.maximum = &value
@@ -558,25 +611,30 @@ const (
// These code copy from
// https://github.com/go-playground/validator/blob/d4271985b44b735c6f76abc7a06532ee997f9476/baked_in.go#L207
-// ---
+// ---.
var oneofValsCache = map[string][]string{}
var oneofValsCacheRWLock = sync.RWMutex{}
var splitParamsRegex = regexp.MustCompile(`'[^']*'|\S+`)
-func parseOneOfParam2(s string) []string {
+func parseOneOfParam2(param string) []string {
oneofValsCacheRWLock.RLock()
- values, ok := oneofValsCache[s]
+ values, ok := oneofValsCache[param]
oneofValsCacheRWLock.RUnlock()
+
if !ok {
oneofValsCacheRWLock.Lock()
- values = splitParamsRegex.FindAllString(s, -1)
+ values = splitParamsRegex.FindAllString(param, -1)
+
for i := 0; i < len(values); i++ {
- values[i] = strings.Replace(values[i], "'", "", -1)
+ values[i] = strings.ReplaceAll(values[i], "'", "")
}
- oneofValsCache[s] = values
+
+ oneofValsCache[param] = values
+
oneofValsCacheRWLock.Unlock()
}
+
return values
}
-// ---
+// ---.
diff --git a/vendor/github.com/swaggo/swag/formater.go b/vendor/github.com/swaggo/swag/formater.go
deleted file mode 100644
index 1c903f4..0000000
--- a/vendor/github.com/swaggo/swag/formater.go
+++ /dev/null
@@ -1,326 +0,0 @@
-package swag
-
-import (
- "bytes"
- "crypto/md5"
- "fmt"
- "go/ast"
- goparser "go/parser"
- "go/token"
- "io"
- "io/ioutil"
- "log"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "strings"
- "text/tabwriter"
-)
-
-const splitTag = "&*"
-
-// Formater implements a formater for Go source files.
-type Formater struct {
- // debugging output goes here
- debug Debugger
-
- // excludes excludes dirs and files in SearchDir
- excludes map[string]struct{}
-
- mainFile string
-}
-
-// NewFormater create a new formater instance.
-func NewFormater() *Formater {
- formater := &Formater{
- debug: log.New(os.Stdout, "", log.LstdFlags),
- excludes: make(map[string]struct{}),
- }
- return formater
-}
-
-// FormatAPI format the swag comment.
-func (f *Formater) FormatAPI(searchDir, excludeDir, mainFile string) error {
- searchDirs := strings.Split(searchDir, ",")
- for _, searchDir := range searchDirs {
- if _, err := os.Stat(searchDir); os.IsNotExist(err) {
- return fmt.Errorf("dir: %s does not exist", searchDir)
- }
- }
- for _, fi := range strings.Split(excludeDir, ",") {
- fi = strings.TrimSpace(fi)
- if fi != "" {
- fi = filepath.Clean(fi)
- f.excludes[fi] = struct{}{}
- }
- }
-
- // parse main.go
- absMainAPIFilePath, err := filepath.Abs(filepath.Join(searchDirs[0], mainFile))
- if err != nil {
- return err
- }
- err = f.FormatMain(absMainAPIFilePath)
- if err != nil {
- return err
- }
- f.mainFile = mainFile
-
- err = f.formatMultiSearchDir(searchDirs)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (f *Formater) formatMultiSearchDir(searchDirs []string) error {
- for _, searchDir := range searchDirs {
- f.debug.Printf("Format API Info, search dir:%s", searchDir)
-
- err := filepath.Walk(searchDir, f.visit)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-func (f *Formater) visit(path string, fileInfo os.FileInfo, err error) error {
- if err := walkWith(f.excludes, false)(path, fileInfo); err != nil {
- return err
- } else if fileInfo.IsDir() {
- // skip if file is folder
- return nil
- }
-
- if strings.HasSuffix(strings.ToLower(path), "_test.go") || filepath.Ext(path) != ".go" {
- // skip if file not has suffix "*.go"
- return nil
- }
- if strings.HasSuffix(strings.ToLower(path), f.mainFile) {
- // skip main file
- return nil
- }
-
- err = f.FormatFile(path)
- if err != nil {
- return fmt.Errorf("ParseFile error:%+v", err)
- }
- return nil
-}
-
-// FormatMain format the main.go comment.
-func (f *Formater) FormatMain(mainFilepath string) error {
- fileSet := token.NewFileSet()
- astFile, err := goparser.ParseFile(fileSet, mainFilepath, nil, goparser.ParseComments)
- if err != nil {
- return fmt.Errorf("cannot format file, err: %w path : %s ", err, mainFilepath)
- }
- var (
- formatedComments = bytes.Buffer{}
- // CommentCache
- oldCommentsMap = make(map[string]string)
- )
-
- if astFile.Comments != nil {
- for _, comment := range astFile.Comments {
- formatFuncDoc(comment.List, &formatedComments, oldCommentsMap)
- }
- }
-
- return writeFormatedComments(mainFilepath, formatedComments, oldCommentsMap)
-}
-
-// FormatFile format the swag comment in go function.
-func (f *Formater) FormatFile(filepath string) error {
- fileSet := token.NewFileSet()
- astFile, err := goparser.ParseFile(fileSet, filepath, nil, goparser.ParseComments)
- if err != nil {
- return fmt.Errorf("cannot format file, err: %w path : %s ", err, filepath)
- }
-
- var (
- formatedComments = bytes.Buffer{}
- // CommentCache
- oldCommentsMap = make(map[string]string)
- )
-
- for _, astDescription := range astFile.Decls {
- astDeclaration, ok := astDescription.(*ast.FuncDecl)
- if ok && astDeclaration.Doc != nil && astDeclaration.Doc.List != nil {
- formatFuncDoc(astDeclaration.Doc.List, &formatedComments, oldCommentsMap)
- }
- }
-
- return writeFormatedComments(filepath, formatedComments, oldCommentsMap)
-}
-
-func writeFormatedComments(filepath string, formatedComments bytes.Buffer, oldCommentsMap map[string]string) error {
- // Replace the file
- // Read the file
- srcBytes, err := ioutil.ReadFile(filepath)
- if err != nil {
- return fmt.Errorf("cannot open file, err: %w path : %s ", err, filepath)
- }
- replaceSrc := string(srcBytes)
- newComments := strings.Split(formatedComments.String(), "\n")
- for _, e := range newComments {
- commentSplit := strings.Split(e, splitTag)
- if len(commentSplit) == 2 {
- commentHash, commentContent := commentSplit[0], commentSplit[1]
-
- if !isBlankComment(commentContent) {
- replaceSrc = strings.Replace(replaceSrc, oldCommentsMap[commentHash], commentContent, 1)
- }
- }
- }
- return writeBack(filepath, []byte(replaceSrc), srcBytes)
-}
-
-func formatFuncDoc(commentList []*ast.Comment, formatedComments io.Writer, oldCommentsMap map[string]string) {
- tabw := tabwriter.NewWriter(formatedComments, 0, 0, 2, ' ', 0)
-
- for _, comment := range commentList {
- commentLine := comment.Text
- if isSwagComment(commentLine) || isBlankComment(commentLine) {
- cmd5 := fmt.Sprintf("%x", md5.Sum([]byte(commentLine)))
-
- // Find the separator and replace to \t
- c := separatorFinder(commentLine, '\t')
- oldCommentsMap[cmd5] = commentLine
-
- // md5 + splitTag + srcCommentLine
- // eg. xxx&*@Description get struct array
- _, _ = fmt.Fprintln(tabw, cmd5+splitTag+c)
- }
- }
- // format by tabwriter
- _ = tabw.Flush()
-}
-
-// Check of @Param @Success @Failure @Response @Header
-var specialTagForSplit = map[string]byte{
- paramAttr: 1,
- successAttr: 1,
- failureAttr: 1,
- responseAttr: 1,
- headerAttr: 1,
-}
-
-var skipChar = map[byte]byte{
- '"': 1,
- '(': 1,
- '{': 1,
- '[': 1,
-}
-
-var skipCharEnd = map[byte]byte{
- '"': 1,
- ')': 1,
- '}': 1,
- ']': 1,
-}
-
-func separatorFinder(comment string, rp byte) string {
- commentBytes := []byte(comment)
- commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/"))
- if len(commentLine) == 0 {
- return ""
- }
- attribute := strings.Fields(commentLine)[0]
- attrLen := strings.Index(comment, attribute) + len(attribute)
- attribute = strings.ToLower(attribute)
- var i = attrLen
-
- if _, ok := specialTagForSplit[attribute]; ok {
- var skipFlag bool
- for ; i < len(commentBytes); i++ {
- if !skipFlag && commentBytes[i] == ' ' {
- j := i
- for j < len(commentBytes) && commentBytes[j] == ' ' {
- j++
- }
- commentBytes = replaceRange(commentBytes, i, j, rp)
- }
- if _, ok := skipChar[commentBytes[i]]; ok && !skipFlag {
- skipFlag = true
- } else if _, ok := skipCharEnd[commentBytes[i]]; ok && skipFlag {
- skipFlag = false
- }
- }
- } else {
- for i < len(commentBytes) && commentBytes[i] == ' ' {
- i++
- }
- if i >= len(commentBytes) {
- return comment
- }
- commentBytes = replaceRange(commentBytes, attrLen, i, rp)
- }
- return string(commentBytes)
-}
-
-func replaceRange(s []byte, start, end int, new byte) []byte {
- if start > end || end < 1 {
- return s
- }
- if end > len(s) {
- end = len(s)
- }
- s = append(s[:start], s[end-1:]...)
- s[start] = new
- return s
-}
-
-var swagCommentExpression = regexp.MustCompile("@[A-z]+")
-
-func isSwagComment(comment string) bool {
- return swagCommentExpression.MatchString(strings.ToLower(comment))
-}
-
-func isBlankComment(comment string) bool {
- lc := strings.TrimSpace(comment)
- return len(lc) == 0
-}
-
-// writeBack write to file
-func writeBack(filepath string, src, old []byte) error {
- // make a temporary backup before overwriting original
- bakname, err := backupFile(filepath+".", old, 0644)
- if err != nil {
- return err
- }
- err = ioutil.WriteFile(filepath, src, 0644)
- if err != nil {
- _ = os.Rename(bakname, filepath)
- return err
- }
- _ = os.Remove(bakname)
- return nil
-}
-
-const chmodSupported = runtime.GOOS != "windows"
-
-// backupFile writes data to a new file named filename with permissions perm,
-// with 0 {
+ i += skipLen
+ }
+ } else if body[i] == ' ' {
+ j := i
+ for ; j < len(body) && body[j] == ' '; j++ {
+ }
+ body = replaceRange(body, i, j, "\t")
+ }
+ }
+ }
+ return body
+}
+
+func replaceRange(s string, start, end int, new string) string {
+ return s[:start] + new + s[end:]
+}
+
+var swagCommentLineExpression = regexp.MustCompile(`^\/\/\s+(@[\S.]+)\s*(.*)`)
+
+func swagComment(comment string) (string, string, bool) {
+ matches := swagCommentLineExpression.FindStringSubmatch(comment)
+ if matches == nil {
+ return "", "", false
+ }
+ return matches[1], matches[2], true
+}
diff --git a/vendor/github.com/swaggo/swag/generics.go b/vendor/github.com/swaggo/swag/generics.go
new file mode 100644
index 0000000..7a7ad02
--- /dev/null
+++ b/vendor/github.com/swaggo/swag/generics.go
@@ -0,0 +1,109 @@
+//go:build go1.18
+// +build go1.18
+
+package swag
+
+import (
+ "go/ast"
+ "strings"
+)
+
+func typeSpecFullName(typeSpecDef *TypeSpecDef) string {
+ fullName := typeSpecDef.FullName()
+
+ if typeSpecDef.TypeSpec.TypeParams != nil {
+ fullName = fullName + "["
+ for i, typeParam := range typeSpecDef.TypeSpec.TypeParams.List {
+ if i > 0 {
+ fullName = fullName + "-"
+ }
+
+ fullName = fullName + typeParam.Names[0].Name
+ }
+ fullName = fullName + "]"
+ }
+
+ return fullName
+}
+
+func (pkgDefs *PackagesDefinitions) parametrizeStruct(original *TypeSpecDef, fullGenericForm string) *TypeSpecDef {
+ genericParams := strings.Split(strings.TrimRight(fullGenericForm, "]"), "[")
+ if len(genericParams) == 1 {
+ return nil
+ }
+
+ genericParams = strings.Split(genericParams[1], ",")
+ for i, p := range genericParams {
+ genericParams[i] = strings.TrimSpace(p)
+ }
+ genericParamTypeDefs := map[string]*TypeSpecDef{}
+
+ if len(genericParams) != len(original.TypeSpec.TypeParams.List) {
+ return nil
+ }
+
+ for i, genericParam := range genericParams {
+ tdef, ok := pkgDefs.uniqueDefinitions[genericParam]
+ if !ok {
+ return nil
+ }
+
+ genericParamTypeDefs[original.TypeSpec.TypeParams.List[i].Names[0].Name] = tdef
+ }
+
+ parametrizedTypeSpec := &TypeSpecDef{
+ File: original.File,
+ PkgPath: original.PkgPath,
+ TypeSpec: &ast.TypeSpec{
+ Doc: original.TypeSpec.Doc,
+ Comment: original.TypeSpec.Comment,
+ Assign: original.TypeSpec.Assign,
+ },
+ }
+
+ ident := &ast.Ident{
+ NamePos: original.TypeSpec.Name.NamePos,
+ Obj: original.TypeSpec.Name.Obj,
+ }
+
+ genNameParts := strings.Split(fullGenericForm, "[")
+ if strings.Contains(genNameParts[0], ".") {
+ genNameParts[0] = strings.Split(genNameParts[0], ".")[1]
+ }
+
+ ident.Name = genNameParts[0] + "-" + strings.Replace(strings.Join(genericParams, "-"), ".", "_", -1)
+ ident.Name = strings.Replace(strings.Replace(ident.Name, "\t", "", -1), " ", "", -1)
+
+ parametrizedTypeSpec.TypeSpec.Name = ident
+
+ origStructType := original.TypeSpec.Type.(*ast.StructType)
+
+ newStructTypeDef := &ast.StructType{
+ Struct: origStructType.Struct,
+ Incomplete: origStructType.Incomplete,
+ Fields: &ast.FieldList{
+ Opening: origStructType.Fields.Opening,
+ Closing: origStructType.Fields.Closing,
+ },
+ }
+
+ for _, field := range origStructType.Fields.List {
+ newField := &ast.Field{
+ Doc: field.Doc,
+ Names: field.Names,
+ Tag: field.Tag,
+ Comment: field.Comment,
+ }
+ if genTypeSpec, ok := genericParamTypeDefs[field.Type.(*ast.Ident).Name]; ok {
+ newField.Type = genTypeSpec.TypeSpec.Type
+ } else {
+ newField.Type = field.Type
+ }
+
+ newStructTypeDef.Fields.List = append(newStructTypeDef.Fields.List, newField)
+ }
+
+ parametrizedTypeSpec.TypeSpec.Type = newStructTypeDef
+
+ return parametrizedTypeSpec
+}
diff --git a/vendor/github.com/swaggo/swag/generics_other.go b/vendor/github.com/swaggo/swag/generics_other.go
new file mode 100644
index 0000000..a695023
--- /dev/null
+++ b/vendor/github.com/swaggo/swag/generics_other.go
@@ -0,0 +1,12 @@
+//go:build !go1.18
+// +build !go1.18
+
+package swag
+
+func typeSpecFullName(typeSpecDef *TypeSpecDef) string {
+ return typeSpecDef.FullName()
+}
+
+func (pkgDefs *PackagesDefinitions) parametrizeStruct(original *TypeSpecDef, fullGenericForm string) *TypeSpecDef {
+ return original
+}
diff --git a/vendor/github.com/swaggo/swag/golist.go b/vendor/github.com/swaggo/swag/golist.go
new file mode 100644
index 0000000..b8663ab
--- /dev/null
+++ b/vendor/github.com/swaggo/swag/golist.go
@@ -0,0 +1,74 @@
+package swag
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "go/build"
+ "os/exec"
+ "path/filepath"
+)
+
+func listPackages(ctx context.Context, dir string, env []string, args ...string) (pkgs []*build.Package, finalErr error) {
+ cmd := exec.CommandContext(ctx, "go", append([]string{"list", "-json", "-e"}, args...)...)
+ cmd.Env = env
+ cmd.Dir = dir
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+ var stderrBuf bytes.Buffer
+ cmd.Stderr = &stderrBuf
+ defer func() {
+ if stderrBuf.Len() > 0 {
+ finalErr = fmt.Errorf("%v\n%s", finalErr, stderrBuf.Bytes())
+ }
+ }()
+
+ err = cmd.Start()
+ if err != nil {
+ return nil, err
+ }
+ dec := json.NewDecoder(stdout)
+ for dec.More() {
+ var pkg build.Package
+ err = dec.Decode(&pkg)
+ if err != nil {
+ return nil, err
+ }
+ pkgs = append(pkgs, &pkg)
+ }
+ err = cmd.Wait()
+ if err != nil {
+ return nil, err
+ }
+ return pkgs, nil
+}
+
+func (parser *Parser) getAllGoFileInfoFromDepsByList(pkg *build.Package) error {
+ ignoreInternal := pkg.Goroot && !parser.ParseInternal
+ if ignoreInternal { // ignored internal
+ return nil
+ }
+
+ srcDir := pkg.Dir
+ var err error
+ for i := range pkg.GoFiles {
+ err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.GoFiles[i]), nil)
+ if err != nil {
+ return err
+ }
+ }
+
+ // parse .go source files that import "C"
+ for i := range pkg.CgoFiles {
+ err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.CgoFiles[i]), nil)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/swaggo/swag/operation.go b/vendor/github.com/swaggo/swag/operation.go
index 66d7ca5..20e7cef 100644
--- a/vendor/github.com/swaggo/swag/operation.go
+++ b/vendor/github.com/swaggo/swag/operation.go
@@ -62,8 +62,23 @@ func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
RouterProperties: []RouteProperties{},
Operation: spec.Operation{
OperationProps: spec.OperationProps{
+ ID: "",
+ Description: "",
+ Summary: "",
+ Security: nil,
+ ExternalDocs: nil,
+ Deprecated: false,
+ Tags: []string{},
+ Consumes: []string{},
+ Produces: []string{},
+ Schemes: []string{},
+ Parameters: []spec.Parameter{},
Responses: &spec.Responses{
+ VendorExtensible: spec.VendorExtensible{
+ Extensions: spec.Extensions{},
+ },
ResponsesProps: spec.ResponsesProps{
+ Default: nil,
StatusCodeResponses: make(map[int]spec.Response),
},
},
@@ -72,6 +87,7 @@ func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
Extensions: spec.Extensions{},
},
},
+ codeExampleFilesDir: "",
}
for _, option := range options {
@@ -94,11 +110,10 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
if len(commentLine) == 0 {
return nil
}
+
attribute := strings.Fields(commentLine)[0]
- lineRemainder := strings.TrimSpace(commentLine[len(attribute):])
- lowerAttribute := strings.ToLower(attribute)
+ lineRemainder, lowerAttribute := strings.TrimSpace(commentLine[len(attribute):]), strings.ToLower(attribute)
- var err error
switch lowerAttribute {
case descriptionAttr:
operation.ParseDescriptionComment(lineRemainder)
@@ -107,6 +122,7 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
if err != nil {
return err
}
+
operation.ParseDescriptionComment(string(commentInfo))
case summaryAttr:
operation.Summary = lineRemainder
@@ -115,28 +131,28 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
case tagsAttr:
operation.ParseTagsComment(lineRemainder)
case acceptAttr:
- err = operation.ParseAcceptComment(lineRemainder)
+ return operation.ParseAcceptComment(lineRemainder)
case produceAttr:
- err = operation.ParseProduceComment(lineRemainder)
+ return operation.ParseProduceComment(lineRemainder)
case paramAttr:
- err = operation.ParseParamComment(lineRemainder, astFile)
+ return operation.ParseParamComment(lineRemainder, astFile)
case successAttr, failureAttr, responseAttr:
- err = operation.ParseResponseComment(lineRemainder, astFile)
+ return operation.ParseResponseComment(lineRemainder, astFile)
case headerAttr:
- err = operation.ParseResponseHeaderComment(lineRemainder, astFile)
+ return operation.ParseResponseHeaderComment(lineRemainder, astFile)
case routerAttr:
- err = operation.ParseRouterComment(lineRemainder)
+ return operation.ParseRouterComment(lineRemainder)
case securityAttr:
- err = operation.ParseSecurityComment(lineRemainder)
+ return operation.ParseSecurityComment(lineRemainder)
case deprecatedAttr:
operation.Deprecate()
case xCodeSamplesAttr:
- err = operation.ParseCodeSample(attribute, commentLine, lineRemainder)
+ return operation.ParseCodeSample(attribute, commentLine, lineRemainder)
default:
- err = operation.ParseMetadata(attribute, lowerAttribute, lineRemainder)
+ return operation.ParseMetadata(attribute, lowerAttribute, lineRemainder)
}
- return err
+ return nil
}
// ParseCodeSample godoc.
@@ -148,6 +164,7 @@ func (operation *Operation) ParseCodeSample(attribute, _, lineRemainder string)
}
var valueJSON interface{}
+
err = json.Unmarshal(data, &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -170,6 +187,7 @@ func (operation *Operation) ParseDescriptionComment(lineRemainder string) {
return
}
+
operation.Description += "\n" + lineRemainder
}
@@ -182,6 +200,7 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
}
var valueJSON interface{}
+
err := json.Unmarshal([]byte(lineRemainder), &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -194,7 +213,7 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
return nil
}
-var paramPattern = regexp.MustCompile(`(\S+)[\s]+([\w]+)[\s]+([\S.]+)[\s]+([\w]+)[\s]+"([^"]+)"`)
+var paramPattern = regexp.MustCompile(`(\S+)\s+(\w+)\s+([\S.]+)\s+(\w+)\s+"([^"]+)"`)
func findInSlice(arr []string, target string) bool {
for _, str := range arr {
@@ -210,13 +229,39 @@ func (operation *Operation) parseArrayParam(param *spec.Parameter, paramType, re
if !IsPrimitiveType(refType) {
return fmt.Errorf("%s is not supported array type for %s", refType, paramType)
}
+
param.SimpleSchema.Type = objectType
+
if operation.parser != nil {
param.CollectionFormat = TransToValidCollectionFormat(operation.parser.collectionFormatInQuery)
}
+
param.SimpleSchema.Items = &spec.Items{
SimpleSchema: spec.SimpleSchema{
- Type: refType,
+ Default: nil,
+ Nullable: false,
+ Format: "",
+ Items: nil,
+ CollectionFormat: "",
+ Type: refType,
+ Example: nil,
+ },
+ CommonValidations: spec.CommonValidations{
+ Maximum: nil,
+ ExclusiveMaximum: false,
+ Minimum: nil,
+ ExclusiveMinimum: false,
+ MaxLength: nil,
+ MinLength: nil,
+ Pattern: "",
+ MaxItems: nil,
+ MinItems: nil,
+ UniqueItems: false,
+ MultipleOf: nil,
+ Enum: nil,
+ },
+ VendorExtensible: spec.VendorExtensible{
+ Extensions: nil,
},
}
@@ -232,6 +277,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if len(matches) != 6 {
return fmt.Errorf("missing required param comment parameters \"%s\"", commentLine)
}
+
name := matches[1]
paramType := matches[2]
refType := TransToValidSchemeType(matches[3])
@@ -248,7 +294,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
}
requiredText := strings.ToLower(matches[4])
- required := requiredText == "true" || requiredText == "required"
+ required := requiredText == "true" || requiredText == requiredLabel
description := matches[5]
param := createParameter(paramType, description, name, refType, required)
@@ -276,27 +322,30 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if err != nil {
return err
}
+
if len(schema.Properties) == 0 {
return nil
}
items := schema.Properties.ToOrderedSchemaItems()
+
for _, item := range items {
- name := item.Name
- prop := item.Schema
+ name, prop := item.Name, item.Schema
if len(prop.Type) == 0 {
continue
}
+
switch {
- case prop.Type[0] == ARRAY &&
- prop.Items.Schema != nil &&
- len(prop.Items.Schema.Type) > 0 &&
- IsSimplePrimitiveType(prop.Items.Schema.Type[0]):
+ case prop.Type[0] == ARRAY && prop.Items.Schema != nil &&
+ len(prop.Items.Schema.Type) > 0 && IsSimplePrimitiveType(prop.Items.Schema.Type[0]):
+
param = createParameter(paramType, prop.Description, name, prop.Type[0], findInSlice(schema.Required, name))
param.SimpleSchema.Type = prop.Type[0]
+
if operation.parser != nil && operation.parser.collectionFormatInQuery != "" && param.CollectionFormat == "" {
param.CollectionFormat = TransToValidCollectionFormat(operation.parser.collectionFormatInQuery)
}
+
param.SimpleSchema.Items = &spec.Items{
SimpleSchema: spec.SimpleSchema{
Type: prop.Items.Schema.Type[0],
@@ -309,6 +358,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
continue
}
+
param.Nullable = prop.Nullable
param.Format = prop.Format
param.Default = prop.Default
@@ -335,20 +385,22 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if objectType == PRIMITIVE {
param.Schema = PrimitiveSchema(refType)
} else {
- schema, err := operation.parseAPIObjectSchema(objectType, refType, astFile)
+ schema, err := operation.parseAPIObjectSchema(commentLine, objectType, refType, astFile)
if err != nil {
return err
}
+
param.Schema = schema
}
default:
return fmt.Errorf("%s is not supported paramType", paramType)
}
- err := operation.parseAndExtractionParamAttribute(commentLine, objectType, refType, ¶m)
+ err := operation.parseParamAttribute(commentLine, objectType, refType, ¶m)
if err != nil {
return err
}
+
operation.Operation.Parameters = append(operation.Operation.Parameters, param)
return nil
@@ -365,8 +417,8 @@ const (
validateTag = "validate"
minimumTag = "minimum"
maximumTag = "maximum"
- minLengthTag = "minlength"
- maxLengthTag = "maxlength"
+ minLengthTag = "minLength"
+ maxLengthTag = "maxLength"
multipleOfTag = "multipleOf"
readOnlyTag = "readonly"
extensionsTag = "extensions"
@@ -398,22 +450,24 @@ var regexAttributes = map[string]*regexp.Regexp{
schemaExampleTag: regexp.MustCompile(`(?i)\s+schemaExample\(.*\)`),
}
-func (operation *Operation) parseAndExtractionParamAttribute(commentLine, objectType, schemaType string, param *spec.Parameter) error {
+func (operation *Operation) parseParamAttribute(comment, objectType, schemaType string, param *spec.Parameter) error {
schemaType = TransToValidSchemeType(schemaType)
+
for attrKey, re := range regexAttributes {
- attr, err := findAttr(re, commentLine)
+ attr, err := findAttr(re, comment)
if err != nil {
continue
}
+
switch attrKey {
case enumsTag:
err = setEnumParam(param, attr, objectType, schemaType)
case minimumTag, maximumTag:
- err = setNumberParam(param, attrKey, schemaType, attr, commentLine)
+ err = setNumberParam(param, attrKey, schemaType, attr, comment)
case defaultTag:
err = setDefault(param, schemaType, attr)
case minLengthTag, maxLengthTag:
- err = setStringParam(param, attrKey, schemaType, attr, commentLine)
+ err = setStringParam(param, attrKey, schemaType, attr, comment)
case formatTag:
param.Format = attr
case exampleTag:
@@ -421,10 +475,11 @@ func (operation *Operation) parseAndExtractionParamAttribute(commentLine, object
case schemaExampleTag:
err = setSchemaExample(param, schemaType, attr)
case extensionsTag:
- _ = setExtensionParam(param, attr)
+ param.Extensions = setExtensionParam(attr)
case collectionFormatTag:
- err = setCollectionFormatParam(param, attrKey, objectType, attr, commentLine)
+ err = setCollectionFormatParam(param, attrKey, objectType, attr, comment)
}
+
if err != nil {
return err
}
@@ -435,8 +490,8 @@ func (operation *Operation) parseAndExtractionParamAttribute(commentLine, object
func findAttr(re *regexp.Regexp, commentLine string) (string, error) {
attr := re.FindString(commentLine)
- l := strings.Index(attr, "(")
- r := strings.Index(attr, ")")
+
+ l, r := strings.Index(attr, "("), strings.Index(attr, ")")
if l == -1 || r == -1 {
return "", fmt.Errorf("can not find regex=%s, comment=%s", re.String(), commentLine)
}
@@ -471,12 +526,14 @@ func setNumberParam(param *spec.Parameter, name, schemaType, attr, commentLine s
if err != nil {
return fmt.Errorf("maximum is allow only a number. comment=%s got=%s", commentLine, attr)
}
+
switch name {
case minimumTag:
param.Minimum = &n
case maximumTag:
param.Maximum = &n
}
+
return nil
default:
return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType)
@@ -503,23 +560,33 @@ func setEnumParam(param *spec.Parameter, attr, objectType, schemaType string) er
return nil
}
-func setExtensionParam(param *spec.Parameter, attr string) error {
- param.Extensions = map[string]interface{}{}
+func setExtensionParam(attr string) spec.Extensions {
+ extensions := spec.Extensions{}
+
for _, val := range splitNotWrapped(attr, ',') {
parts := strings.SplitN(val, "=", 2)
if len(parts) == 2 {
- param.Extensions.Add(parts[0], parts[1])
+ extensions.Add(parts[0], parts[1])
continue
}
- param.Extensions.Add(parts[0], true)
+
+ if len(parts[0]) > 0 && string(parts[0][0]) == "!" {
+ extensions.Add(parts[0][1:], false)
+
+ continue
+ }
+
+ extensions.Add(parts[0], true)
}
- return nil
+
+ return extensions
}
func setCollectionFormatParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error {
if schemaType == ARRAY {
param.CollectionFormat = TransToValidCollectionFormat(attr)
+
return nil
}
@@ -531,13 +598,12 @@ func setDefault(param *spec.Parameter, schemaType string, value string) error {
if err != nil {
return nil // Don't set a default value if it's not valid
}
+
param.Default = val
+
return nil
}
-// controlCharReplacer replaces \r \n \t in example string values
-var controlCharReplacer = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t")
-
func setSchemaExample(param *spec.Parameter, schemaType string, value string) error {
val, err := defineType(schemaType, value)
if err != nil {
@@ -550,7 +616,8 @@ func setSchemaExample(param *spec.Parameter, schemaType string, value string) er
switch v := val.(type) {
case string:
- param.Schema.Example = controlCharReplacer.Replace(v)
+ // replaces \r \n \t in example string values.
+ param.Schema.Example = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t").Replace(v)
default:
param.Schema.Example = val
}
@@ -563,13 +630,16 @@ func setExample(param *spec.Parameter, schemaType string, value string) error {
if err != nil {
return nil // Don't set a example value if it's not valid
}
+
param.Example = val
+
return nil
}
// defineType enum value define the type (object and array unsupported).
func defineType(schemaType string, value string) (v interface{}, err error) {
schemaType = TransToValidSchemeType(schemaType)
+
switch schemaType {
case STRING:
return value, nil
@@ -597,8 +667,7 @@ func defineType(schemaType string, value string) (v interface{}, err error) {
// ParseTagsComment parses comment for given `tag` comment string.
func (operation *Operation) ParseTagsComment(commentLine string) {
- tags := strings.Split(commentLine, ",")
- for _, tag := range tags {
+ for _, tag := range strings.Split(commentLine, ",") {
operation.Tags = append(operation.Tags, strings.TrimSpace(tag))
}
}
@@ -617,13 +686,13 @@ func (operation *Operation) ParseProduceComment(commentLine string) error {
// `produce` (`Content-Type:` response header) or
// `accept` (`Accept:` request header).
func parseMimeTypeList(mimeTypeList string, typeList *[]string, format string) error {
- mimeTypes := strings.Split(mimeTypeList, ",")
- for _, typeName := range mimeTypes {
+ for _, typeName := range strings.Split(mimeTypeList, ",") {
if mimeTypePattern.MatchString(typeName) {
*typeList = append(*typeList, typeName)
continue
}
+
aliasMimeType, ok := mimeTypeAliases[typeName]
if !ok {
return fmt.Errorf(format, typeName)
@@ -643,6 +712,7 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {
if len(matches) != 3 {
return fmt.Errorf("can not parse router comment \"%s\"", commentLine)
}
+
signature := RouteProperties{
Path: matches[1],
HTTPMethod: strings.ToUpper(matches[2]),
@@ -659,35 +729,41 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {
// ParseSecurityComment parses comment for given `security` comment string.
func (operation *Operation) ParseSecurityComment(commentLine string) error {
- //var securityMap map[string][]string = map[string][]string{}
+ var (
+ securityMap = make(map[string][]string)
+ securitySource = commentLine[strings.Index(commentLine, "@Security")+1:]
+ )
- var securityMap = make(map[string][]string)
- securitySource := commentLine[strings.Index(commentLine, "@Security")+1:]
for _, securityOption := range strings.Split(securitySource, "||") {
securityOption = strings.TrimSpace(securityOption)
- l := strings.Index(securityOption, "[")
- r := strings.Index(securityOption, "]")
- if !(l == -1 && r == -1) {
- scopes := securityOption[l+1 : r]
- var s []string
+
+ left, right := strings.Index(securityOption, "["), strings.Index(securityOption, "]")
+
+ if !(left == -1 && right == -1) {
+ scopes := securityOption[left+1 : right]
+
+ var options []string
+
for _, scope := range strings.Split(scopes, ",") {
- s = append(s, strings.TrimSpace(scope))
+ options = append(options, strings.TrimSpace(scope))
}
- securityKey := securityOption[0:l]
- securityMap[securityKey] = append(securityMap[securityKey], s...)
+ securityKey := securityOption[0:left]
+ securityMap[securityKey] = append(securityMap[securityKey], options...)
} else {
securityKey := strings.TrimSpace(securityOption)
securityMap[securityKey] = []string{}
}
}
+
operation.Security = append(operation.Security, securityMap)
+
return nil
}
// findTypeDef attempts to find the *ast.TypeSpec for a specific type given the
// type's name and the package's import path.
-// TODO: improve finding external pkg
+// TODO: improve finding external pkg.
func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
cwd, err := os.Getwd()
if err != nil {
@@ -723,7 +799,6 @@ func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
}
// TODO: possibly cache pkgInfo since it's an expensive operation
-
for i := range pkgInfo.Files {
for _, astDeclaration := range pkgInfo.Files[i].Decls {
generalDeclaration, ok := astDeclaration.(*ast.GenDecl)
@@ -743,7 +818,7 @@ func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
return nil, fmt.Errorf("type spec not found")
}
-var responsePattern = regexp.MustCompile(`^([\w,]+)[\s]+([\w{}]+)[\s]+([\w\-.\\{}=,\[\]]+)[^"]*(.*)?`)
+var responsePattern = regexp.MustCompile(`^([\w,]+)\s+([\w{}]+)\s+([\w\-.\\{}=,\[\]]+)[^"]*(.*)?`)
// ResponseType{data1=Type1,data2=Type2}.
var combinedPattern = regexp.MustCompile(`^([\w\-./\[\]]+){(.*)}$`)
@@ -752,9 +827,9 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
switch {
case refType == NIL:
return nil, nil
- case refType == "interface{}":
+ case refType == INTERFACE:
return PrimitiveSchema(OBJECT), nil
- case refType == "any":
+ case refType == ANY:
return PrimitiveSchema(OBJECT), nil
case IsGolangPrimitiveType(refType):
refType = TransToValidSchemeType(refType)
@@ -775,10 +850,12 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
if idx < 0 {
return nil, fmt.Errorf("invalid type: %s", refType)
}
+
refType = refType[idx+1:]
- if refType == "interface{}" || refType == "any" {
+ if refType == INTERFACE || refType == ANY {
return spec.MapProperty(nil), nil
}
+
schema, err := operation.parseObjectSchema(refType, astFile)
if err != nil {
return nil, err
@@ -801,45 +878,46 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
}
}
+func parseFields(s string) []string {
+ nestLevel := 0
+
+ return strings.FieldsFunc(s, func(char rune) bool {
+ if char == '{' {
+ nestLevel++
+
+ return false
+ } else if char == '}' {
+ nestLevel--
+
+ return false
+ }
+
+ return char == ',' && nestLevel == 0
+ })
+}
+
func (operation *Operation) parseCombinedObjectSchema(refType string, astFile *ast.File) (*spec.Schema, error) {
matches := combinedPattern.FindStringSubmatch(refType)
if len(matches) != 3 {
return nil, fmt.Errorf("invalid type: %s", refType)
}
- refType = matches[1]
- schema, err := operation.parseObjectSchema(refType, astFile)
+
+ schema, err := operation.parseObjectSchema(matches[1], astFile)
if err != nil {
return nil, err
}
- parseFields := func(s string) []string {
- n := 0
-
- return strings.FieldsFunc(s, func(r rune) bool {
- if r == '{' {
- n++
+ fields, props := parseFields(matches[2]), map[string]spec.Schema{}
- return false
- } else if r == '}' {
- n--
-
- return false
- }
-
- return r == ',' && n == 0
- })
- }
-
- fields := parseFields(matches[2])
- props := map[string]spec.Schema{}
for _, field := range fields {
- matches := strings.SplitN(field, "=", 2)
- if len(matches) == 2 {
- schema, err := operation.parseObjectSchema(matches[1], astFile)
+ keyVal := strings.SplitN(field, "=", 2)
+ if len(keyVal) == 2 {
+ schema, err := operation.parseObjectSchema(keyVal[1], astFile)
if err != nil {
return nil, err
}
- props[matches[0]] = *schema
+
+ props[keyVal[0]] = *schema
}
}
@@ -855,12 +933,22 @@ func (operation *Operation) parseCombinedObjectSchema(refType string, astFile *a
}), nil
}
-func (operation *Operation) parseAPIObjectSchema(schemaType, refType string, astFile *ast.File) (*spec.Schema, error) {
+func (operation *Operation) parseAPIObjectSchema(commentLine, schemaType, refType string, astFile *ast.File) (*spec.Schema, error) {
+ if strings.HasSuffix(refType, ",") && strings.Contains(refType, "[") {
+ // regexp may have broken generics syntax. find closing bracket and add it back
+ allMatchesLenOffset := strings.Index(commentLine, refType) + len(refType)
+ lostPartEndIdx := strings.Index(commentLine[allMatchesLenOffset:], "]")
+ if lostPartEndIdx >= 0 {
+ refType += commentLine[allMatchesLenOffset : allMatchesLenOffset+lostPartEndIdx+1]
+ }
+ }
+
switch schemaType {
case OBJECT:
if !strings.HasPrefix(refType, "[]") {
return operation.parseObjectSchema(refType, astFile)
}
+
refType = refType[2:]
fallthrough
@@ -889,7 +977,8 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
}
description := strings.Trim(matches[4], "\"")
- schema, err := operation.parseAPIObjectSchema(strings.Trim(matches[2], "{}"), matches[3], astFile)
+
+ schema, err := operation.parseAPIObjectSchema(commentLine, strings.Trim(matches[2], "{}"), matches[3], astFile)
if err != nil {
return err
}
@@ -900,6 +989,7 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
continue
}
+
code, err := strconv.Atoi(codeStr)
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
@@ -924,6 +1014,23 @@ func newHeaderSpec(schemaType, description string) spec.Header {
HeaderProps: spec.HeaderProps{
Description: description,
},
+ VendorExtensible: spec.VendorExtensible{
+ Extensions: nil,
+ },
+ CommonValidations: spec.CommonValidations{
+ Maximum: nil,
+ ExclusiveMaximum: false,
+ Minimum: nil,
+ ExclusiveMinimum: false,
+ MaxLength: nil,
+ MinLength: nil,
+ Pattern: "",
+ MaxItems: nil,
+ MinItems: nil,
+ UniqueItems: false,
+ MultipleOf: nil,
+ Enum: nil,
+ },
}
}
@@ -966,6 +1073,7 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *as
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
}
+
if operation.Responses.StatusCodeResponses != nil {
response, responseExist := operation.Responses.StatusCodeResponses[code]
if responseExist {
@@ -979,7 +1087,7 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *as
return nil
}
-var emptyResponsePattern = regexp.MustCompile(`([\w,]+)[\s]+"(.*)"`)
+var emptyResponsePattern = regexp.MustCompile(`([\w,]+)\s+"(.*)"`)
// ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok".
func (operation *Operation) ParseEmptyResponseComment(commentLine string) error {
@@ -989,6 +1097,7 @@ func (operation *Operation) ParseEmptyResponseComment(commentLine string) error
}
description := strings.Trim(matches[2], "\"")
+
for _, codeStr := range strings.Split(matches[1], ",") {
if strings.EqualFold(codeStr, defaultTag) {
operation.DefaultResponse().WithDescription(description)
@@ -1015,6 +1124,7 @@ func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error {
continue
}
+
code, err := strconv.Atoi(codeStr)
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
@@ -1031,7 +1141,8 @@ func (operation *Operation) DefaultResponse() *spec.Response {
if operation.Responses.Default == nil {
operation.Responses.Default = &spec.Response{
ResponseProps: spec.ResponseProps{
- Headers: make(map[string]spec.Header),
+ Description: "",
+ Headers: make(map[string]spec.Header),
},
}
}
@@ -1044,6 +1155,7 @@ func (operation *Operation) AddResponse(code int, response *spec.Response) {
if response.Headers == nil {
response.Headers = make(map[string]spec.Header)
}
+
operation.Responses.StatusCodeResponses[code] = *response
}
@@ -1052,10 +1164,12 @@ func createParameter(paramType, description, paramName, schemaType string, requi
// //five possible parameter types. query, path, body, header, form
result := spec.Parameter{
ParamProps: spec.ParamProps{
- Name: paramName,
- Description: description,
- Required: required,
- In: paramType,
+ Name: paramName,
+ Description: description,
+ Required: required,
+ In: paramType,
+ Schema: nil,
+ AllowEmptyValue: false,
},
}
@@ -1070,7 +1184,9 @@ func createParameter(paramType, description, paramName, schemaType string, requi
}
result.SimpleSchema = spec.SimpleSchema{
- Type: schemaType,
+ Type: schemaType,
+ Nullable: false,
+ Format: "",
}
return result
@@ -1086,6 +1202,7 @@ func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error
if fileInfo.IsDir() {
continue
}
+
fileName := fileInfo.Name()
if !strings.Contains(fileName, ".json") {
@@ -1094,6 +1211,7 @@ func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error
if strings.Contains(fileName, summaryName) {
fullPath := filepath.Join(dirPath, fileName)
+
commentInfo, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read code example file %s error: %s ", fullPath, err)
diff --git a/vendor/github.com/swaggo/swag/packages.go b/vendor/github.com/swaggo/swag/packages.go
index c454f06..445d095 100644
--- a/vendor/github.com/swaggo/swag/packages.go
+++ b/vendor/github.com/swaggo/swag/packages.go
@@ -6,6 +6,7 @@ import (
"go/token"
"os"
"path/filepath"
+ "runtime"
"sort"
"strings"
@@ -29,13 +30,13 @@ func NewPackagesDefinitions() *PackagesDefinitions {
}
// CollectAstFile collect ast.file.
-func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile *ast.File) error {
- if pkgs.files == nil {
- pkgs.files = make(map[*ast.File]*AstFileInfo)
+func (pkgDefs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile *ast.File) error {
+ if pkgDefs.files == nil {
+ pkgDefs.files = make(map[*ast.File]*AstFileInfo)
}
- if pkgs.packages == nil {
- pkgs.packages = make(map[string]*PackageDefinitions)
+ if pkgDefs.packages == nil {
+ pkgDefs.packages = make(map[string]*PackageDefinitions)
}
// return without storing the file if we lack a packageDir
@@ -48,23 +49,24 @@ func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile
return err
}
- pd, ok := pkgs.packages[packageDir]
+ dependency, ok := pkgDefs.packages[packageDir]
if ok {
// return without storing the file if it already exists
- _, exists := pd.Files[path]
+ _, exists := dependency.Files[path]
if exists {
return nil
}
- pd.Files[path] = astFile
+
+ dependency.Files[path] = astFile
} else {
- pkgs.packages[packageDir] = &PackageDefinitions{
+ pkgDefs.packages[packageDir] = &PackageDefinitions{
Name: astFile.Name.Name,
Files: map[string]*ast.File{path: astFile},
TypeDefinitions: make(map[string]*TypeSpecDef),
}
}
- pkgs.files[astFile] = &AstFileInfo{
+ pkgDefs.files[astFile] = &AstFileInfo{
File: astFile,
Path: path,
PackagePath: packageDir,
@@ -77,6 +79,11 @@ func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile
func rangeFiles(files map[*ast.File]*AstFileInfo, handle func(filename string, file *ast.File) error) error {
sortedFiles := make([]*AstFileInfo, 0, len(files))
for _, info := range files {
+ // ignore package path prefix with 'vendor' or $GOROOT,
+ // because the router info of api will not be included these files.
+ if strings.HasPrefix(info.PackagePath, "vendor") || strings.HasPrefix(info.Path, runtime.GOROOT()) {
+ continue
+ }
sortedFiles = append(sortedFiles, info)
}
@@ -96,15 +103,15 @@ func rangeFiles(files map[*ast.File]*AstFileInfo, handle func(filename string, f
// ParseTypes parse types
// @Return parsed definitions.
-func (pkgs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) {
+func (pkgDefs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) {
parsedSchemas := make(map[*TypeSpecDef]*Schema)
- for astFile, info := range pkgs.files {
- pkgs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas)
+ for astFile, info := range pkgDefs.files {
+ pkgDefs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas)
}
return parsedSchemas, nil
}
-func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
+func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
for _, astDeclaration := range astFile.Decls {
if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE {
for _, astSpec := range generalDeclaration.Specs {
@@ -123,29 +130,30 @@ func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePa
}
}
- if pkgs.uniqueDefinitions == nil {
- pkgs.uniqueDefinitions = make(map[string]*TypeSpecDef)
+ if pkgDefs.uniqueDefinitions == nil {
+ pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef)
}
- fullName := typeSpecDef.FullName()
- anotherTypeDef, ok := pkgs.uniqueDefinitions[fullName]
+ fullName := typeSpecFullName(typeSpecDef)
+
+ anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName]
if ok {
if typeSpecDef.PkgPath == anotherTypeDef.PkgPath {
continue
} else {
- delete(pkgs.uniqueDefinitions, fullName)
+ delete(pkgDefs.uniqueDefinitions, fullName)
}
} else {
- pkgs.uniqueDefinitions[fullName] = typeSpecDef
+ pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
}
- if pkgs.packages[typeSpecDef.PkgPath] == nil {
- pkgs.packages[typeSpecDef.PkgPath] = &PackageDefinitions{
+ if pkgDefs.packages[typeSpecDef.PkgPath] == nil {
+ pkgDefs.packages[typeSpecDef.PkgPath] = &PackageDefinitions{
Name: astFile.Name.Name,
TypeDefinitions: map[string]*TypeSpecDef{typeSpecDef.Name(): typeSpecDef},
}
- } else if _, ok = pkgs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok {
- pkgs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()] = typeSpecDef
+ } else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok {
+ pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()] = typeSpecDef
}
}
}
@@ -153,11 +161,12 @@ func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePa
}
}
-func (pkgs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef {
- if pkgs.packages == nil {
+func (pkgDefs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef {
+ if pkgDefs.packages == nil {
return nil
}
- pd, found := pkgs.packages[pkgPath]
+
+ pd, found := pkgDefs.packages[pkgPath]
if found {
typeSpec, ok := pd.TypeDefinitions[typeName]
if ok {
@@ -168,7 +177,7 @@ func (pkgs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *
return nil
}
-func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
+func (pkgDefs *PackagesDefinitions) loadExternalPackage(importPath string) error {
cwd, err := os.Getwd()
if err != nil {
return err
@@ -189,7 +198,7 @@ func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
for _, info := range loaderProgram.AllPackages {
pkgPath := strings.TrimPrefix(info.Pkg.Path(), "vendor/")
for _, astFile := range info.Files {
- pkgs.parseTypesFromFile(astFile, pkgPath, nil)
+ pkgDefs.parseTypesFromFile(astFile, pkgPath, nil)
}
}
@@ -201,7 +210,7 @@ func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
// @file current ast.File in which to search imports
// @fuzzy search for the package path that the last part matches the @pkg if true
// @return the package path of a package of @pkg.
-func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File, fuzzy bool) string {
+func (pkgDefs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File, fuzzy bool) string {
if file == nil {
return ""
}
@@ -214,6 +223,7 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
matchLastPathPart := func(pkgPath string) bool {
paths := strings.Split(pkgPath, "/")
+
return paths[len(paths)-1] == pkg
}
@@ -223,26 +233,33 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
if imp.Name.Name == pkg {
return strings.Trim(imp.Path.Value, `"`)
}
+
if imp.Name.Name == "_" {
hasAnonymousPkg = true
}
continue
}
- if pkgs.packages != nil {
+
+ if pkgDefs.packages != nil {
path := strings.Trim(imp.Path.Value, `"`)
if fuzzy {
if matchLastPathPart(path) {
return path
}
- } else if pd, ok := pkgs.packages[path]; ok && pd.Name == pkg {
+
+ continue
+ }
+
+ pd, ok := pkgDefs.packages[path]
+ if ok && pd.Name == pkg {
return path
}
}
}
// match unnamed package
- if hasAnonymousPkg && pkgs.packages != nil {
+ if hasAnonymousPkg && pkgDefs.packages != nil {
for _, imp := range file.Imports {
if imp.Name == nil {
continue
@@ -253,7 +270,7 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
if matchLastPathPart(path) {
return path
}
- } else if pd, ok := pkgs.packages[path]; ok && pd.Name == pkg {
+ } else if pd, ok := pkgDefs.packages[path]; ok && pd.Name == pkg {
return path
}
}
@@ -267,15 +284,16 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
// @typeName the name of the target type, if it starts with a package name, find its own package path from imports on top of @file
// @file the ast.file in which @typeName is used
// @pkgPath the package path of @file.
-func (pkgs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, parseDependency bool) *TypeSpecDef {
+func (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, parseDependency bool) *TypeSpecDef {
if IsGolangPrimitiveType(typeName) {
return nil
}
+
if file == nil { // for test
- return pkgs.uniqueDefinitions[typeName]
+ return pkgDefs.uniqueDefinitions[typeName]
}
- parts := strings.Split(typeName, ".")
+ parts := strings.Split(strings.Split(typeName, "[")[0], ".")
if len(parts) > 1 {
isAliasPkgName := func(file *ast.File, pkgName string) bool {
if file != nil && file.Imports != nil {
@@ -290,42 +308,59 @@ func (pkgs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, p
}
if !isAliasPkgName(file, parts[0]) {
- typeDef, ok := pkgs.uniqueDefinitions[typeName]
+ typeDef, ok := pkgDefs.uniqueDefinitions[typeName]
if ok {
return typeDef
}
}
- pkgPath := pkgs.findPackagePathFromImports(parts[0], file, false)
+
+ pkgPath := pkgDefs.findPackagePathFromImports(parts[0], file, false)
if len(pkgPath) == 0 {
// check if the current package
if parts[0] == file.Name.Name {
- pkgPath = pkgs.files[file].PackagePath
+ pkgPath = pkgDefs.files[file].PackagePath
} else if parseDependency {
// take it as an external package, needs to be loaded
- if pkgPath = pkgs.findPackagePathFromImports(parts[0], file, true); len(pkgPath) > 0 {
- if err := pkgs.loadExternalPackage(pkgPath); err != nil {
+ if pkgPath = pkgDefs.findPackagePathFromImports(parts[0], file, true); len(pkgPath) > 0 {
+ if err := pkgDefs.loadExternalPackage(pkgPath); err != nil {
return nil
}
}
}
}
- return pkgs.findTypeSpec(pkgPath, parts[1])
+ if strings.Contains(typeName, "[") {
+ // joinedParts differs from typeName in that it does not contain any type parameters
+ joinedParts := strings.Join(parts, ".")
+ for tName, tSpec := range pkgDefs.uniqueDefinitions {
+ if !strings.Contains(tName, "[") {
+ continue
+ }
+
+ if strings.Contains(tName, joinedParts) {
+ if parametrized := pkgDefs.parametrizeStruct(tSpec, typeName); parametrized != nil {
+ return parametrized
+ }
+ }
+ }
+ }
+
+ return pkgDefs.findTypeSpec(pkgPath, parts[1])
}
- typeDef, ok := pkgs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)]
+ typeDef, ok := pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)]
if ok {
return typeDef
}
- typeDef = pkgs.findTypeSpec(pkgs.files[file].PackagePath, typeName)
+ typeDef = pkgDefs.findTypeSpec(pkgDefs.files[file].PackagePath, typeName)
if typeDef != nil {
return typeDef
}
for _, imp := range file.Imports {
if imp.Name != nil && imp.Name.Name == "." {
- typeDef := pkgs.findTypeSpec(strings.Trim(imp.Path.Value, `"`), typeName)
+ typeDef := pkgDefs.findTypeSpec(strings.Trim(imp.Path.Value, `"`), typeName)
if typeDef != nil {
return typeDef
}
diff --git a/vendor/github.com/swaggo/swag/parser.go b/vendor/github.com/swaggo/swag/parser.go
index 387151a..815b2f8 100644
--- a/vendor/github.com/swaggo/swag/parser.go
+++ b/vendor/github.com/swaggo/swag/parser.go
@@ -1,6 +1,7 @@
package swag
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -48,9 +49,21 @@ const (
deprecatedAttr = "@deprecated"
securityAttr = "@security"
titleAttr = "@title"
+ conNameAttr = "@contact.name"
+ conURLAttr = "@contact.url"
+ conEmailAttr = "@contact.email"
+ licNameAttr = "@license.name"
+ licURLAttr = "@license.url"
versionAttr = "@version"
descriptionAttr = "@description"
descriptionMarkdownAttr = "@description.markdown"
+ secBasicAttr = "@securitydefinitions.basic"
+ secAPIKeyAttr = "@securitydefinitions.apikey"
+ secApplicationAttr = "@securitydefinitions.oauth2.application"
+ secImplicitAttr = "@securitydefinitions.oauth2.implicit"
+ secPasswordAttr = "@securitydefinitions.oauth2.password"
+ secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode"
+ tosAttr = "@termsofservice"
xCodeSamplesAttr = "@x-codesamples"
scopeAttrPrefix = "@scope."
)
@@ -65,7 +78,7 @@ var (
// ErrFailedConvertPrimitiveType Failed to convert for swag to interpretable type.
ErrFailedConvertPrimitiveType = errors.New("swag property: failed convert primitive type")
- // ErrSkippedField .swaggo specifies field should be skipped
+ // ErrSkippedField .swaggo specifies field should be skipped.
ErrSkippedField = errors.New("field is skipped by global overrides")
)
@@ -140,14 +153,17 @@ type Parser struct {
// Overrides allows global replacements of types. A blank replacement will be skipped.
Overrides map[string]string
+
+ // parseGoList whether swag use go list to parse dependency
+ parseGoList bool
}
-// FieldParserFactory create FieldParser
+// FieldParserFactory create FieldParser.
type FieldParserFactory func(ps *Parser, field *ast.Field) FieldParser
-// FieldParser parse struct field
+// FieldParser parse struct field.
type FieldParser interface {
- ShouldSkip() (bool, error)
+ ShouldSkip() bool
FieldName() (string, error)
CustomSchema() (*spec.Schema, error)
ComplementSchema(schema *spec.Schema) error
@@ -161,8 +177,6 @@ type Debugger interface {
// New creates a new Parser with default properties.
func New(options ...func(*Parser)) *Parser {
- // parser.swagger.SecurityDefinitions =
-
parser := &Parser{
swagger: &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
@@ -177,10 +191,16 @@ func New(options ...func(*Parser)) *Parser {
},
Paths: &spec.Paths{
Paths: make(map[string]spec.PathItem),
+ VendorExtensible: spec.VendorExtensible{
+ Extensions: nil,
+ },
},
Definitions: make(map[string]spec.Schema),
SecurityDefinitions: make(map[string]*spec.SecurityScheme),
},
+ VendorExtensible: spec.VendorExtensible{
+ Extensions: nil,
+ },
},
packages: NewPackagesDefinitions(),
debug: log.New(os.Stdout, "", log.LstdFlags),
@@ -237,7 +257,10 @@ func SetStrict(strict bool) func(*Parser) {
// SetDebugger allows the use of user-defined implementations.
func SetDebugger(logger Debugger) func(parser *Parser) {
return func(p *Parser) {
- p.debug = logger
+ if logger != nil {
+ p.debug = logger
+ }
+
}
}
@@ -257,6 +280,13 @@ func SetOverrides(overrides map[string]string) func(parser *Parser) {
}
}
+// ParseUsingGoList sets whether swag use go list to parse dependency
+func ParseUsingGoList(enabled bool) func(parser *Parser) {
+ return func(p *Parser) {
+ p.parseGoList = enabled
+ }
+}
+
// ParseAPI parses general api info for given searchDir and mainAPIFile.
func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string, parseDepth int) error {
return parser.ParseAPIMultiSearchDir([]string{searchDir}, mainAPIFile, parseDepth)
@@ -283,26 +313,41 @@ func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, mainAPIFile st
return err
}
+ // Use 'go list' command instead of depth.Resolve()
if parser.ParseDependency {
- var t depth.Tree
- t.ResolveInternal = true
- t.MaxDepth = parseDepth
-
- pkgName, err := getPkgName(filepath.Dir(absMainAPIFilePath))
- if err != nil {
- return err
- }
+ if parser.parseGoList {
+ pkgs, err := listPackages(context.Background(), filepath.Dir(absMainAPIFilePath), nil, "-deps")
+ if err != nil {
+ return fmt.Errorf("pkg %s cannot find all dependencies, %s", filepath.Dir(absMainAPIFilePath), err)
+ }
- err = t.Resolve(pkgName)
- if err != nil {
- return fmt.Errorf("pkg %s cannot find all dependencies, %s", pkgName, err)
- }
+ length := len(pkgs)
+ for i := 0; i < length; i++ {
+ err := parser.getAllGoFileInfoFromDepsByList(pkgs[i])
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ var t depth.Tree
+ t.ResolveInternal = true
+ t.MaxDepth = parseDepth
- for i := 0; i < len(t.Root.Deps); i++ {
- err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i])
+ pkgName, err := getPkgName(filepath.Dir(absMainAPIFilePath))
if err != nil {
return err
}
+
+ err = t.Resolve(pkgName)
+ if err != nil {
+ return fmt.Errorf("pkg %s cannot find all dependencies, %s", pkgName, err)
+ }
+ for i := 0; i < len(t.Root.Deps); i++ {
+ err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i])
+ if err != nil {
+ return err
+ }
+ }
}
}
@@ -329,7 +374,9 @@ func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, mainAPIFile st
func getPkgName(searchDir string) (string, error) {
cmd := exec.Command("go", "list", "-f={{.ImportPath}}")
cmd.Dir = searchDir
+
var stdout, stderr strings.Builder
+
cmd.Stdout = &stdout
cmd.Stderr = &stderr
@@ -342,20 +389,14 @@ func getPkgName(searchDir string) (string, error) {
if outStr[0] == '_' { // will shown like _/{GOPATH}/src/{YOUR_PACKAGE} when NOT enable GO MODULE.
outStr = strings.TrimPrefix(outStr, "_"+build.Default.GOPATH+"/src/")
}
+
f := strings.Split(outStr, "\n")
+
outStr = f[0]
return outStr, nil
}
-func initIfEmpty(license *spec.License) *spec.License {
- if license == nil {
- return new(spec.License)
- }
-
- return license
-}
-
// ParseGeneralAPIInfo parses general api info for given mainAPIFile path.
func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
fileTree, err := goparser.ParseFile(token.NewFileSet(), mainAPIFile, nil, goparser.ParseComments)
@@ -370,7 +411,8 @@ func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
if !isGeneralAPIComment(comments) {
continue
}
- err := parseGeneralAPIInfo(parser, comments)
+
+ err = parseGeneralAPIInfo(parser, comments)
if err != nil {
return err
}
@@ -383,49 +425,40 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
previousAttribute := ""
// parsing classic meta data model
- for i, commentLine := range comments {
+ for line := 0; line < len(comments); line++ {
+ commentLine := comments[line]
attribute := strings.Split(commentLine, " ")[0]
value := strings.TrimSpace(commentLine[len(attribute):])
+
multilineBlock := false
if previousAttribute == attribute {
multilineBlock = true
}
- switch strings.ToLower(attribute) {
- case versionAttr:
- parser.swagger.Info.Version = value
- case titleAttr:
- parser.swagger.Info.Title = value
+
+ switch attr := strings.ToLower(attribute); attr {
+ case versionAttr, titleAttr, tosAttr, licNameAttr, licURLAttr, conNameAttr, conURLAttr, conEmailAttr:
+ setSwaggerInfo(parser.swagger, attr, value)
case descriptionAttr:
if multilineBlock {
parser.swagger.Info.Description += "\n" + value
continue
}
- parser.swagger.Info.Description = value
- case "@description.markdown":
+
+ setSwaggerInfo(parser.swagger, attr, value)
+ case descriptionMarkdownAttr:
commentInfo, err := getMarkdownForTag("api", parser.markdownFileDir)
if err != nil {
return err
}
- parser.swagger.Info.Description = string(commentInfo)
- case "@termsofservice":
- parser.swagger.Info.TermsOfService = value
- case "@contact.name":
- parser.swagger.Info.Contact.Name = value
- case "@contact.email":
- parser.swagger.Info.Contact.Email = value
- case "@contact.url":
- parser.swagger.Info.Contact.URL = value
- case "@license.name":
- parser.swagger.Info.License = initIfEmpty(parser.swagger.Info.License)
- parser.swagger.Info.License.Name = value
- case "@license.url":
- parser.swagger.Info.License = initIfEmpty(parser.swagger.Info.License)
- parser.swagger.Info.License.URL = value
+
+ setSwaggerInfo(parser.swagger, descriptionAttr, string(commentInfo))
+
case "@host":
parser.swagger.Host = value
case "@basepath":
parser.swagger.BasePath = value
+
case acceptAttr:
err := parser.ParseAcceptComment(value)
if err != nil {
@@ -437,7 +470,7 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
return err
}
case "@schemes":
- parser.swagger.Schemes = getSchemes(commentLine)
+ parser.swagger.Schemes = strings.Split(value, " ")
case "@tag.name":
parser.swagger.Tags = append(parser.swagger.Tags, spec.Tag{
TagProps: spec.TagProps{
@@ -450,57 +483,39 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.description.markdown":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
+
commentInfo, err := getMarkdownForTag(tag.TagProps.Name, parser.markdownFileDir)
if err != nil {
return err
}
+
tag.TagProps.Description = string(commentInfo)
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.url":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
tag.TagProps.ExternalDocs = &spec.ExternalDocumentation{
- URL: value,
+ URL: value,
+ Description: "",
}
+
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.description":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
if tag.TagProps.ExternalDocs == nil {
return fmt.Errorf("%s needs to come after a @tags.docs.url", attribute)
}
+
tag.TagProps.ExternalDocs.Description = value
replaceLastTag(parser.swagger.Tags, tag)
- case "@securitydefinitions.basic":
- parser.swagger.SecurityDefinitions[value] = spec.BasicAuth()
- case "@securitydefinitions.apikey":
- attrMap, _, _, err := parseSecAttr(attribute, []string{"@in", "@name"}, comments[i+1:])
- if err != nil {
- return err
- }
- parser.swagger.SecurityDefinitions[value] = spec.APIKeyAuth(attrMap["@name"], attrMap["@in"])
- case "@securitydefinitions.oauth2.application":
- attrMap, scopes, extensions, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments[i+1:])
- if err != nil {
- return err
- }
- parser.swagger.SecurityDefinitions[value] = secOAuth2Application(attrMap["@tokenurl"], scopes, extensions)
- case "@securitydefinitions.oauth2.implicit":
- attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@authorizationurl"}, comments[i+1:])
- if err != nil {
- return err
- }
- parser.swagger.SecurityDefinitions[value] = secOAuth2Implicit(attrs["@authorizationurl"], scopes, ext)
- case "@securitydefinitions.oauth2.password":
- attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments[i+1:])
- if err != nil {
- return err
- }
- parser.swagger.SecurityDefinitions[value] = secOAuth2Password(attrs["@tokenurl"], scopes, ext)
- case "@securitydefinitions.oauth2.accesscode":
- attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl", "@authorizationurl"}, comments[i+1:])
+
+ case secBasicAttr, secAPIKeyAttr, secApplicationAttr, secImplicitAttr, secPasswordAttr, secAccessCodeAttr:
+ scheme, err := parseSecAttributes(attribute, comments, &line)
if err != nil {
return err
}
- parser.swagger.SecurityDefinitions[value] = secOAuth2AccessToken(attrs["@authorizationurl"], attrs["@tokenurl"], scopes, ext)
+
+ parser.swagger.SecurityDefinitions[value] = scheme
+
case "@query.collection.format":
parser.collectionFormatInQuery = value
default:
@@ -517,17 +532,21 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
break
}
}
+
// if it is present on security def, don't add it again
if extExistsInSecurityDef {
break
}
var valueJSON interface{}
+
split := strings.SplitAfter(commentLine, attribute+" ")
if len(split) < 2 {
return fmt.Errorf("annotation %s need a value", attribute)
}
+
extensionName := "x-" + strings.SplitAfter(attribute, prefixExtension)[1]
+
err := json.Unmarshal([]byte(split[1]), &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -539,44 +558,77 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
if parser.swagger.Extensions == nil {
parser.swagger.Extensions = make(map[string]interface{})
}
+
parser.swagger.Extensions[attribute[1:]] = valueJSON
}
}
}
+
previousAttribute = attribute
}
return nil
}
-// ParseAcceptComment parses comment for given `accept` comment string.
-func (parser *Parser) ParseAcceptComment(commentLine string) error {
- return parseMimeTypeList(commentLine, &parser.swagger.Consumes, "%v accept type can't be accepted")
+func setSwaggerInfo(swagger *spec.Swagger, attribute, value string) {
+ switch attribute {
+ case versionAttr:
+ swagger.Info.Version = value
+ case titleAttr:
+ swagger.Info.Title = value
+ case tosAttr:
+ swagger.Info.TermsOfService = value
+ case descriptionAttr:
+ swagger.Info.Description = value
+ case conNameAttr:
+ swagger.Info.Contact.Name = value
+ case conEmailAttr:
+ swagger.Info.Contact.Email = value
+ case conURLAttr:
+ swagger.Info.Contact.URL = value
+ case licNameAttr:
+ swagger.Info.License = initIfEmpty(swagger.Info.License)
+ swagger.Info.License.Name = value
+ case licURLAttr:
+ swagger.Info.License = initIfEmpty(swagger.Info.License)
+ swagger.Info.License.URL = value
+ }
}
-// ParseProduceComment parses comment for given `produce` comment string.
-func (parser *Parser) ParseProduceComment(commentLine string) error {
- return parseMimeTypeList(commentLine, &parser.swagger.Produces, "%v produce type can't be accepted")
-}
+func parseSecAttributes(context string, lines []string, index *int) (*spec.SecurityScheme, error) {
+ const (
+ in = "@in"
+ name = "@name"
+ descriptionAttr = "@description"
+ tokenURL = "@tokenurl"
+ authorizationURL = "@authorizationurl"
+ )
-func isGeneralAPIComment(comments []string) bool {
- for _, commentLine := range comments {
- attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
- switch attribute {
- // The @summary, @router, @success, @failure annotation belongs to Operation
- case summaryAttr, routerAttr, successAttr, failureAttr, responseAttr:
- return false
- }
+ var search []string
+
+ attribute := strings.ToLower(strings.Split(lines[*index], " ")[0])
+ switch attribute {
+ case secBasicAttr:
+ return spec.BasicAuth(), nil
+ case secAPIKeyAttr:
+ search = []string{in, name}
+ case secApplicationAttr, secPasswordAttr:
+ search = []string{tokenURL}
+ case secImplicitAttr:
+ search = []string{authorizationURL}
+ case secAccessCodeAttr:
+ search = []string{tokenURL, authorizationURL}
}
- return true
-}
+ // For the first line we get the attributes in the context parameter, so we skip to the next one
+ *index++
+
+ attrMap, scopes := make(map[string]string), make(map[string]string)
+ extensions, description := make(map[string]interface{}), ""
+
+ for ; *index < len(lines); *index++ {
+ v := lines[*index]
-func parseSecAttr(context string, search []string, lines []string) (map[string]string, map[string]string, map[string]interface{}, error) {
- attrMap := map[string]string{}
- scopes := map[string]string{}
- extensions := map[string]interface{}{}
- for _, v := range lines {
securityAttr := strings.ToLower(strings.Split(v, " ")[0])
for _, findterm := range search {
if securityAttr == findterm {
@@ -585,84 +637,96 @@ func parseSecAttr(context string, search []string, lines []string) (map[string]s
continue
}
}
+
isExists, err := isExistsScope(securityAttr)
if err != nil {
- return nil, nil, nil, err
+ return nil, err
}
+
if isExists {
scopes[securityAttr[len(scopeAttrPrefix):]] = v[len(securityAttr):]
}
+
if strings.HasPrefix(securityAttr, "@x-") {
// Add the custom attribute without the @
extensions[securityAttr[1:]] = strings.TrimSpace(v[len(securityAttr):])
}
+
+ // Not mandatory field
+ if securityAttr == descriptionAttr {
+ description = strings.TrimSpace(v[len(securityAttr):])
+ }
+
// next securityDefinitions
if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
+ // Go back to the previous line and break
+ *index--
+
break
}
}
if len(attrMap) != len(search) {
- return nil, nil, nil, fmt.Errorf("%s is %v required", context, search)
+ return nil, fmt.Errorf("%s is %v required", context, search)
}
- return attrMap, scopes, extensions, nil
-}
+ var scheme *spec.SecurityScheme
-func secOAuth2Application(tokenURL string, scopes map[string]string,
- extensions map[string]interface{}) *spec.SecurityScheme {
- securityScheme := spec.OAuth2Application(tokenURL)
- securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
- for scope, description := range scopes {
- securityScheme.AddScope(scope, description)
+ switch attribute {
+ case secAPIKeyAttr:
+ scheme = spec.APIKeyAuth(attrMap[name], attrMap[in])
+ case secApplicationAttr:
+ scheme = spec.OAuth2Application(attrMap[tokenURL])
+ case secImplicitAttr:
+ scheme = spec.OAuth2Implicit(attrMap[authorizationURL])
+ case secPasswordAttr:
+ scheme = spec.OAuth2Password(attrMap[tokenURL])
+ case secAccessCodeAttr:
+ scheme = spec.OAuth2AccessToken(attrMap[authorizationURL], attrMap[tokenURL])
}
- return securityScheme
-}
+ scheme.Description = description
+
+ for extKey, extValue := range extensions {
+ scheme.AddExtension(extKey, extValue)
+ }
-func secOAuth2Implicit(authorizationURL string, scopes map[string]string,
- extensions map[string]interface{}) *spec.SecurityScheme {
- securityScheme := spec.OAuth2Implicit(authorizationURL)
- securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
- for scope, description := range scopes {
- securityScheme.AddScope(scope, description)
+ for scope, scopeDescription := range scopes {
+ scheme.AddScope(scope, scopeDescription)
}
- return securityScheme
+ return scheme, nil
}
-func secOAuth2Password(tokenURL string, scopes map[string]string,
- extensions map[string]interface{}) *spec.SecurityScheme {
- securityScheme := spec.OAuth2Password(tokenURL)
- securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
- for scope, description := range scopes {
- securityScheme.AddScope(scope, description)
+func initIfEmpty(license *spec.License) *spec.License {
+ if license == nil {
+ return new(spec.License)
}
- return securityScheme
+ return license
}
-func secOAuth2AccessToken(authorizationURL, tokenURL string,
- scopes map[string]string, extensions map[string]interface{}) *spec.SecurityScheme {
- securityScheme := spec.OAuth2AccessToken(authorizationURL, tokenURL)
- securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
- for scope, description := range scopes {
- securityScheme.AddScope(scope, description)
- }
+// ParseAcceptComment parses comment for given `accept` comment string.
+func (parser *Parser) ParseAcceptComment(commentLine string) error {
+ return parseMimeTypeList(commentLine, &parser.swagger.Consumes, "%v accept type can't be accepted")
+}
- return securityScheme
+// ParseProduceComment parses comment for given `produce` comment string.
+func (parser *Parser) ParseProduceComment(commentLine string) error {
+ return parseMimeTypeList(commentLine, &parser.swagger.Produces, "%v produce type can't be accepted")
}
-func handleSecuritySchemaExtensions(providedExtensions map[string]interface{}) spec.Extensions {
- var extensions spec.Extensions
- if len(providedExtensions) > 0 {
- extensions = make(map[string]interface{}, len(providedExtensions))
- for key, value := range providedExtensions {
- extensions[key] = value
+func isGeneralAPIComment(comments []string) bool {
+ for _, commentLine := range comments {
+ attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
+ switch attribute {
+ // The @summary, @router, @success, @failure annotation belongs to Operation
+ case summaryAttr, routerAttr, successAttr, failureAttr, responseAttr:
+ return false
}
}
- return extensions
+ return true
}
func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
@@ -675,6 +739,7 @@ func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
if fileInfo.IsDir() {
continue
}
+
fileName := fileInfo.Name()
if !strings.Contains(fileName, ".md") {
@@ -683,6 +748,7 @@ func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
if strings.Contains(fileName, tagName) {
fullPath := filepath.Join(dirPath, fileName)
+
commentInfo, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read markdown file %s error: %s ", fullPath, err)
@@ -708,13 +774,6 @@ func isExistsScope(scope string) (bool, error) {
return strings.Contains(scope, scopeAttrPrefix), nil
}
-// getSchemes parses swagger schemes for given commentLine.
-func getSchemes(commentLine string) []string {
- attribute := strings.ToLower(strings.Split(commentLine, " ")[0])
-
- return strings.Split(strings.TrimSpace(commentLine[len(attribute):]), " ")
-}
-
// ParseRouterAPIInfo parses router api info for given astFile.
func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) error {
for _, astDescription := range astFile.Decls {
@@ -729,29 +788,9 @@ func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) err
}
}
- for _, routeProperties := range operation.RouterProperties {
- var pathItem spec.PathItem
- var ok bool
-
- pathItem, ok = parser.swagger.Paths.Paths[routeProperties.Path]
- if !ok {
- pathItem = spec.PathItem{}
- }
-
- op := refRouteMethodOp(&pathItem, routeProperties.HTTPMethod)
-
- // check if we already have a operation for this path and method
- if *op != nil {
- err := fmt.Errorf("route %s %s is declared multiple times", routeProperties.HTTPMethod, routeProperties.Path)
- if parser.Strict {
- return err
- }
- parser.debug.Printf("warning: %s\n", err)
- }
-
- *op = &operation.Operation
-
- parser.swagger.Paths.Paths[routeProperties.Path] = pathItem
+ err := processRouterOperation(parser, operation)
+ if err != nil {
+ return err
}
}
}
@@ -776,14 +815,48 @@ func refRouteMethodOp(item *spec.PathItem, method string) (op **spec.Operation)
case http.MethodOptions:
op = &item.Options
}
+
return
}
+func processRouterOperation(parser *Parser, operation *Operation) error {
+ for _, routeProperties := range operation.RouterProperties {
+ var (
+ pathItem spec.PathItem
+ ok bool
+ )
+
+ pathItem, ok = parser.swagger.Paths.Paths[routeProperties.Path]
+ if !ok {
+ pathItem = spec.PathItem{}
+ }
+
+ op := refRouteMethodOp(&pathItem, routeProperties.HTTPMethod)
+
+ // check if we already have an operation for this path and method
+ if *op != nil {
+ err := fmt.Errorf("route %s %s is declared multiple times", routeProperties.HTTPMethod, routeProperties.Path)
+ if parser.Strict {
+ return err
+ }
+
+ parser.debug.Printf("warning: %s\n", err)
+ }
+
+ *op = &operation.Operation
+
+ parser.swagger.Paths.Paths[routeProperties.Path] = pathItem
+ }
+
+ return nil
+}
+
func convertFromSpecificToPrimitive(typeName string) (string, error) {
name := typeName
if strings.ContainsRune(name, '.') {
name = strings.Split(name, ".")[1]
}
+
switch strings.ToUpper(name) {
case "TIME", "OBJECTID", "UUID":
return STRING, nil
@@ -812,6 +885,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
if override, ok := parser.Overrides[typeSpecDef.FullPath()]; ok {
if override == "" {
parser.debug.Printf("Override detected for %s: ignoring", typeSpecDef.FullPath())
+
return nil, ErrSkippedField
}
@@ -821,6 +895,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
if separator == -1 {
// treat as a swaggertype tag
parts := strings.Split(override, ",")
+
return BuildCustomSchema(parts)
}
@@ -830,6 +905,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
schema, ok := parser.parsedSchemas[typeSpecDef]
if !ok {
var err error
+
schema, err = parser.ParseDefinition(typeSpecDef)
if err != nil {
if err == ErrRecursiveParseStruct && ref {
@@ -865,8 +941,10 @@ func (parser *Parser) renameRefSchemas() {
for _, refURL := range parser.toBeRenamedRefURLs {
parts := strings.Split(refURL.Fragment, "/")
name := parts[len(parts)-1]
+
if pkgPath, ok := parser.toBeRenamedSchemas[name]; ok {
parts[len(parts)-1] = parser.renameSchema(name, pkgPath)
+
refURL.Fragment = strings.Join(parts, "/")
}
}
@@ -895,6 +973,7 @@ func (parser *Parser) getRefTypeSchema(typeSpecDef *TypeSpecDef, schema *Schema)
} else {
parser.existSchemaNames[schema.Name] = schema
}
+
parser.swagger.Definitions[schema.Name] = spec.Schema{}
if schema.Schema != nil {
@@ -928,8 +1007,8 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
typeName := typeSpecDef.FullName()
refTypeName := TypeDocName(typeName, typeSpecDef.TypeSpec)
- schema, ok := parser.parsedSchemas[typeSpecDef]
- if ok {
+ schema, found := parser.parsedSchemas[typeSpecDef]
+ if found {
parser.debug.Printf("Skipping '%s', already parsed.", typeName)
return schema, nil
@@ -945,6 +1024,7 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
},
ErrRecursiveParseStruct
}
+
parser.structStack = append(parser.structStack, typeSpecDef)
parser.debug.Printf("Generating %s", typeName)
@@ -958,20 +1038,20 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
fillDefinitionDescription(definition, typeSpecDef.File, typeSpecDef)
}
- s := Schema{
+ sch := Schema{
Name: refTypeName,
PkgPath: typeSpecDef.PkgPath,
Schema: definition,
}
- parser.parsedSchemas[typeSpecDef] = &s
+ parser.parsedSchemas[typeSpecDef] = &sch
// update an empty schema as a result of recursion
- s2, ok := parser.outputSchemas[typeSpecDef]
- if ok {
+ s2, found := parser.outputSchemas[typeSpecDef]
+ if found {
parser.swagger.Definitions[s2.Name] = *definition
}
- return &s, nil
+ return &sch, nil
}
func fullTypeName(pkgName, typeName string) string {
@@ -1014,13 +1094,16 @@ func extractDeclarationDescription(commentGroups ...*ast.CommentGroup) string {
}
isHandlingDescription := false
+
for _, comment := range commentGroup.List {
commentText := strings.TrimSpace(strings.TrimLeft(comment.Text, "/"))
attribute := strings.Split(commentText, " ")[0]
+
if strings.ToLower(attribute) != descriptionAttr {
if !isHandlingDescription {
continue
}
+
break
}
@@ -1088,8 +1171,8 @@ func (parser *Parser) parseTypeExpr(file *ast.File, typeExpr ast.Expr, ref bool)
}
func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldList) (*spec.Schema, error) {
- required := make([]string, 0)
- properties := make(map[string]spec.Schema)
+ required, properties := make([]string, 0), make(map[string]spec.Schema)
+
for _, field := range fields.List {
fieldProps, requiredFromAnon, err := parser.parseStructField(file, field)
if err != nil {
@@ -1099,10 +1182,13 @@ func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldList) (*spec.
return nil, err
}
+
if len(fieldProps) == 0 {
continue
}
+
required = append(required, requiredFromAnon...)
+
for k, v := range fieldProps {
properties[k] = v
}
@@ -1132,10 +1218,12 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
if err != nil {
return nil, nil, err
}
+
schema, err := parser.getTypeSchema(typeName, file, false)
if err != nil {
return nil, nil, err
}
+
if len(schema.Type) > 0 && schema.Type[0] == OBJECT {
if len(schema.Properties) == 0 {
return nil, nil, nil
@@ -1155,11 +1243,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
ps := parser.fieldParserFactory(parser, field)
- ok, err := ps.ShouldSkip()
- if err != nil {
- return nil, nil, err
- }
- if ok {
+ if ps.ShouldSkip() {
return nil, nil, nil
}
@@ -1172,6 +1256,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
if err != nil {
return nil, nil, err
}
+
if schema == nil {
typeName, err := getFieldType(field.Type)
if err == nil {
@@ -1181,6 +1266,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
// unnamed type
schema, err = parser.parseTypeExpr(file, field.Type, false)
}
+
if err != nil {
return nil, nil, err
}
@@ -1192,10 +1278,12 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
}
var tagRequired []string
+
required, err := ps.IsRequired()
if err != nil {
return nil, nil, err
}
+
if required {
tagRequired = append(tagRequired, fieldName)
}
@@ -1214,7 +1302,6 @@ func getFieldType(field ast.Expr) (string, error) {
}
return fullTypeName(packageName, fieldType.Sel.Name), nil
-
case *ast.StarExpr:
fullName, err := getFieldType(fieldType.X)
if err != nil {
@@ -1232,6 +1319,7 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
if schema == nil || depth == 0 {
return nil
}
+
name := schema.Ref.String()
if name != "" {
if pos := strings.LastIndexByte(name, '/'); pos >= 0 {
@@ -1243,10 +1331,12 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
return nil
}
+
if len(schema.Type) > 0 {
switch schema.Type[0] {
case ARRAY:
depth--
+
s := []string{schema.Type[0]}
return append(s, parser.GetSchemaTypePath(schema.Items.Schema, depth)...)
@@ -1254,6 +1344,7 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
// for map
depth--
+
s := []string{schema.Type[0]}
return append(s, parser.GetSchemaTypePath(schema.AdditionalProperties.Schema, depth)...)
@@ -1270,7 +1361,7 @@ func replaceLastTag(slice []spec.Tag, element spec.Tag) {
slice = append(slice[:len(slice)-1], element)
}
-// defineTypeOfExample example value define the type (object and array unsupported)
+// defineTypeOfExample example value define the type (object and array unsupported).
func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{}, error) {
switch schemaType {
case STRING:
@@ -1304,6 +1395,7 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
if err != nil {
return nil, err
}
+
result = append(result, v)
}
@@ -1314,7 +1406,9 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
}
values := strings.Split(exampleValue, ",")
+
result := map[string]interface{}{}
+
for _, value := range values {
mapData := strings.Split(value, ":")
@@ -1323,10 +1417,14 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
if err != nil {
return nil, err
}
+
result[mapData[0]] = v
- } else {
- return nil, fmt.Errorf("example value %s should format: key:value", exampleValue)
+
+ continue
+
}
+
+ return nil, fmt.Errorf("example value %s should format: key:value", exampleValue)
}
return result, nil
@@ -1338,9 +1436,12 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
// GetAllGoFileInfo gets all Go source files information for given searchDir.
func (parser *Parser) getAllGoFileInfo(packageDir, searchDir string) error {
return filepath.Walk(searchDir, func(path string, f os.FileInfo, _ error) error {
- if err := parser.Skip(path, f); err != nil {
+ err := parser.Skip(path, f)
+ if err != nil {
return err
- } else if f.IsDir() {
+ }
+
+ if f.IsDir() {
return nil
}
@@ -1363,7 +1464,9 @@ func (parser *Parser) getAllGoFileInfoFromDeps(pkg *depth.Pkg) error {
if pkg.Raw == nil && pkg.Name == "C" {
return nil
}
+
srcDir := pkg.Raw.Dir
+
files, err := ioutil.ReadDir(srcDir) // only parsing files in the dir(don't contain sub dir files)
if err != nil {
return err
@@ -1414,24 +1517,29 @@ func (parser *Parser) checkOperationIDUniqueness() error {
for path, item := range parser.swagger.Paths.Paths {
var method, id string
+
for method = range allMethod {
op := refRouteMethodOp(&item, method)
if *op != nil {
id = (**op).ID
+
break
}
}
+
if id == "" {
continue
}
current := fmt.Sprintf("%s %s", method, path)
+
previous, ok := operationsIds[id]
if ok {
return fmt.Errorf(
"duplicated @id annotation '%s' found in '%s', previously declared in: '%s'",
id, current, previous)
}
+
operationsIds[id] = current
}
diff --git a/vendor/github.com/swaggo/swag/schema.go b/vendor/github.com/swaggo/swag/schema.go
index 0e72f65..a23d21b 100644
--- a/vendor/github.com/swaggo/swag/schema.go
+++ b/vendor/github.com/swaggo/swag/schema.go
@@ -26,6 +26,8 @@ const (
STRING = "string"
// FUNC represent a function value.
FUNC = "func"
+ // INTERFACE represent a interface value.
+ INTERFACE = "interface{}"
// ANY represent a any value.
ANY = "any"
// NIL represent a empty value.
@@ -133,6 +135,7 @@ func TypeDocName(pkgName string, spec *ast.TypeSpec) string {
}
}
}
+
if spec.Name != nil {
return fullTypeName(strings.Split(pkgName, ".")[0], spec.Name.Name)
}
@@ -168,6 +171,7 @@ func BuildCustomSchema(types []string) (*spec.Schema, error) {
if len(types) == 1 {
return nil, errors.New("need array item type after array")
}
+
schema, err := BuildCustomSchema(types[1:])
if err != nil {
return nil, err
@@ -178,6 +182,7 @@ func BuildCustomSchema(types []string) (*spec.Schema, error) {
if len(types) == 1 {
return PrimitiveSchema(types[0]), nil
}
+
schema, err := BuildCustomSchema(types[1:])
if err != nil {
return nil, err
diff --git a/vendor/github.com/swaggo/swag/spec.go b/vendor/github.com/swaggo/swag/spec.go
index 9e0ec1a..3a727c9 100644
--- a/vendor/github.com/swaggo/swag/spec.go
+++ b/vendor/github.com/swaggo/swag/spec.go
@@ -21,31 +21,33 @@ type Spec struct {
// ReadDoc parses SwaggerTemplate into swagger document.
func (i *Spec) ReadDoc() string {
- i.Description = strings.Replace(i.Description, "\n", "\\n", -1)
+ i.Description = strings.ReplaceAll(i.Description, "\n", "\\n")
- t, err := template.New("swagger_info").Funcs(template.FuncMap{
+ tpl, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
+
return string(a)
},
"escape": func(v interface{}) string {
// escape tabs
- str := strings.Replace(v.(string), "\t", "\\t", -1)
+ var str = strings.ReplaceAll(v.(string), "\t", "\\t")
// replace " with \", and if that results in \\", replace that with \\\"
- str = strings.Replace(str, "\"", "\\\"", -1)
- return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1)
+ str = strings.ReplaceAll(str, "\"", "\\\"")
+
+ return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"")
},
}).Parse(i.SwaggerTemplate)
if err != nil {
return i.SwaggerTemplate
}
- var tpl bytes.Buffer
- if err = t.Execute(&tpl, i); err != nil {
+ var doc bytes.Buffer
+ if err = tpl.Execute(&doc, i); err != nil {
return i.SwaggerTemplate
}
- return tpl.String()
+ return doc.String()
}
// InstanceName returns Spec instance name.
diff --git a/vendor/github.com/swaggo/swag/swagger.go b/vendor/github.com/swaggo/swag/swagger.go
index c00feb2..5ffbab6 100644
--- a/vendor/github.com/swaggo/swag/swagger.go
+++ b/vendor/github.com/swaggo/swag/swagger.go
@@ -23,6 +23,7 @@ type Swagger interface {
func Register(name string, swagger Swagger) {
swaggerMu.Lock()
defer swaggerMu.Unlock()
+
if swagger == nil {
panic("swagger is nil")
}
@@ -34,6 +35,7 @@ func Register(name string, swagger Swagger) {
if _, ok := swags[name]; ok {
panic("Register called twice for swag: " + name)
}
+
swags[name] = swagger
}
diff --git a/vendor/github.com/swaggo/swag/version.go b/vendor/github.com/swaggo/swag/version.go
index 0955fab..4c0837e 100644
--- a/vendor/github.com/swaggo/swag/version.go
+++ b/vendor/github.com/swaggo/swag/version.go
@@ -1,4 +1,4 @@
package swag
// Version of swag.
-const Version = "v1.8.1"
+const Version = "v1.8.3"
diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go
index 33765d3..4bb0d66 100644
--- a/vendor/golang.org/x/net/http2/server.go
+++ b/vendor/golang.org/x/net/http2/server.go
@@ -400,7 +400,7 @@ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
if s.NewWriteScheduler != nil {
sc.writeSched = s.NewWriteScheduler()
} else {
- sc.writeSched = NewRandomWriteScheduler()
+ sc.writeSched = NewPriorityWriteScheduler(nil)
}
// These start at the RFC-specified defaults. If there is a higher
@@ -2316,17 +2316,18 @@ type requestBody struct {
_ incomparable
stream *stream
conn *serverConn
- closed bool // for use by Close only
- sawEOF bool // for use by Read only
- pipe *pipe // non-nil if we have a HTTP entity message body
- needsContinue bool // need to send a 100-continue
+ closeOnce sync.Once // for use by Close only
+ sawEOF bool // for use by Read only
+ pipe *pipe // non-nil if we have a HTTP entity message body
+ needsContinue bool // need to send a 100-continue
}
func (b *requestBody) Close() error {
- if b.pipe != nil && !b.closed {
- b.pipe.BreakWithError(errClosedBody)
- }
- b.closed = true
+ b.closeOnce.Do(func() {
+ if b.pipe != nil {
+ b.pipe.BreakWithError(errClosedBody)
+ }
+ })
return nil
}
diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go
index 9180ba3..4ded4df 100644
--- a/vendor/golang.org/x/net/http2/transport.go
+++ b/vendor/golang.org/x/net/http2/transport.go
@@ -16,7 +16,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"math"
mathrand "math/rand"
@@ -2904,7 +2903,12 @@ func (t *Transport) logf(format string, args ...interface{}) {
log.Printf(format, args...)
}
-var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
+var noBody io.ReadCloser = noBodyReader{}
+
+type noBodyReader struct{}
+
+func (noBodyReader) Close() error { return nil }
+func (noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
type missingBody struct{}
diff --git a/vendor/golang.org/x/tools/go/loader/loader.go b/vendor/golang.org/x/tools/go/loader/loader.go
index 508a1fd..3ba91f7 100644
--- a/vendor/golang.org/x/tools/go/loader/loader.go
+++ b/vendor/golang.org/x/tools/go/loader/loader.go
@@ -23,6 +23,7 @@ import (
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/internal/cgo"
+ "golang.org/x/tools/internal/typeparams"
)
var ignoreVendor build.ImportMode
@@ -1053,6 +1054,7 @@ func (imp *importer) newPackageInfo(path, dir string) *PackageInfo {
errorFunc: imp.conf.TypeChecker.Error,
dir: dir,
}
+ typeparams.InitInstanceInfo(&info.Info)
// Copy the types.Config so we can vary it across PackageInfos.
tc := imp.conf.TypeChecker
diff --git a/vendor/golang.org/x/tools/internal/typeparams/common.go b/vendor/golang.org/x/tools/internal/typeparams/common.go
index 1222764..ab6b30b 100644
--- a/vendor/golang.org/x/tools/internal/typeparams/common.go
+++ b/vendor/golang.org/x/tools/internal/typeparams/common.go
@@ -77,3 +77,104 @@ func IsTypeParam(t types.Type) bool {
_, ok := t.(*TypeParam)
return ok
}
+
+// OriginMethod returns the origin method associated with the method fn.
+// For methods on a non-generic receiver base type, this is just
+// fn. However, for methods with a generic receiver, OriginMethod returns the
+// corresponding method in the method set of the origin type.
+//
+// As a special case, if fn is not a method (has no receiver), OriginMethod
+// returns fn.
+func OriginMethod(fn *types.Func) *types.Func {
+ recv := fn.Type().(*types.Signature).Recv()
+ if recv == nil {
+
+ return fn
+ }
+ base := recv.Type()
+ p, isPtr := base.(*types.Pointer)
+ if isPtr {
+ base = p.Elem()
+ }
+ named, isNamed := base.(*types.Named)
+ if !isNamed {
+ // Receiver is a *types.Interface.
+ return fn
+ }
+ if ForNamed(named).Len() == 0 {
+ // Receiver base has no type parameters, so we can avoid the lookup below.
+ return fn
+ }
+ orig := NamedTypeOrigin(named)
+ gfn, _, _ := types.LookupFieldOrMethod(orig, true, fn.Pkg(), fn.Name())
+ return gfn.(*types.Func)
+}
+
+// GenericAssignableTo is a generalization of types.AssignableTo that
+// implements the following rule for uninstantiated generic types:
+//
+// If V and T are generic named types, then V is considered assignable to T if,
+// for every possible instantation of V[A_1, ..., A_N], the instantiation
+// T[A_1, ..., A_N] is valid and V[A_1, ..., A_N] implements T[A_1, ..., A_N].
+//
+// If T has structural constraints, they must be satisfied by V.
+//
+// For example, consider the following type declarations:
+//
+// type Interface[T any] interface {
+// Accept(T)
+// }
+//
+// type Container[T any] struct {
+// Element T
+// }
+//
+// func (c Container[T]) Accept(t T) { c.Element = t }
+//
+// In this case, GenericAssignableTo reports that instantiations of Container
+// are assignable to the corresponding instantiation of Interface.
+func GenericAssignableTo(ctxt *Context, V, T types.Type) bool {
+ // If V and T are not both named, or do not have matching non-empty type
+ // parameter lists, fall back on types.AssignableTo.
+
+ VN, Vnamed := V.(*types.Named)
+ TN, Tnamed := T.(*types.Named)
+ if !Vnamed || !Tnamed {
+ return types.AssignableTo(V, T)
+ }
+
+ vtparams := ForNamed(VN)
+ ttparams := ForNamed(TN)
+ if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || NamedTypeArgs(VN).Len() != 0 || NamedTypeArgs(TN).Len() != 0 {
+ return types.AssignableTo(V, T)
+ }
+
+ // V and T have the same (non-zero) number of type params. Instantiate both
+ // with the type parameters of V. This must always succeed for V, and will
+ // succeed for T if and only if the type set of each type parameter of V is a
+ // subset of the type set of the corresponding type parameter of T, meaning
+ // that every instantiation of V corresponds to a valid instantiation of T.
+
+ // Minor optimization: ensure we share a context across the two
+ // instantiations below.
+ if ctxt == nil {
+ ctxt = NewContext()
+ }
+
+ var targs []types.Type
+ for i := 0; i < vtparams.Len(); i++ {
+ targs = append(targs, vtparams.At(i))
+ }
+
+ vinst, err := Instantiate(ctxt, V, targs, true)
+ if err != nil {
+ panic("type parameters should satisfy their own constraints")
+ }
+
+ tinst, err := Instantiate(ctxt, T, targs, true)
+ if err != nil {
+ return false
+ }
+
+ return types.AssignableTo(vinst, tinst)
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go b/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go
index 5fd3fc3..b478897 100644
--- a/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go
+++ b/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go
@@ -185,6 +185,11 @@ func GetInstances(info *types.Info) map[*ast.Ident]Instance { return nil }
// this Go version.
type Context struct{}
+// NewContext returns a placeholder Context instance.
+func NewContext() *Context {
+ return &Context{}
+}
+
// Instantiate is unsupported on this Go version, and panics.
func Instantiate(ctxt *Context, typ types.Type, targs []types.Type, validate bool) (types.Type, error) {
unsupported()
diff --git a/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go b/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go
index 7470aed..114a36b 100644
--- a/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go
+++ b/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go
@@ -140,6 +140,11 @@ func GetInstances(info *types.Info) map[*ast.Ident]Instance {
// Context is an alias for types.Context.
type Context = types.Context
+// NewContext calls types.NewContext.
+func NewContext() *Context {
+ return types.NewContext()
+}
+
// Instantiate calls types.Instantiate.
func Instantiate(ctxt *Context, typ types.Type, targs []types.Type, validate bool) (types.Type, error) {
return types.Instantiate(ctxt, typ, targs, validate)
diff --git a/vendor/modules.txt b/vendor/modules.txt
index f857383..602bacf 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -188,7 +188,7 @@ github.com/swaggo/echo-swagger
# github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2
## explicit; go 1.15
github.com/swaggo/files
-# github.com/swaggo/swag v1.8.1
+# github.com/swaggo/swag v1.8.3
## explicit; go 1.18
github.com/swaggo/swag
# github.com/theflyingcodr/govalidator v0.1.3
@@ -215,7 +215,7 @@ github.com/valyala/fasttemplate
golang.org/x/crypto/acme
golang.org/x/crypto/acme/autocert
golang.org/x/crypto/ripemd160
-# golang.org/x/net v0.0.0-20220412020605-290c469a71a5
+# golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4
## explicit; go 1.17
golang.org/x/net/http/httpguts
golang.org/x/net/http2
@@ -240,7 +240,7 @@ golang.org/x/text/width
# golang.org/x/time v0.0.0-20201208040808-7e3f01d25324
## explicit
golang.org/x/time/rate
-# golang.org/x/tools v0.1.9
+# golang.org/x/tools v0.1.10
## explicit; go 1.17
golang.org/x/tools/go/ast/astutil
golang.org/x/tools/go/buildutil