settings section

This commit is contained in:
2026-07-04 18:34:30 +05:00
parent bbe5d219ad
commit 0c717101da
2867 changed files with 1118596 additions and 1 deletions

3
vendor/github.com/swaggo/files/.gitmodules generated vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "swagger-ui"]
path = swagger-ui
url = https://github.com/swagger-api/swagger-ui.git

21
vendor/github.com/swaggo/files/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Swaggo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

13
vendor/github.com/swaggo/files/Makefile generated vendored Normal file
View File

@@ -0,0 +1,13 @@
all: build
.PHONY: init
init:
git submodule update --init --recursive
.PHONY: deps
deps:
go install github.com/UnnoTed/fileb0x@v1.1.4
.PHONY: build
build:
fileb0x fileb0x/b0x.yaml

9
vendor/github.com/swaggo/files/README.md generated vendored Normal file
View File

@@ -0,0 +1,9 @@
# swaggerFiles
[![Build Status](https://github.com/swaggo/files/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/features/actions)
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/files)](https://goreportcard.com/report/github.com/swaggo/files)
Generate swagger ui embedded files by using:
```
make
```

139
vendor/github.com/swaggo/files/ab0x.go generated vendored Normal file
View File

@@ -0,0 +1,139 @@
// Code generated by fileb0x at "2022-11-15 13:55:38.404267311 +0100 CET m=+0.035387629" from config file "b0x.yaml" DO NOT EDIT.
// modification hash(5424c7522cb6baaa7040b4a878b6c931.84893f7d7f6af7d7916db9fe20160151)
package swaggerFiles
import (
"bytes"
"context"
"io"
"net/http"
"os"
"path"
"golang.org/x/net/webdav"
)
var (
// CTX is a context for webdav vfs
CTX = context.Background()
// FS is a virtual memory file system
FS = webdav.NewMemFS()
// Handler is used to server files through a http handler
Handler *webdav.Handler
// HTTP is the http file system
HTTP http.FileSystem = new(HTTPFS)
)
// HTTPFS implements http.FileSystem
type HTTPFS struct {
// Prefix allows to limit the path of all requests. F.e. a prefix "css" would allow only calls to /css/*
Prefix string
}
func init() {
err := CTX.Err()
if err != nil {
panic(err)
}
Handler = &webdav.Handler{
FileSystem: FS,
LockSystem: webdav.NewMemLS(),
}
}
// Open a file
func (hfs *HTTPFS) Open(path string) (http.File, error) {
path = hfs.Prefix + path
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
return f, nil
}
// ReadFile is adapTed from ioutil
func ReadFile(path string) ([]byte, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
return buf.Bytes(), err
}
// WriteFile is adapTed from ioutil
func WriteFile(filename string, data []byte, perm os.FileMode) error {
f, err := FS.OpenFile(CTX, filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
// WalkDirs looks for files in the given dir and returns a list of files in it
// usage for all files in the b0x: WalkDirs("", false)
func WalkDirs(name string, includeDirsInList bool, files ...string) ([]string, error) {
f, err := FS.OpenFile(CTX, name, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
fileInfos, err := f.Readdir(0)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
for _, info := range fileInfos {
filename := path.Join(name, info.Name())
if includeDirsInList || !info.IsDir() {
files = append(files, filename)
}
if info.IsDir() {
files, err = WalkDirs(filename, includeDirsInList, files...)
if err != nil {
return nil, err
}
}
}
return files, nil
}

View File

@@ -0,0 +1,30 @@
// Code generaTed by fileb0x at "2022-11-15 13:53:16.093343763 +0100 CET m=+0.037760322" from config file "b0x.yaml" DO NOT EDIT.
// modified(2022-11-15 13:51:12.282597108 +0100 CET)
// original path: swagger-ui/dist/favicon-16x16.png
package swaggerFiles
import (
"os"
)
// FileFavicon16x16Png is "/favicon-16x16.png"
var FileFavicon16x16Png = []byte("\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x10\x00\x00\x00\x10\x08\x03\x00\x00\x00\x28\x2d\x0f\x53\x00\x00\x01\x35\x50\x4c\x54\x45\x62\xb1\x34\x61\xb1\x34\x5e\xab\x35\x5b\xa5\x35\x57\xa0\x37\x55\x9d\x37\x52\x97\x38\x51\x96\x38\x2f\x5e\x40\x2e\x5d\x40\x2d\x5a\x41\x2b\x57\x41\x33\x66\x3e\x34\x66\x3f\x39\x6f\x3d\x25\x4e\x43\x24\x4d\x43\x24\x4f\x43\x26\x4d\x42\x24\x4b\x42\x23\x4c\x42\x21\x49\x43\x24\x4b\x42\x24\x4c\x42\x24\x4d\x42\x25\x4d\x42\x24\x4e\x43\x25\x4e\x43\x1c\x41\x44\x1c\x3f\x45\x1f\x43\x44\x1d\x43\x44\x1f\x44\x44\x20\x45\x43\x22\x49\x43\x22\x49\x43\x23\x4a\x42\x27\x53\x41\x24\x4c\x43\x26\x50\x41\x22\x47\x42\x22\x48\x43\x29\x56\x41\x2b\x59\x3f\x24\x4d\x41\x25\x4d\x42\x14\x36\x46\x15\x34\x44\x15\x32\x47\x11\x33\x44\x12\x35\x46\x10\x31\x42\x0c\x31\x49\x15\x2b\x40\x00\x24\x49\x00\x33\x4d\x00\x33\x33\x00\x00\x00\x00\x00\x00\x85\xea\x2d\x84\xe9\x2c\x83\xe8\x2c\x82\xe6\x2d\x81\xe5\x2c\x7f\xe2\x2e\x80\xe1\x2e\x7d\xdd\x2e\x7c\xdd\x2e\x76\xd2\x30\x74\xd0\x30\x72\xca\x31\x71\xc9\x31\x70\xc8\x31\x6f\xc6\x32\x6d\xc5\x31\x6d\xc4\x31\x6c\xc3\x32\x6b\xc0\x32\x6a\xbf\x32\x69\xbe\x33\x68\xbb\x33\x68\xba\x33\x67\xb8\x33\x4b\x8d\x39\x4a\x8a\x3a\x4a\x89\x3a\x44\x7f\x3b\x43\x7f\x3c\x40\x79\x3d\x3e\x77\x3d\x39\x6e\x3e\x38\x6d\x3e\x38\x6e\x3f\x36\x6a\x3f\x35\x68\x3f\x33\x65\x3f\x1b\x3d\x45\x1b\x3e\x45\x1c\x3f\x45\x1c\x3d\x45\x1e\x43\x45\x1f\x44\x44\x20\x46\x44\x60\x25\x11\x2f\x00\x00\x00\x3b\x74\x52\x4e\x53\xf4\xf4\xf5\xf5\xf6\xf5\xf7\xf6\xee\xee\xef\xf0\xea\xea\xe7\xe1\xe1\xe0\xe0\xe3\xe3\xdf\xdc\xdb\xdb\xda\xd9\xd8\xd8\xdb\xcf\xbf\xbc\xba\xac\xab\xa9\xa9\xa1\x99\x96\x94\x8e\x89\x85\x84\x4c\x31\x24\x1e\x1d\x1f\x15\x0c\x07\x0a\x05\x01\x00\x07\x07\xae\xc9\x00\x00\x00\xd8\x49\x44\x41\x54\x78\xda\x3d\xcf\xd9\x2e\x43\x51\x18\x86\xe1\xcf\x6e\x8a\x8d\x52\x69\xa9\x22\x86\xb6\x31\xcf\x73\xd6\xbb\x5b\xb3\x84\x12\x1b\x41\x8c\x35\x94\x3b\x75\xe0\x86\xa4\x12\xc1\x5a\xcd\x4e\x9f\xa3\xff\xff\xce\x5e\x19\x6b\x2e\x97\x49\x76\x0f\x4c\x2d\xb9\x5b\xc6\xac\x0f\x77\x94\x4b\x50\x3a\x4e\x8c\xae\xba\x61\x63\x30\x4e\xa4\x69\x68\xcd\x0e\x85\x96\xe8\xdd\xdb\x24\x96\x37\x9a\xf7\xe1\xf2\x01\xeb\xf1\x1e\xda\x16\x54\x08\xe1\x7d\x0b\x6b\xe7\x0d\xc2\x49\xf5\x04\xf0\x1a\xe0\xbc\x40\xd0\xa7\x14\x5c\xdd\xec\x9f\x1f\x9c\x1e\x9e\x54\x2e\x20\xed\xfd\x49\xbf\x71\xff\xcb\xaf\xf9\xb5\xef\x98\xf4\xa3\x6c\x00\x4f\x45\x9c\xe7\x22\x41\xaf\xc6\x43\xa8\xee\x62\x6d\x57\xe1\x6c\x42\xcb\xad\x70\x5b\xc1\xba\xbb\x86\xf6\x45\x99\x31\x8f\x86\xe6\x9c\xf1\x94\xca\x7f\x28\xf2\x99\x49\x4b\x36\x70\xba\xf3\xc8\xc5\x95\x13\x23\xf5\x38\x6b\x65\x36\x9b\xec\xea\x9f\xa9\xe7\xff\x03\xcd\x4a\x39\x84\xc0\xe4\xbb\xd1\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82")
func init() {
f, err := FS.OpenFile(CTX, "/favicon-16x16.png", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileFavicon16x16Png)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,30 @@
// Code generaTed by fileb0x at "2022-11-15 13:53:16.221563184 +0100 CET m=+0.165979743" from config file "b0x.yaml" DO NOT EDIT.
// modified(2022-11-15 13:51:12.282597108 +0100 CET)
// original path: swagger-ui/dist/favicon-32x32.png
package swaggerFiles
import (
"os"
)
// FileFavicon32x32Png is "/favicon-32x32.png"
var FileFavicon32x32Png = []byte("\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\x00\x00\x00\x90\x50\x4c\x54\x45\x00\x00\x00\x10\x33\x44\x16\x35\x46\x16\x36\x46\x17\x36\x46\x00\x2e\x3a\x16\x35\x46\x18\x38\x45\x17\x37\x46\x1a\x3c\x45\x0f\x31\x40\x14\x33\x44\x15\x35\x46\x16\x36\x46\x16\x35\x46\x16\x35\x45\x16\x35\x46\x15\x34\x46\x16\x36\x46\x16\x35\x46\x16\x33\x47\x85\xea\x2d\x17\x36\x47\x21\x47\x43\x81\xe5\x2c\x33\x66\x3f\x70\xc9\x31\x2f\x5e\x40\x37\x6b\x3e\x5a\xa5\x36\x7e\xe0\x2e\x43\x80\x3b\x77\xd4\x2f\x5f\xae\x35\x39\x6f\x3e\x6e\xc5\x32\x3f\x78\x3c\x73\xce\x30\x26\x4f\x42\x2c\x59\x41\x1e\x42\x45\x65\xb7\x34\x7a\xd9\x2e\x83\xe8\x2c\x48\x87\x3a\x4a\x8a\x3a\x49\x88\x3a\x4e\x90\x39\x78\x6f\x8d\xe5\x00\x00\x00\x15\x74\x52\x4e\x53\x00\x15\xcd\xf4\xe1\x07\x99\xfe\xf8\xfe\x10\x20\x77\xc4\xa9\x46\x8a\x53\xd7\xbd\x2d\x8a\x6b\xf8\x74\x00\x00\x01\x7e\x49\x44\x41\x54\x78\xda\x85\x53\xd9\x76\x82\x30\x10\x1d\x25\x10\x22\xee\x96\x09\x6b\x64\x07\xc5\xb6\xff\xff\x77\x2d\x49\x20\x14\x3d\xf6\xbe\x4c\x72\xe6\xce\x3e\x03\x06\xf6\x69\xbf\x26\xae\x4b\xd6\xfb\x93\x0d\xcf\x58\x39\x16\xb2\xb0\xfa\x7c\x54\x21\x43\xd7\x59\x2d\xf5\x5b\x0b\x93\x3c\xf0\x25\x82\x3c\x44\x6b\xfb\xc7\xcb\x66\x87\x49\xe4\xcf\x10\x25\xb8\xdb\x18\xbd\x47\xd8\xcd\x5f\x20\x67\xc4\x9b\xec\x09\x37\xe6\xc6\x09\x27\x3a\x11\x7b\x4d\x4b\xff\x05\x4a\xba\xb6\x55\x7e\x98\x0e\xff\xbe\x5c\xba\x49\xf1\x28\x03\x58\xc9\xf0\xab\x39\xc6\xa3\xa6\xa5\x71\x36\xc8\xc4\x1d\x82\x1c\xa9\xfc\x54\x58\xa4\x93\x69\x8c\x57\x69\x44\x9d\x5f\x82\x25\xdf\x7e\x8c\x99\x71\x5e\x63\x2b\xe5\xd5\xb5\xe1\x80\xaa\xc2\x06\xc5\xa4\xef\x05\x36\xf2\x71\xc3\x03\x38\x4c\xf5\x8f\xa3\x94\x1a\x94\x4b\x11\x30\x07\x2e\xb1\x7a\x62\xe7\xcf\xd0\x50\x45\x8f\x2f\x40\x0a\xd5\x38\x4c\xe6\x84\x02\x53\x25\xcf\xa0\xf2\x0d\x91\xd7\x7d\xdb\x65\x41\xc3\x85\xe0\x4d\x5f\x73\x0c\x65\x96\x16\xb8\x23\x21\x0b\x38\xbf\x0b\xce\x83\xac\x6b\xfb\xa8\x1b\x09\x3a\x84\xf8\x36\x21\x94\xc1\x97\xd0\x21\x76\x3a\x49\xca\xe6\x04\x36\x26\xb9\x03\x87\xf5\xba\x4c\xe1\x1b\x60\x37\x95\x79\xc2\x9b\x26\xdc\x8d\x5e\x20\x9f\x1a\x65\xbb\x57\xdd\xc9\xda\x10\xee\xb3\x56\xc3\x7e\x1c\x56\x6c\x86\x55\x60\x35\xc8\x4c\x0e\xcb\xa3\xa1\x34\x2a\xd8\x20\xf5\xe0\x78\x29\x6b\x91\xe3\x86\xa3\xee\x9a\x41\x54\xf6\xb3\x85\x01\xfb\xfc\xcf\xca\x81\x67\xbd\x5f\x5a\x80\x83\xc5\xf2\xa5\x3e\xa7\xc4\x83\x09\x1f\xe4\xfd\xe1\x00\xac\x2e\xf8\xf6\xf4\x86\x30\x67\x1c\x8e\xf7\xf1\x7c\xbc\x26\xce\xf6\xd5\xf9\xff\x00\xc6\x8c\x46\x7b\xbe\xb8\x05\x67\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82")
func init() {
f, err := FS.OpenFile(CTX, "/favicon-32x32.png", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileFavicon32x32Png)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

30
vendor/github.com/swaggo/files/b0xfile__index.css.go generated vendored Normal file
View File

@@ -0,0 +1,30 @@
// Code generaTed by fileb0x at "2022-11-15 13:53:16.165834797 +0100 CET m=+0.110251356" from config file "b0x.yaml" DO NOT EDIT.
// modified(2022-11-15 13:51:12.282597108 +0100 CET)
// original path: swagger-ui/dist/index.css
package swaggerFiles
import (
"os"
)
// FileIndexCSS is "/index.css"
var FileIndexCSS = []byte("\x68\x74\x6d\x6c\x20\x7b\x0a\x20\x20\x20\x20\x62\x6f\x78\x2d\x73\x69\x7a\x69\x6e\x67\x3a\x20\x62\x6f\x72\x64\x65\x72\x2d\x62\x6f\x78\x3b\x0a\x20\x20\x20\x20\x6f\x76\x65\x72\x66\x6c\x6f\x77\x3a\x20\x2d\x6d\x6f\x7a\x2d\x73\x63\x72\x6f\x6c\x6c\x62\x61\x72\x73\x2d\x76\x65\x72\x74\x69\x63\x61\x6c\x3b\x0a\x20\x20\x20\x20\x6f\x76\x65\x72\x66\x6c\x6f\x77\x2d\x79\x3a\x20\x73\x63\x72\x6f\x6c\x6c\x3b\x0a\x7d\x0a\x0a\x2a\x2c\x0a\x2a\x3a\x62\x65\x66\x6f\x72\x65\x2c\x0a\x2a\x3a\x61\x66\x74\x65\x72\x20\x7b\x0a\x20\x20\x20\x20\x62\x6f\x78\x2d\x73\x69\x7a\x69\x6e\x67\x3a\x20\x69\x6e\x68\x65\x72\x69\x74\x3b\x0a\x7d\x0a\x0a\x62\x6f\x64\x79\x20\x7b\x0a\x20\x20\x20\x20\x6d\x61\x72\x67\x69\x6e\x3a\x20\x30\x3b\x0a\x20\x20\x20\x20\x62\x61\x63\x6b\x67\x72\x6f\x75\x6e\x64\x3a\x20\x23\x66\x61\x66\x61\x66\x61\x3b\x0a\x7d\x0a")
func init() {
f, err := FS.OpenFile(CTX, "/index.css", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileIndexCSS)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

30
vendor/github.com/swaggo/files/b0xfile__index.html.go generated vendored Normal file
View File

@@ -0,0 +1,30 @@
// Code generaTed by fileb0x at "2022-11-15 13:53:16.140766442 +0100 CET m=+0.085183001" from config file "b0x.yaml" DO NOT EDIT.
// modified(2022-11-15 13:51:12.282597108 +0100 CET)
// original path: swagger-ui/dist/index.html
package swaggerFiles
import (
"os"
)
// FileIndexHTML is "/index.html"
var FileIndexHTML = []byte("\x3c\x21\x2d\x2d\x20\x48\x54\x4d\x4c\x20\x66\x6f\x72\x20\x73\x74\x61\x74\x69\x63\x20\x64\x69\x73\x74\x72\x69\x62\x75\x74\x69\x6f\x6e\x20\x62\x75\x6e\x64\x6c\x65\x20\x62\x75\x69\x6c\x64\x20\x2d\x2d\x3e\x0a\x3c\x21\x44\x4f\x43\x54\x59\x50\x45\x20\x68\x74\x6d\x6c\x3e\x0a\x3c\x68\x74\x6d\x6c\x20\x6c\x61\x6e\x67\x3d\x22\x65\x6e\x22\x3e\x0a\x20\x20\x3c\x68\x65\x61\x64\x3e\x0a\x20\x20\x20\x20\x3c\x6d\x65\x74\x61\x20\x63\x68\x61\x72\x73\x65\x74\x3d\x22\x55\x54\x46\x2d\x38\x22\x3e\x0a\x20\x20\x20\x20\x3c\x74\x69\x74\x6c\x65\x3e\x53\x77\x61\x67\x67\x65\x72\x20\x55\x49\x3c\x2f\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x73\x74\x79\x6c\x65\x73\x68\x65\x65\x74\x22\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\x2f\x63\x73\x73\x22\x20\x68\x72\x65\x66\x3d\x22\x2e\x2f\x73\x77\x61\x67\x67\x65\x72\x2d\x75\x69\x2e\x63\x73\x73\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x73\x74\x79\x6c\x65\x73\x68\x65\x65\x74\x22\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\x2f\x63\x73\x73\x22\x20\x68\x72\x65\x66\x3d\x22\x69\x6e\x64\x65\x78\x2e\x63\x73\x73\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x69\x63\x6f\x6e\x22\x20\x74\x79\x70\x65\x3d\x22\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x22\x20\x68\x72\x65\x66\x3d\x22\x2e\x2f\x66\x61\x76\x69\x63\x6f\x6e\x2d\x33\x32\x78\x33\x32\x2e\x70\x6e\x67\x22\x20\x73\x69\x7a\x65\x73\x3d\x22\x33\x32\x78\x33\x32\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x69\x63\x6f\x6e\x22\x20\x74\x79\x70\x65\x3d\x22\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x22\x20\x68\x72\x65\x66\x3d\x22\x2e\x2f\x66\x61\x76\x69\x63\x6f\x6e\x2d\x31\x36\x78\x31\x36\x2e\x70\x6e\x67\x22\x20\x73\x69\x7a\x65\x73\x3d\x22\x31\x36\x78\x31\x36\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x2f\x68\x65\x61\x64\x3e\x0a\x0a\x20\x20\x3c\x62\x6f\x64\x79\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x69\x64\x3d\x22\x73\x77\x61\x67\x67\x65\x72\x2d\x75\x69\x22\x3e\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x3c\x73\x63\x72\x69\x70\x74\x20\x73\x72\x63\x3d\x22\x2e\x2f\x73\x77\x61\x67\x67\x65\x72\x2d\x75\x69\x2d\x62\x75\x6e\x64\x6c\x65\x2e\x6a\x73\x22\x20\x63\x68\x61\x72\x73\x65\x74\x3d\x22\x55\x54\x46\x2d\x38\x22\x3e\x20\x3c\x2f\x73\x63\x72\x69\x70\x74\x3e\x0a\x20\x20\x20\x20\x3c\x73\x63\x72\x69\x70\x74\x20\x73\x72\x63\x3d\x22\x2e\x2f\x73\x77\x61\x67\x67\x65\x72\x2d\x75\x69\x2d\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x2d\x70\x72\x65\x73\x65\x74\x2e\x6a\x73\x22\x20\x63\x68\x61\x72\x73\x65\x74\x3d\x22\x55\x54\x46\x2d\x38\x22\x3e\x20\x3c\x2f\x73\x63\x72\x69\x70\x74\x3e\x0a\x20\x20\x20\x20\x3c\x73\x63\x72\x69\x70\x74\x20\x73\x72\x63\x3d\x22\x2e\x2f\x73\x77\x61\x67\x67\x65\x72\x2d\x69\x6e\x69\x74\x69\x61\x6c\x69\x7a\x65\x72\x2e\x6a\x73\x22\x20\x63\x68\x61\x72\x73\x65\x74\x3d\x22\x55\x54\x46\x2d\x38\x22\x3e\x20\x3c\x2f\x73\x63\x72\x69\x70\x74\x3e\x0a\x20\x20\x3c\x2f\x62\x6f\x64\x79\x3e\x0a\x3c\x2f\x68\x74\x6d\x6c\x3e\x0a")
func init() {
f, err := FS.OpenFile(CTX, "/index.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileIndexHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,30 @@
// Code generaTed by fileb0x at "2022-11-15 13:53:16.093034824 +0100 CET m=+0.037451383" from config file "b0x.yaml" DO NOT EDIT.
// modified(2022-11-15 13:51:12.282597108 +0100 CET)
// original path: swagger-ui/dist/swagger-initializer.js
package swaggerFiles
import (
"os"
)
// FileSwaggerInitializerJs is "/swagger-initializer.js"
var FileSwaggerInitializerJs = []byte("\x77\x69\x6e\x64\x6f\x77\x2e\x6f\x6e\x6c\x6f\x61\x64\x20\x3d\x20\x66\x75\x6e\x63\x74\x69\x6f\x6e\x28\x29\x20\x7b\x0a\x20\x20\x2f\x2f\x3c\x65\x64\x69\x74\x6f\x72\x2d\x66\x6f\x6c\x64\x20\x64\x65\x73\x63\x3d\x22\x43\x68\x61\x6e\x67\x65\x61\x62\x6c\x65\x20\x43\x6f\x6e\x66\x69\x67\x75\x72\x61\x74\x69\x6f\x6e\x20\x42\x6c\x6f\x63\x6b\x22\x3e\x0a\x0a\x20\x20\x2f\x2f\x20\x74\x68\x65\x20\x66\x6f\x6c\x6c\x6f\x77\x69\x6e\x67\x20\x6c\x69\x6e\x65\x73\x20\x77\x69\x6c\x6c\x20\x62\x65\x20\x72\x65\x70\x6c\x61\x63\x65\x64\x20\x62\x79\x20\x64\x6f\x63\x6b\x65\x72\x2f\x63\x6f\x6e\x66\x69\x67\x75\x72\x61\x74\x6f\x72\x2c\x20\x77\x68\x65\x6e\x20\x69\x74\x20\x72\x75\x6e\x73\x20\x69\x6e\x20\x61\x20\x64\x6f\x63\x6b\x65\x72\x2d\x63\x6f\x6e\x74\x61\x69\x6e\x65\x72\x0a\x20\x20\x77\x69\x6e\x64\x6f\x77\x2e\x75\x69\x20\x3d\x20\x53\x77\x61\x67\x67\x65\x72\x55\x49\x42\x75\x6e\x64\x6c\x65\x28\x7b\x0a\x20\x20\x20\x20\x75\x72\x6c\x3a\x20\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x70\x65\x74\x73\x74\x6f\x72\x65\x2e\x73\x77\x61\x67\x67\x65\x72\x2e\x69\x6f\x2f\x76\x32\x2f\x73\x77\x61\x67\x67\x65\x72\x2e\x6a\x73\x6f\x6e\x22\x2c\x0a\x20\x20\x20\x20\x64\x6f\x6d\x5f\x69\x64\x3a\x20\x27\x23\x73\x77\x61\x67\x67\x65\x72\x2d\x75\x69\x27\x2c\x0a\x20\x20\x20\x20\x64\x65\x65\x70\x4c\x69\x6e\x6b\x69\x6e\x67\x3a\x20\x74\x72\x75\x65\x2c\x0a\x20\x20\x20\x20\x70\x72\x65\x73\x65\x74\x73\x3a\x20\x5b\x0a\x20\x20\x20\x20\x20\x20\x53\x77\x61\x67\x67\x65\x72\x55\x49\x42\x75\x6e\x64\x6c\x65\x2e\x70\x72\x65\x73\x65\x74\x73\x2e\x61\x70\x69\x73\x2c\x0a\x20\x20\x20\x20\x20\x20\x53\x77\x61\x67\x67\x65\x72\x55\x49\x53\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x50\x72\x65\x73\x65\x74\x0a\x20\x20\x20\x20\x5d\x2c\x0a\x20\x20\x20\x20\x70\x6c\x75\x67\x69\x6e\x73\x3a\x20\x5b\x0a\x20\x20\x20\x20\x20\x20\x53\x77\x61\x67\x67\x65\x72\x55\x49\x42\x75\x6e\x64\x6c\x65\x2e\x70\x6c\x75\x67\x69\x6e\x73\x2e\x44\x6f\x77\x6e\x6c\x6f\x61\x64\x55\x72\x6c\x0a\x20\x20\x20\x20\x5d\x2c\x0a\x20\x20\x20\x20\x6c\x61\x79\x6f\x75\x74\x3a\x20\x22\x53\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x4c\x61\x79\x6f\x75\x74\x22\x0a\x20\x20\x7d\x29\x3b\x0a\x0a\x20\x20\x2f\x2f\x3c\x2f\x65\x64\x69\x74\x6f\x72\x2d\x66\x6f\x6c\x64\x3e\x0a\x7d\x3b\x0a")
func init() {
f, err := FS.OpenFile(CTX, "/swagger-initializer.js", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileSwaggerInitializerJs)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

12
vendor/github.com/swaggo/files/filebox.go generated vendored Normal file
View File

@@ -0,0 +1,12 @@
package swaggerFiles
import (
"golang.org/x/net/webdav"
)
func NewHandler() *webdav.Handler {
return &webdav.Handler{
FileSystem: FS,
LockSystem: webdav.NewMemLS(),
}
}

16
vendor/github.com/swaggo/gin-swagger/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,16 @@
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
dist
.idea
vendor
.envrc

10
vendor/github.com/swaggo/gin-swagger/.goreleaser.yml generated vendored Normal file
View File

@@ -0,0 +1,10 @@
builds:
- skip: true
snapshot:
name_template: "{{ .Tag }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'

21
vendor/github.com/swaggo/gin-swagger/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Swaggo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,8 @@
**Describe the PR**
e.g. add cool parser.
**Relation issue**
e.g. https://github.com/swaggo/gin-swagger/pull/123/files
**Additional context**
Add any other context about the problem here.

207
vendor/github.com/swaggo/gin-swagger/README.md generated vendored Normal file
View File

@@ -0,0 +1,207 @@
# gin-swagger
gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
[![Build Status](https://github.com/swaggo/gin-swagger/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/features/actions)
[![Codecov branch](https://img.shields.io/codecov/c/github/swaggo/gin-swagger/master.svg)](https://codecov.io/gh/swaggo/gin-swagger)
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/gin-swagger)](https://goreportcard.com/report/github.com/swaggo/gin-swagger)
[![GoDoc](https://godoc.org/github.com/swaggo/gin-swagger?status.svg)](https://godoc.org/github.com/swaggo/gin-swagger)
[![Release](https://img.shields.io/github/release/swaggo/gin-swagger.svg?style=flat-square)](https://github.com/swaggo/gin-swagger/releases)
## Usage
### Start using it
1. Add comments to your API source code, [See Declarative Comments Format](https://github.com/swaggo/swag/blob/master/README.md#declarative-comments-format).
2. Download [Swag](https://github.com/swaggo/swag) for Go by using:
```sh
go get -u github.com/swaggo/swag/cmd/swag
```
Starting in Go 1.17, installing executables with `go get` is deprecated. `go install` may be used instead:
```sh
go install github.com/swaggo/swag/cmd/swag@latest
```
3. Run the [Swag](https://github.com/swaggo/swag) at your Go project root path(for instance `~/root/go-project-name`),
[Swag](https://github.com/swaggo/swag) will parse comments and generate required files(`docs` folder and `docs/doc.go`)
at `~/root/go-project-name/docs`.
```sh
swag init
```
4. Download [gin-swagger](https://github.com/swaggo/gin-swagger) by using:
```sh
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
```
Import following in your code:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
```
### Canonical example:
Now assume you have implemented a simple api as following:
```go
// A get function which returns a hello world string by json
func Helloworld(g *gin.Context) {
g.JSON(http.StatusOK,"helloworld")
}
```
So how to use gin-swagger on api above? Just follow the following guide.
1. Add Comments for apis and main function with gin-swagger rules like following:
```go
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(g *gin.Context) {
g.JSON(http.StatusOK,"helloworld")
}
```
2. Use `swag init` command to generate a docs, docs generated will be stored at `docs/`.
3. import the docs like this:
I assume your project named `github.com/go-project-name/docs`.
```go
import (
docs "github.com/go-project-name/docs"
)
```
4. build your application and after that, go to http://localhost:8080/swagger/index.html ,you to see your Swagger UI.
5. The full code and folder relatives here:
```go
package main
import (
"github.com/gin-gonic/gin"
docs "github.com/go-project-name/docs"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"net/http"
)
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(g *gin.Context) {
g.JSON(http.StatusOK,"helloworld")
}
func main() {
r := gin.Default()
docs.SwaggerInfo.BasePath = "/api/v1"
v1 := r.Group("/api/v1")
{
eg := v1.Group("/example")
{
eg.GET("/helloworld",Helloworld)
}
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
r.Run(":8080")
}
```
Demo project tree, `swag init` is run at relative `.`
```
.
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
└── main.go
```
## Project with Nested Directory
```
.
├── cmd
│   └── ginsimple
│   └── main.go
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
└── internal
├── handlers
│   ├── helloWorld.go
│   └── userHandler.go
└── models
├── profile.go
└── user.go
```
Inorder generate swagger docs for projects with nested directories run the following command
```bash
swag init -g ./cmd/ginsimple/main.go -o cmd/docs
```
`-o` will set the auto generated file to the specified path
## Multiple APIs
This feature was introduced in swag v1.7.9
## Configuration
You can configure Swagger using different configuration options
```go
func main() {
r := gin.New()
ginSwagger.WrapHandler(swaggerfiles.Handler,
ginSwagger.URL("http://localhost:8080/swagger/doc.json"),
ginSwagger.DefaultModelsExpandDepth(-1))
r.Run()
}
```
| Option | Type | Default | Description |
| ------------------------ | ------ | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| URL | string | "doc.json" | URL pointing to API definition |
| DocExpansion | string | "list" | Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing). |
| DeepLinking | bool | true | If set to true, enables deep linking for tags and operations. See the Deep Linking documentation for more information. |
| DefaultModelsExpandDepth | int | 1 | Default expansion depth for models (set to -1 completely hide the models). |
| InstanceName | string | "swagger" | The instance name of the swagger document. If multiple different swagger instances should be deployed on one gin router, ensure that each instance has a unique name (use the _--instanceName_ parameter to generate swagger documents with _swag init_). |
| PersistAuthorization | bool | false | If set to true, it persists authorization data and it would not be lost on browser close/refresh. |
| Oauth2DefaultClientID | string | "" | If set, it's used to prepopulate the _client_id_ field of the OAuth2 Authorization dialog. |
| Oauth2UsePkce | bool | false | If set to true, it enables Proof Key for Code Exchange to enhance security for OAuth public clients. |

354
vendor/github.com/swaggo/gin-swagger/swagger.go generated vendored Normal file
View File

@@ -0,0 +1,354 @@
package ginSwagger
import (
htmlTemplate "html/template"
"net/http"
"os"
"path/filepath"
"regexp"
"sync"
textTemplate "text/template"
"golang.org/x/net/webdav"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag"
)
type swaggerConfig struct {
URL string
DocExpansion string
Title string
Oauth2RedirectURL htmlTemplate.JS
DefaultModelsExpandDepth int
DeepLinking bool
PersistAuthorization bool
Oauth2DefaultClientID string
Oauth2UsePkce bool
}
// Config stores ginSwagger configuration variables.
type Config struct {
// The url pointing to API definition (normally swagger.json or swagger.yaml). Default is `doc.json`.
URL string
DocExpansion string
InstanceName string
Title string
DefaultModelsExpandDepth int
DeepLinking bool
PersistAuthorization bool
Oauth2DefaultClientID string
Oauth2UsePkce bool
}
func (config Config) toSwaggerConfig() swaggerConfig {
return swaggerConfig{
URL: config.URL,
DeepLinking: config.DeepLinking,
DocExpansion: config.DocExpansion,
DefaultModelsExpandDepth: config.DefaultModelsExpandDepth,
Oauth2RedirectURL: "`${window.location.protocol}//${window.location.host}$" +
"{window.location.pathname.split('/').slice(0, window.location.pathname.split('/').length - 1).join('/')}" +
"/oauth2-redirect.html`",
Title: config.Title,
PersistAuthorization: config.PersistAuthorization,
Oauth2DefaultClientID: config.Oauth2DefaultClientID,
Oauth2UsePkce: config.Oauth2UsePkce,
}
}
// URL presents the url pointing to API definition (normally swagger.json or swagger.yaml).
func URL(url string) func(*Config) {
return func(c *Config) {
c.URL = url
}
}
// DocExpansion list, full, none.
func DocExpansion(docExpansion string) func(*Config) {
return func(c *Config) {
c.DocExpansion = docExpansion
}
}
// DeepLinking set the swagger deep linking configuration.
func DeepLinking(deepLinking bool) func(*Config) {
return func(c *Config) {
c.DeepLinking = deepLinking
}
}
// DefaultModelsExpandDepth set the default expansion depth for models
// (set to -1 completely hide the models).
func DefaultModelsExpandDepth(depth int) func(*Config) {
return func(c *Config) {
c.DefaultModelsExpandDepth = depth
}
}
// InstanceName set the instance name that was used to generate the swagger documents
// Defaults to swag.Name ("swagger").
func InstanceName(name string) func(*Config) {
return func(c *Config) {
c.InstanceName = name
}
}
// PersistAuthorization Persist authorization information over browser close/refresh.
// Defaults to false.
func PersistAuthorization(persistAuthorization bool) func(*Config) {
return func(c *Config) {
c.PersistAuthorization = persistAuthorization
}
}
// Oauth2DefaultClientID set the default client ID used for OAuth2
func Oauth2DefaultClientID(oauth2DefaultClientID string) func(*Config) {
return func(c *Config) {
c.Oauth2DefaultClientID = oauth2DefaultClientID
}
}
// Oauth2UsePkce enables Proof Key for Code Exchange.
// Corresponds to the usePkceWithAuthorizationCodeGrant property of the Swagger UI
// and applies only to accessCode (Authorization Code) flows.
func Oauth2UsePkce(usePkce bool) func(*Config) {
return func(c *Config) {
c.Oauth2UsePkce = usePkce
}
}
// WrapHandler wraps `http.Handler` into `gin.HandlerFunc`.
func WrapHandler(handler *webdav.Handler, options ...func(*Config)) gin.HandlerFunc {
var config = Config{
URL: "doc.json",
DocExpansion: "list",
InstanceName: swag.Name,
Title: "Swagger UI",
DefaultModelsExpandDepth: 1,
DeepLinking: true,
PersistAuthorization: false,
Oauth2DefaultClientID: "",
Oauth2UsePkce: false,
}
for _, c := range options {
c(&config)
}
return CustomWrapHandler(&config, handler)
}
// CustomWrapHandler wraps `http.Handler` into `gin.HandlerFunc`.
func CustomWrapHandler(config *Config, handler *webdav.Handler) gin.HandlerFunc {
var once sync.Once
if config.InstanceName == "" {
config.InstanceName = swag.Name
}
if config.Title == "" {
config.Title = "Swagger UI"
}
// create a template with name
index, _ := htmlTemplate.New("swagger_index.html").Parse(swaggerIndexTpl)
js, _ := textTemplate.New("swagger_index.js").Parse(swaggerJSTpl)
css, _ := textTemplate.New("swagger_index.css").Parse(swaggerStyleTpl)
var matcher = regexp.MustCompile(`(.*)(index\.html|index\.css|swagger-initializer\.js|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[?|.]*`)
return func(ctx *gin.Context) {
if ctx.Request.Method != http.MethodGet {
ctx.AbortWithStatus(http.StatusMethodNotAllowed)
return
}
matches := matcher.FindStringSubmatch(ctx.Request.RequestURI)
if len(matches) != 3 {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
path := matches[2]
once.Do(func() {
handler.Prefix = matches[1]
})
switch filepath.Ext(path) {
case ".html":
ctx.Header("Content-Type", "text/html; charset=utf-8")
case ".css":
ctx.Header("Content-Type", "text/css; charset=utf-8")
case ".js":
ctx.Header("Content-Type", "application/javascript")
case ".png":
ctx.Header("Content-Type", "image/png")
case ".json":
ctx.Header("Content-Type", "application/json; charset=utf-8")
}
switch path {
case "index.html":
_ = index.Execute(ctx.Writer, config.toSwaggerConfig())
case "index.css":
_ = css.Execute(ctx.Writer, config.toSwaggerConfig())
case "swagger-initializer.js":
_ = js.Execute(ctx.Writer, config.toSwaggerConfig())
case "doc.json":
doc, err := swag.ReadDoc(config.InstanceName)
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
ctx.String(http.StatusOK, doc)
default:
handler.ServeHTTP(ctx.Writer, ctx.Request)
}
}
}
// DisablingWrapHandler turn handler off
// if specified environment variable passed.
func DisablingWrapHandler(handler *webdav.Handler, envName string) gin.HandlerFunc {
if os.Getenv(envName) != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(http.StatusNotFound, "")
}
}
return WrapHandler(handler)
}
// DisablingCustomWrapHandler turn handler off
// if specified environment variable passed.
func DisablingCustomWrapHandler(config *Config, handler *webdav.Handler, envName string) gin.HandlerFunc {
if os.Getenv(envName) != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(http.StatusNotFound, "")
}
}
return CustomWrapHandler(config, handler)
}
const swaggerStyleTpl = `
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body {
margin:0;
background: #fafafa;
}
`
const swaggerJSTpl = `
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "{{.URL}}",
dom_id: '#swagger-ui',
validatorUrl: null,
oauth2RedirectUrl: {{.Oauth2RedirectURL}},
persistAuthorization: {{.PersistAuthorization}},
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
docExpansion: "{{.DocExpansion}}",
deepLinking: {{.DeepLinking}},
defaultModelsExpandDepth: {{.DefaultModelsExpandDepth}}
})
const defaultClientId = "{{.Oauth2DefaultClientID}}";
if (defaultClientId) {
ui.initOAuth({
clientId: defaultClientId,
usePkceWithAuthorizationCodeGrant: {{.Oauth2UsePkce}}
})
}
window.ui = ui
}
`
const swaggerIndexTpl = `<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<link rel="stylesheet" type="text/css" href="index.css" />
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
<defs>
<symbol viewBox="0 0 20 20" id="unlocked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="locked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="close">
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow">
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow-down">
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="jump-to">
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="expand">
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
</symbol>
</defs>
</svg>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script src="./swagger-initializer.js"> </script>
</body>
</html>
`

24
vendor/github.com/swaggo/swag/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,24 @@
dist
testdata/simple*/docs
testdata/quotes/docs
testdata/quotes/quotes.so
testdata/delims/docs
testdata/delims/delims.so
example/basic/docs/*
example/celler/docs/*
cover.out
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.idea
.vscode
# Etc
.DS_Store
/swag
/swag.exe

30
vendor/github.com/swaggo/swag/.goreleaser.yml generated vendored Normal file
View File

@@ -0,0 +1,30 @@
build:
main: cmd/swag/main.go
goos:
- linux
- darwin
goarch:
- amd64
- arm64
- 386
env:
- CGO_ENABLED=0
archives:
- id: foo
name_template: >-
{{ .ProjectName }}_
{{- .Version }}_
{{- if eq .Os "linux"}}Linux{{ else if eq .Os "darwin"}}Darwin{{ else }}{{ .Os }}{{ end }}_
{{- if eq .Arch "386" }}i386{{ else if eq .Arch "amd64" }}x86_64{{ else }}{{ .Arch }}{{ end }}
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Tag }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'

46
vendor/github.com/swaggo/swag/CODE_OF_CONDUCT.md generated vendored Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [gitter.im/swaggo/swag](https://gitter.im/swaggo/swag).The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

16
vendor/github.com/swaggo/swag/CONTRIBUTING.md generated vendored Normal file
View File

@@ -0,0 +1,16 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Pull Request Process
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
Please make an issue first if the change is likely to increase.

36
vendor/github.com/swaggo/swag/Dockerfile generated vendored Normal file
View File

@@ -0,0 +1,36 @@
# Dockerfile References: https://docs.docker.com/engine/reference/builder/
# Start from the latest golang base image
FROM --platform=$BUILDPLATFORM golang:1.21-alpine as builder
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum ./
# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download
# Copy the source from the current directory to the Working Directory inside the container
COPY . .
# Configure go compiler target platform
ARG TARGETOS
ARG TARGETARCH
ENV GOARCH=$TARGETARCH \
GOOS=$TARGETOS
# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -v -a -installsuffix cgo -o swag cmd/swag/main.go
######## Start a new stage from scratch #######
FROM --platform=$TARGETPLATFORM scratch
WORKDIR /code/
# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/swag /bin/swag
ENTRYPOINT ["/bin/swag"]

78
vendor/github.com/swaggo/swag/Makefile generated vendored Normal file
View File

@@ -0,0 +1,78 @@
GOCMD:=$(shell which go)
GOLINT:=$(shell which golint)
GOIMPORT:=$(shell which goimports)
GOFMT:=$(shell which gofmt)
GOBUILD:=$(GOCMD) build
GOINSTALL:=$(GOCMD) install
GOCLEAN:=$(GOCMD) clean
GOTEST:=$(GOCMD) test
GOMODTIDY:=$(GOCMD) mod tidy
GOGET:=$(GOCMD) get
GOLIST:=$(GOCMD) list
GOVET:=$(GOCMD) vet
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 github.com/swaggo/swag/format)
GOFILES:=$(shell find . -name "*.go" -type f)
all: test build
.PHONY: build
build: deps
$(GOBUILD) -o $(BINARY_NAME) ./cmd/swag
.PHONY: install
install: deps
$(GOINSTALL) ./cmd/swag
.PHONY: test
test:
echo "mode: count" > coverage.out
for PKG in $(PACKAGES); do \
$(GOCMD) test -v -covermode=count -coverprofile=profile.out $$PKG > tmp.out; \
cat tmp.out; \
if grep -q "^--- FAIL" tmp.out; then \
rm tmp.out; \
exit 1; \
elif grep -q "build failed" tmp.out; then \
rm tmp.out; \
exit; \
fi; \
if [ -f profile.out ]; then \
cat profile.out | grep -v "mode:" >> coverage.out; \
rm profile.out; \
fi; \
done
.PHONY: clean
clean:
$(GOCLEAN)
rm -f $(BINARY_NAME)
.PHONY: deps
deps:
$(GOMODTIDY)
.PHONY: vet
vet: deps
$(GOVET) $(PACKAGES)
.PHONY: fmt
fmt:
$(GOFMT) -s -w $(GOFILES)
.PHONY: fmt-check
fmt-check:
@diff=$$($(GOFMT) -s -d $(GOFILES)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${diff}"; \
exit 1; \
fi;
.PHONY: view-covered
view-covered:
$(GOTEST) -coverprofile=cover.out $(TARGET)
$(GOCMD) tool cover -html=cover.out

View File

@@ -0,0 +1,8 @@
**Describe the PR**
e.g. add cool parser.
**Relation issue**
e.g. https://github.com/swaggo/swag/pull/118/files
**Additional context**
Add any other context about the problem here.

1037
vendor/github.com/swaggo/swag/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

969
vendor/github.com/swaggo/swag/README_pt.md generated vendored Normal file
View File

@@ -0,0 +1,969 @@
# swag
🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md) ∙ [Português](README_pt.md)*
<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
[![Build Status](https://github.com/swaggo/swag/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/features/actions)
[![Coverage Status](https://img.shields.io/codecov/c/github/swaggo/swag/master.svg)](https://codecov.io/gh/swaggo/swag)
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/swag/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)
Swag converte anotações Go para Documentação Swagger 2.0. Criámos uma variedade de plugins para populares [Go web frameworks](#supported-web-frameworks). Isto permite uma integração rápida com um projecto Go existente (utilizando a Swagger UI).
## Conteúdo
- [Começando](#começando)
- [Estruturas Web Suportadas](#estruturas-web-suportadas)
- [Como utilizá-lo com Gin](#como-como-ser-como-gin)
- [O formatador de swag](#a-formatação-de-swag)
- [Estado de Implementação](#implementação-estado)
- [Formato dos comentários declarativos](#formato-dos-comentarios-declarativos)
- [Informações Gerais API](#informações-gerais-api)
- [Operação API](#api-operacao)
- [Segurança](#seguranca)
- [Exemplos](#exemplos)
- [Descrições em múltiplas linhas](#descricoes-sobre-múltiplas-linhas)
- [Estrutura definida pelo utilizador com um tipo de matriz](#-estrutura-definida-pelo-utilizador-com-um-um-tipo)
- [Declaração de estruturação de funções](#function-scoped-struct-declaration)
- [Composição do modelo em resposta](#model-composição-em-resposta)
- [Adicionar um cabeçalho em resposta](#add-a-headers-in-response)
- [Utilizar parâmetros de caminhos múltiplos](#use-multiple-path-params)
- [Exemplo de valor de estrutura](#exemplo-do-valor-de-estrutura)
- [Schema Exemplo do corpo](#schemaexample-of-body)
- [Descrição da estrutura](#descrição-da-estrutura)
- [Usar etiqueta do tipo swaggertype para suportar o tipo personalizado](#use-swaggertype-tag-to-supported-custom-type)
- [Utilizar anulações globais para suportar um tipo personalizado](#use-global-overrides-to-support-a-custom-type)
- [Use swaggerignore tag para excluir um campo](#use-swaggerignore-tag-to-excluir-um-campo)
- [Adicionar informações de extensão ao campo de estruturação](#add-extension-info-to-struct-field)
- [Renomear modelo a expor](#renome-modelo-a-exibir)
- [Como utilizar as anotações de segurança](#como-utilizar-as-anotações-de-segurança)
- [Adicionar uma descrição para enumerar artigos](#add-a-description-for-enum-items)
- [Gerar apenas tipos de ficheiros de documentos específicos](#generate-only-specific-docs-file-file-types)
- [Como usar tipos genéricos](#como-usar-tipos-genéricos)
- [Sobre o projecto](#sobre-o-projecto)
## Começando
1. Adicione comentários ao código-fonte da API, consulte [Formato dos comentários declarativos](#declarative-comments-format).
2. Descarregue o swag utilizando:
```sh
go install github.com/swaggo/swag/cmd/swag@latest
```
Para construir a partir da fonte é necessário [Go](https://golang.org/dl/) (1.19 ou mais recente).
Ou descarregar um binário pré-compilado a partir da [página de lançamento](https://github.com/swaggo/swag/releases).
3. Executar `swag init` na pasta raiz do projecto que contém o ficheiro `main.go`. Isto irá analisar os seus comentários e gerar os ficheiros necessários (pasta `docs` e `docs/docs.go`).
```sh
swag init
```
Certifique-se de importar os `docs/docs.go` gerados para que a sua configuração específica fique "init" ed. Se as suas anotações API gerais não viverem em `main.go`, pode avisar a swag com a bandeira `-g`.
```sh
swag init -g http/api.go
```
4. (opcional) Utilizar o formato `swag fmt` no comentário SWAG. (Por favor, actualizar para a versão mais recente)
```sh
swag fmt
```
## swag cli
```sh
swag init -h
NOME:
swag init - Criar docs.go
UTILIZAÇÃO:
swag init [opções de comando] [argumentos...]
OPÇÕES:
--quiet, -q Fazer o logger ficar quiet (por padrão: falso)
--generalInfo valor, -g valor Go caminho do ficheiro em que 'swagger general API Info' está escrito (por padrão: "main.go")
--dir valor, -d valor Os directórios que deseja analisar, separados por vírgulas e de informação geral devem estar no primeiro (por padrão: "./")
--exclude valor Excluir directórios e ficheiros ao pesquisar, separados por vírgulas
-propertyStrategy da estratégia, -p valor da propriedadeEstratégia de nomeação de propriedades como snakecase,camelcase,pascalcase (por padrão: "camelcase")
--output de saída, -o valor directório de saída para todos os ficheiros gerados(swagger.json, swagger.yaml e docs.go) (por padrão: "./docs")
--outputTypes valor de saídaTypes, -- valor de saída Tipos de ficheiros gerados (docs.go, swagger.json, swagger.yaml) como go,json,yaml (por padrão: "go,json,yaml")
--parseVendor ParseVendor Parse go files na pasta 'vendor', desactivado por padrão (padrão: falso)
--parseInternal Parse go ficheiros em pacotes internos, desactivados por padrão (padrão: falso)
--generatedTime Gerar timestamp no topo dos docs.go, desactivado por padrão (padrão: falso)
--parteDepth value Dependência profundidade parse (por padrão: 100)
--templateDelims value, --td value fornecem delimitadores personalizados para a geração de modelos Go. O formato é leftDelim,rightDelim. Por exemplo: "[[,]]"
...
--help, -h mostrar ajuda (por padrão: falso)
```
```bash
swag fmt -h
NOME:
swag fmt - formato swag comentários
UTILIZAÇÃO:
swag fmt [opções de comando] [argumentos...]
OPÇÕES:
--dir valor, -d valor Os directórios que pretende analisar, separados por vírgulas e de informação geral devem estar no primeiro (por padrão: "./")
--excluir valor Excluir directórios e ficheiros ao pesquisar, separados por vírgulas
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (por padrão: "main.go")
--ajuda, -h mostrar ajuda (por padrão: falso)
```
## Estruturas Web Suportadas
- [gin](http://github.com/swaggo/gin-swagger)
- [echo](http://github.com/swaggo/echo-swagger)
- [buffalo](https://github.com/swaggo/buffalo-swagger)
- [net/http](https://github.com/swaggo/http-swagger)
- [gorilla/mux](https://github.com/swaggo/http-swagger)
- [go-chi/chi](https://github.com/swaggo/http-swagger)
- [flamingo](https://github.com/i-love-flamingo/swagger)
- [fiber](https://github.com/gofiber/swagger)
- [atreugo](https://github.com/Nerzal/atreugo-swagger)
- [hertz](https://github.com/hertz-contrib/swagger)
## Como utilizá-lo com Gin
Encontrar o código fonte de exemplo [aqui](https://github.com/swaggo/swag/tree/master/example/celler).
1. Depois de utilizar `swag init` para gerar os documentos Swagger 2.0, importar os seguintes pacotes:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
```
2. Adicionar [Informações Gerais API](#general-api-info) anotações em código `main.go`:
```go
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
```
Além disso, algumas informações API gerais podem ser definidas de forma dinâmica. O pacote de código gerado `docs` exporta a variável `SwaggerInfo` que podemos utilizar para definir programticamente o título, descrição, versão, hospedeiro e caminho base. Exemplo utilizando Gin:
```go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
```
3. Adicionar [Operação API](#api-operacao) anotações em código `controller`
```go
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
```
```console
swag init
```
4. Execute a sua aplicação, e navegue para http://localhost:8080/swagger/index.html. Verá os documentos Swagger 2.0 Api, como mostrado abaixo:
![swagger_index.html](https://raw.githubusercontent.com/swaggo/swag/master/assets/swagger-image.png)
## O formatador de swag
Os Swag Comments podem ser formatados automaticamente, assim como 'go fmt'.
Encontre o resultado da formatação [aqui](https://github.com/swaggo/swag/tree/master/example/celler).
Usage:
```shell
swag fmt
```
Exclude folder:
```shell
swag fmt -d ./ --exclude ./internal
```
Ao utilizar `swag fmt`, é necessário assegurar-se de que tem um comentário doc para a função a fim de assegurar uma formatação correcta.
Isto deve-se ao `swag fmt` que traça comentários swag com separadores, o que só é permitido *após* um comentário doc padrão.
Por exemplo, utilizar
```go
// ListAccounts lists all existing accounts
//
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
```
## Estado de Implementação
[Documento Swagger 2.0](https://swagger.io/docs/specification/2-0/basic-structure/)
- [x] Estrutura básica
- [x] Hospedeiro API e Caminho Base
- [x] Caminhos e operações
- [x] Descrição dos parâmetros
- [x] Descrever o corpo do pedido
- [x] Descrição das respostas
- [x] Tipos MIME
- [x] Autenticação
- [x] Autenticação básica
- [x] Chaves API
- [x] Acrescentar exemplos
- [x] Carregamento de ficheiros
- [x] Enums
- [x] Operações de Agrupamento com Etiquetas
- Extensões Swagger
## Formato dos comentários declarativos
## Informações Gerais API
**Exemplo**
[celler/main.go](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
| anotação | descrição | exemplo |
|-------------|--------------------------------------------|---------------------------------|
| title | **Obrigatório.** O título da aplicação.| // @title Swagger Example API |
| version | **Obrigatório.** Fornece a versão da aplicação API.| // @version 1.0 |
| description | Uma breve descrição da candidatura. |// @descrição Este é um servidor servidor de celas de amostra. |
| tag.name | Nome de uma tag.| // @tag.name Este é o nome da tag |
| tag.description | Descrição da tag | // @tag.description Cool Description |
| tag.docs.url | Url da Documentação externa da tag | // @tag.docs.url https://example.com|
| tag.docs.description | Descrição da documentação externa da tag| // @tag.docs.description Melhor exemplo de documentação |
| TermsOfService | Os Termos de Serviço para o API.| // @termsOfService http://swagger.io/terms/ |
| contact.name | A informação de contacto para a API exposta.| // @contacto.name Suporte API |
| contact.url | O URL que aponta para as informações de contacto. DEVE estar no formato de um URL. | // @contact.url http://www.swagger.io/support|
| contact.email| O endereço de email da pessoa/organização de contacto. DEVE estar no formato de um endereço de correio electrónico.| // @contact.email support@swagger.io |
| license.name | **Obrigatório.** O nome da licença utilizada para a API.|// @licença.name Apache 2.0|
| license.url | Um URL para a licença utilizada para a API. DEVE estar no formato de um URL. | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | O anfitrião (nome ou ip) que serve o API. | // @host localhost:8080 |
| BasePath | O caminho de base sobre o qual o API é servido. | // @BasePath /api/v1 |
| accept | Uma lista de tipos de MIME que os APIs podem consumir. Note que accept só afecta operações com um organismo de pedido, tais como POST, PUT e PATCH. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). | // @accept json |
| produce | Uma lista de tipos de MIME que os APIs podem produce. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). | // @produce json |
| query.collection.format | O formato padrão de param de colecção(array) em query,enums:csv,multi,pipes,tsv,ssv. Se não definido, csv é o padrão.| // @query.collection.format multi
| schemes | O protocolo de transferência para a operação que separou por espaços. | // @schemes http https |
| externalDocs.description | Descrição do documento externo. | // @externalDocs.description OpenAPI |
| externalDocs.url | URL do documento externo. | // @externalDocs.url https://swagger.io/resources/open-api/ |
| x-name | A chave de extensão, deve ser iniciada por x- e tomar apenas o valor json | // @x-example-key {"chave": "valor"} |
### Usando descrições de remarcação para baixo
Quando uma pequena sequência na sua documentação é insuficiente, ou precisa de imagens, exemplos de códigos e coisas do género, pode querer usar descrições de marcação. Para utilizar as descrições markdown, utilize as seguintes anotações.
| anotação | descrição | exemplo |
|-------------|--------------------------------------------|---------------------------------|
| title | **Obrigatório.** O título da aplicação.| // @title Swagger Example API |
| version | **Obrigatório.** Fornece a versão da aplicação API.| // @versão 1.0 |
| description.markdown | Uma breve descrição da candidatura. Parsed a partir do ficheiro api.md. Esta é uma alternativa a @description |// @description.markdown Sem valor necessário, isto analisa a descrição do ficheiro api.md |.
| tag.name | Nome de uma tag.| // @tag.name Este é o nome da tag |
| tag.description.markdown | Descrição da tag esta é uma alternativa à tag.description. A descrição será lida a partir de um ficheiro nomeado como tagname.md | // @tag.description.markdown |
## Operação API
**Exemplo**
[celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
| anotação | descrição |
|-------------|----------------------------------------------------------------------------------------------------------------------------|
| descrição | Uma explicação verbosa do comportamento da operação. |
| description.markdown | Uma breve descrição da candidatura. A descrição será lida a partir de um ficheiro. Por exemplo, `@description.markdown details` irá carregar `details.md`| // @description.file endpoint.description.markdown |
| id | Um fio único utilizado para identificar a operação. Deve ser única entre todas as operações API. |
| tags | Uma lista de tags para cada operação API que separou por vírgulas. |
| summary | Um breve resumo do que a operação faz. |
| accept | Uma lista de tipos de MIME que os APIs podem consumir. Note que accept só afecta operações com um organismo de pedido, tais como POST, PUT e PATCH. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). |
| produce | Uma lista de tipos de MIME que os APIs podem produce. O valor DEVE ser o descrito em [Tipos de Mime](#mime-types). |
| param | Parâmetros que se separaram por espaços. `param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | [Segurança](#security) para cada operação API. |
| success | resposta de sucesso que separou por espaços. `return code or default`,`{param type}`,`data type`,`comment` |.
| failure | Resposta de falha que separou por espaços. `return code or default`,`{param type}`,`data type`,`comment` |
| response | Igual ao `sucesso` e `falha` |
| header | Cabeçalho em resposta que separou por espaços. `código de retorno`,`{tipo de parâmetro}`,`tipo de dados`,`comentário` |.
| router | Definição do caminho que separou por espaços. caminho",`path`,`[httpMethod]` |[httpMethod]` |
| x-name | A chave de extensão, deve ser iniciada por x- e tomar apenas o valor json. |
| x-codeSample | Optional Markdown use. tomar `file` como parâmetro. Isto irá então procurar um ficheiro nomeado como o resumo na pasta dada. |
| deprecated | Marcar o ponto final como depreciado. |
## Mime Types
`swag` aceita todos os tipos MIME que estão no formato correcto, ou seja, correspondem `*/*`.
Além disso, `swag` também aceita pseudónimos para alguns tipos de MIME, como se segue:
| Alias | MIME Type |
|-----------------------|-----------------------------------|
| json | application/json |
| xml | text/xml |
| plain | text/plain |
| html | text/html |
| mpfd | multipart/form-data |
| x-www-form-urlencoded | application/x-www-form-urlencoded |
| json-api | application/vnd.api+json |
| json-stream | application/x-json-stream |
| octet-stream | application/octet-stream |
| png | image/png |
| jpeg | image/jpeg |
| gif | image/gif |
| event-stream | text/event-stream |
## Tipo de parâmetro
- query
- path
- header
- body
- formData
## Tipo de dados
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- file (param data type when uploading)
- user defined struct
## Segurança
| anotação | descrição | parâmetros | exemplo |
|------------|-------------|------------|---------|
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basicAuth | [Básico]()
| securitydefinitions.apikey | [chave API](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [Aplicação OAuth2](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 | [OAuth2Implicit]()
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [código de acesso OAuth2](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode | [código de acesso OAuth2.accessCode]()
| anotação de parâmetros | exemplo |
|---------------------------------|-------------------------------------------------------------------------|
| 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 | // @descrição OAuth protege os pontos finais da nossa entidade |
## Atributo
```go
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
It also works for the struct fields:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
```
### Disponível
Nome do campo | Tipo | Descrição
---|:---:|---
<a name="validate"></a>validate | `string` | Determina a validação para o parâmetro. Os valores possíveis são: `required,optional`.
<a name="parameterDefault"></a>default | * | Declara o valor do parâmetro que o servidor utilizará se nenhum for fornecido, por exemplo, uma "contagem" para controlar o número de resultados por página poderá ser por defeito de 100 se não for fornecido pelo cliente no pedido. (Nota: "por defeito" não tem significado para os parâmetros requeridos).
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Ao contrário do esquema JSON, este valor DEVE estar em conformidade com o definido [`type`](#parameterType) para este parâmetro.
<a name="parameterMaximum"></a>maximum | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
<a name="parameterMultipleOf"></a>multipleOf | `number` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
<a name="parameterMaxLength"></a>maxLength | `integer` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
<a name="parameterMinLength"></a>minLength | `integer` | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
<a name="parameterEnums"></a>enums | [\*] | Ver https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
<a name="parameterFormat"></a>format | `string` | O formato de extensão para o anteriormente mencionado [`type`](#parameterType). Ver [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) para mais detalhes.
<a name="parameterCollectionFormat"></a>collectionFormat | `string` |Determina o formato da matriz se for utilizada uma matriz de tipos. Os valores possíveis são: <ul><li>`csv` - valores separados por vírgulas `foo,bar`. <li>`ssv` - valores separados por espaço `foo bar`. <li>`tsv` - valores separados por tabulação `foo\tbar`. <li>`pipes` - valores separados por tubo <code>foo&#124;bar</code>. <li>`multi` - corresponde a múltiplas instâncias de parâmetros em vez de múltiplos valores para uma única instância `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData". </ul> Default value is `csv`.
<a name="parameterExample"></a>example | * | Declara o exemplo para o valor do parâmetro
<a name="parameterExtensions"></a>extensions | `string` | Acrescentar extensão aos parâmetros.
### Futuro
Nome do campo | Tipo | Description
---|:---:|---
<a name="parameterPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
<a name="parameterMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
<a name="parameterMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
<a name="parameterUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.
## Exemplos
### Descrições em múltiplas linhas
É possível acrescentar descrições que abranjam várias linhas tanto na descrição geral da api como em definições de rotas como esta:
```go
// @description This is the first line
// @description This is the second line
// @description And so forth.
```
### Estrutura definida pelo utilizador com um tipo de matriz
```go
// @Success 200 {array} model.Account <-- This is a user defined struct.
```
```go
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
```
### Declaração de estruturação de funções
Pode declarar as estruturas de resposta do seu pedido dentro de um corpo funcional.
Deve ter de seguir a convenção de nomeação
`<package-name>.<function-name>.<struct-name> `.
```go
package main
// @Param request body main.MyHandler.request true "query params"
// @Success 200 {object} main.MyHandler.response
// @Router /test [post]
func MyHandler() {
type request struct {
RequestField string
}
type response struct {
ResponseField string
}
}
```
### Composição do modelo em resposta
```go
// JSONResult's data field will be overridden by the specific type proto.Order
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
```
```go
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
Id uint `json:"id"`
Data interface{} `json:"data"`
}
```
- também suportam uma variedade de objectos e tipos primitivos como resposta aninhada
```go
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- campos múltiplos que se sobrepõem. campo será adicionado se não existir
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
- overriding deep-level fields
```go
type DeepObject struct { //in `proto` package
...
}
@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"
```
### Adicionar um cabeçalho em resposta
```go
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
```
### Utilizar parâmetros de caminhos múltiplos
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
```
### Adicionar múltiplos caminhos
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param user_id path int true "User ID"
// ...
// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
// @Router /examples/user/{user_id}/address [put]
```
### Exemplo de valor de estrutura
```go
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
```
### Schema Exemplo do corpo
```go
// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)
```
### Descrição da estrutura
```go
// Account model info
// @Description User account information
// @Description with user id and username
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
```
[#708](https://github.com/swaggo/swag/issues/708) O analisador trata apenas de comentários estruturais a partir de `@Description` attribute.
Assim, gerou o doc. de swagger como se segue:
```json
"Account": {
"type":"object",
"description": "User account information with user id and username"
"properties": {
"id": {
"type": "integer",
"description": "ID this is userid"
},
"name": {
"type":"string",
"description": "This is Name"
}
}
}
```
### Usar etiqueta do tipo swaggertype para suportar o tipo personalizado
[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
```go
type TimestampTime struct {
time.Time
}
///implement encoding.JSON.Marshaler interface
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// Override primitive type by simply specifying it via `swaggertype` tag
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
```
[#379](https://github.com/swaggo/swag/issues/379)
```go
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
```
generated swagger doc as follows:
```go
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
```
### Utilizar anulações globais para suportar um tipo personalizado
Se estiver a utilizar ficheiros gerados, as etiquetas [`swaggertype`](#use-swaggertype-tag-to-supported-custom-type) ou `swaggerignore` podem não ser possíveis.
Ao passar um mapeamento para swag com `--overridesFile` pode dizer swag para utilizar um tipo no lugar de outro onde quer que apareça. Por defeito, se um ficheiro `.swaggo` estiver presente no directório actual, será utilizado.
Go code:
```go
type MyStruct struct {
ID sql.NullInt64 `json:"id"`
Name sql.NullString `json:"name"`
}
```
`.swaggo`:
```
// Substituir todos os NullInt64 por int
replace database/sql.NullInt64 int
// Não inclua quaisquer campos do tipo base de database/sql.
NullString no swagger docs
skip database/sql.NullString
```
As directivas possíveis são comentários (começando por `//`), `replace path/to/a.type path/to/b.type`, e `skip path/to/a.type`.
(Note que os caminhos completos para qualquer tipo nomeado devem ser fornecidos para evitar problemas quando vários pacotes definem um tipo com o mesmo nome)
Entregue em:
```go
"types.MyStruct": {
"id": "integer"
}
### Use swaggerignore tag para excluir um campo
```go
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
```
### Adicionar informações de extensão ao campo de estruturação
```go
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
```
gerar doc. de swagger como se segue:
```go
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
```
### Renomear modelo a expor
```golang
type Resp struct {
Code int
}//@name Response
```
### Como utilizar as anotações de segurança
Informações API gerais.
```go
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
```
Cada operação API.
```go
// @Security ApiKeyAuth
```
Faça-o OR condicione-o
```go
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
```
Faça-o AND condição
```go
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
```
### Adicionar uma descrição para enumerar artigos
```go
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
```
### Gerar apenas tipos de ficheiros de documentos específicos
Por defeito, o comando `swag` gera especificação Swagger em três tipos diferentes de ficheiros/arquivos:
- docs.go
- swagger.json
- swagger.yaml
Se desejar limitar um conjunto de tipos de ficheiros que devem ser gerados pode utilizar a bandeira `--outputTypes` (short `-ot`). O valor por defeito é `go,json,yaml` - tipos de saída separados por vírgula. Para limitar a saída apenas a ficheiros `go` e `yaml`, escrever-se-ia `go,yaml'. Com comando completo que seria `swag init --outputTypes go,yaml`.
### Como usar tipos genéricos
```go
// @Success 200 {object} web.GenericNestedResponse[types.Post]
// @Success 204 {object} web.GenericNestedResponse[types.Post, Types.AnotherOne]
// @Success 201 {object} web.GenericNestedResponse[web.GenericInnerType[types.Post]]
func GetPosts(w http.ResponseWriter, r *http.Request) {
_ = web.GenericNestedResponse[types.Post]{}
}
```
Para mais detalhes e outros exemplos, veja [esse arquivo](https://github.com/swaggo/swag/blob/master/testdata/generics_nested/api/api.go)
### Alterar os delimitadores de acção padrão Go Template
[#980](https://github.com/swaggo/swag/issues/980)
[#1177](https://github.com/swaggo/swag/issues/1177)
Se as suas anotações ou campos estruturantes contêm "{{" or "}}", a geração de modelos irá muito provavelmente falhar, uma vez que estes são os delimitadores por defeito para [go templates](https://pkg.go.dev/text/template#Template.Delims).
Para que a geração funcione correctamente, pode alterar os delimitadores por defeito com `-td'. Por exemplo:
``console
swag init -g http/api.go -td "[[,]"
```
O novo delimitador é um fio com o formato "`<left delimiter>`,`<right delimiter>`".
## Sobre o projecto
Este projecto foi inspirado por [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) mas simplificámos a utilização e acrescentámos apoio a uma variedade de [frameworks web](#estruturas-web-suportadas). A fonte de imagem Gopher é [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). Tem licenças [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
## Contribuidores
Este projecto existe graças a todas as pessoas que contribuem. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
## Apoios
Obrigado a todos os nossos apoiantes! 🙏 [[Become a backer](https://opencollective.com/swag#backer)]
<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
## Patrocinadores
Apoiar este projecto tornando-se um patrocinador. O seu logótipo aparecerá aqui com um link para o seu website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
## Licença
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)

771
vendor/github.com/swaggo/swag/README_zh-CN.md generated vendored Normal file
View File

@@ -0,0 +1,771 @@
# swag
🌍 *[English](README.md) ∙ [简体中文](README_zh-CN.md)*
<img align="right" width="180px" src="https://raw.githubusercontent.com/swaggo/swag/master/assets/swaggo.png">
[![Travis Status](https://img.shields.io/travis/swaggo/swag/master.svg)](https://travis-ci.org/swaggo/swag)
[![Coverage Status](https://img.shields.io/codecov/c/github/swaggo/swag/master.svg)](https://codecov.io/gh/swaggo/swag)
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/swag/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)
Swag将Go的注释转换为Swagger2.0文档。我们为流行的 [Go Web Framework](#支持的Web框架) 创建了各种插件,这样可以与现有Go项目快速集成(使用Swagger UI)。
## 目录
- [快速开始](#快速开始)
- [支持的Web框架](#支持的web框架)
- [如何与Gin集成](#如何与gin集成)
- [格式化说明](#格式化说明)
- [开发现状](#开发现状)
- [声明式注释格式](#声明式注释格式)
- [通用API信息](#通用api信息)
- [API操作](#api操作)
- [安全性](#安全性)
- [样例](#样例)
- [多行的描述](#多行的描述)
- [用户自定义的具有数组类型的结构](#用户自定义的具有数组类型的结构)
- [响应对象中的模型组合](#响应对象中的模型组合)
- [在响应中增加头字段](#在响应中增加头字段)
- [使用多路径参数](#使用多路径参数)
- [结构体的示例值](#结构体的示例值)
- [结构体描述](#结构体描述)
- [使用`swaggertype`标签更改字段类型](#使用`swaggertype`标签更改字段类型)
- [使用`swaggerignore`标签排除字段](#使用swaggerignore标签排除字段)
- [将扩展信息添加到结构字段](#将扩展信息添加到结构字段)
- [对展示的模型重命名](#对展示的模型重命名)
- [如何使用安全性注释](#如何使用安全性注释)
- [项目相关](#项目相关)
## 快速开始
1. 将注释添加到API源代码中,请参阅声明性注释格式。
2. 使用如下命令下载swag:
```bash
go install github.com/swaggo/swag/cmd/swag@latest
```
从源码开始构建的话,需要有Go环境(1.19及以上版本)。
或者从github的release页面下载预编译好的二进制文件。
3. 在包含`main.go`文件的项目根目录运行`swag init`。这将会解析注释并生成需要的文件(`docs`文件夹和`docs/docs.go`)。
```bash
swag init
```
确保导入了生成的`docs/docs.go`文件,这样特定的配置文件才会被初始化。如果通用API注释没有写在`main.go`中,可以使用`-g`标识符来告知swag。
```bash
swag init -g http/api.go
```
4. (可选) 使用`fmt`格式化 SWAG 注释。(请先升级到最新版本)
```bash
swag fmt
```
## swag cli
```bash
swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--generalInfo value, -g value API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
--dir value, -d value API解析目录 (默认: "./")
--exclude value 解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
--propertyStrategy value, -p value 结构体字段命名规则,三种:snakecase,camelcase,pascalcase (默认: "camelcase")
--output value, -o value 文件(swagger.json, swagger.yaml and doc.go)输出目录 (默认: "./docs")
--parseVendor 是否解析vendor目录里的go源文件,默认不
--parseDependency 是否解析依赖目录中的go源文件,默认不
--parseDependencyLevel, --pdl 对'--parseDependency'参数进行增强, 是否解析依赖目录中的go源文件, 0 不解析, 1 只解析对象模型, 2 只解析API, 3 对象模型和API都解析 (default: 0)
--markdownFiles value, --md value 指定API的描述信息所使用的markdown文件所在的目录
--generatedTime 是否输出时间到输出文件docs.go的顶部,默认是
--codeExampleFiles value, --cef value 解析包含用于 x-codeSamples 扩展的代码示例文件的文件夹,默认禁用
--parseInternal 解析 internal 包中的go文件,默认禁用
--parseDepth value 依赖解析深度 (默认: 100)
--instanceName value 设置文档实例名 (默认: "swagger")
```
```bash
swag fmt -h
NAME:
swag fmt - format swag comments
USAGE:
swag fmt [command options] [arguments...]
OPTIONS:
--dir value, -d value API解析目录 (默认: "./")
--exclude value 解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
--generalInfo value, -g value API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
--help, -h show help (default: false)
```
## 支持的Web框架
- [gin](http://github.com/swaggo/gin-swagger)
- [echo](http://github.com/swaggo/echo-swagger)
- [buffalo](https://github.com/swaggo/buffalo-swagger)
- [net/http](https://github.com/swaggo/http-swagger)
- [gorilla/mux](https://github.com/swaggo/http-swagger)
- [go-chi/chi](https://github.com/swaggo/http-swagger)
- [flamingo](https://github.com/i-love-flamingo/swagger)
- [fiber](https://github.com/gofiber/swagger)
- [atreugo](https://github.com/Nerzal/atreugo-swagger)
- [hertz](https://github.com/hertz-contrib/swagger)
## 如何与Gin集成
[点击此处](https://github.com/swaggo/swag/tree/master/example/celler)查看示例源代码。
1. 使用`swag init`生成Swagger2.0文档后,导入如下代码包:
```go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
```
2. 在`main.go`源代码中添加通用的API注释:
```go
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
```
此外,可以动态设置一些通用的API信息。生成的代码包`docs`导出`SwaggerInfo`变量,使用该变量可以通过编码的方式设置标题、描述、版本、主机和基础路径。使用Gin的示例:
```go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
```
3. 在`controller`代码中添加API操作注释:
```go
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
```
```bash
swag init
```
4. 运行程序,然后在浏览器中访问 http://localhost:8080/swagger/index.html 。将看到Swagger 2.0 Api文档,如下所示:
![swagger_index.html](https://raw.githubusercontent.com/swaggo/swag/master/assets/swagger-image.png)
## 格式化说明
可以针对Swag的注释自动格式化,就像`go fmt`。
此处查看格式化结果 [here](https://github.com/swaggo/swag/tree/master/example/celler).
示例:
```shell
swag fmt
```
排除目录(不扫描)示例:
```shell
swag fmt -d ./ --exclude ./internal
```
## 开发现状
[Swagger 2.0 文档](https://swagger.io/docs/specification/2-0/basic-structure/)
- [x] Basic Structure
- [x] API Host and Base Path
- [x] Paths and Operations
- [x] Describing Parameters
- [x] Describing Request Body
- [x] Describing Responses
- [x] MIME Types
- [x] Authentication
- [x] Basic Authentication
- [x] API Keys
- [x] Adding Examples
- [x] File Upload
- [x] Enums
- [x] Grouping Operations With Tags
- [ ] Swagger Extensions
## 声明式注释格式
## 通用API信息
**示例** [`celler/main.go`](https://github.com/swaggo/swag/blob/master/example/celler/main.go)
| 注释 | 说明 | 示例 |
| ----------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| title | **必填** 应用程序的名称。 | // @title Swagger Example API |
| version | **必填** 提供应用程序API的版本。 | // @version 1.0 |
| description | 应用程序的简短描述。 | // @description This is a sample server celler server. |
| tag.name | 标签的名称。 | // @tag.name This is the name of the tag |
| tag.description | 标签的描述。 | // @tag.description Cool Description |
| tag.docs.url | 标签的外部文档的URL。 | // @tag.docs.url https://example.com |
| tag.docs.description | 标签的外部文档说明。 | // @tag.docs.description Best example documentation |
| termsOfService | API的服务条款。 | // @termsOfService http://swagger.io/terms/ |
| contact.name | 公开的API的联系信息。 | // @contact.name API Support |
| contact.url | 联系信息的URL。 必须采用网址格式。 | // @contact.url http://www.swagger.io/support |
| contact.email | 联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。 | // @contact.email support@swagger.io |
| license.name | **必填** 用于API的许可证名称。 | // @license.name Apache 2.0 |
| license.url | 用于API的许可证的URL。 必须采用网址格式。 | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | 运行API的主机(主机名或IP地址)。 | // @host localhost:8080 |
| BasePath | 运行API的基本路径。 | // @BasePath /api/v1 |
| accept | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 | // @accept json |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 | // @produce json |
| query.collection.format | 请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。 | // @query.collection.format multi |
| schemes | 用空格分隔的请求的传输协议。 | // @schemes http https |
| externalDocs.description | Description of the external document. | // @externalDocs.description OpenAPI |
| externalDocs.url | URL of the external document. | // @externalDocs.url https://swagger.io/resources/open-api/ |
| x-name | 扩展的键必须以x-开头,并且只能使用json值 | // @x-example-key {"key": "value"} |
### 使用Markdown描述
如果文档中的短字符串不足以完整表达,或者需要展示图片,代码示例等类似的内容,则可能需要使用Markdown描述。要使用Markdown描述,请使用一下注释。
| 注释 | 说明 | 示例 |
| ------------------------ | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| title | **必填** 应用程序的名称。 | // @title Swagger Example API |
| version | **必填** 提供应用程序API的版本。 | // @version 1.0 |
| description.markdown | 应用程序的简短描述。 从`api.md`文件中解析。 这是`@description`的替代用法。 | // @description.markdown No value needed, this parses the description from api.md |
| tag.name | 标签的名称。 | // @tag.name This is the name of the tag |
| tag.description.markdown | 标签说明,这是`tag.description`的替代用法。 该描述将从名为`tagname.md的`文件中读取。 | // @tag.description.markdown |
## API操作
Example [celler/controller](https://github.com/swaggo/swag/tree/master/example/celler/controller)
| 注释 | 描述 |
|----------------------|------------------------------------------------------------------------------------------------|
| description | 操作行为的详细说明。 |
| description.markdown | 应用程序的简短描述。该描述将从名为`endpointname.md`的文件中读取。 |
| id | 用于标识操作的唯一字符串。在所有API操作中必须唯一。 |
| tags | 每个API操作的标签列表,以逗号分隔。 |
| summary | 该操作的简短摘要。 |
| accept | API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 |
| param | 用空格分隔的参数。`param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | 每个API操作的[安全性](#安全性)。 |
| success | 以空格分隔的成功响应。`return code`,`{param type}`,`data type`,`comment` |
| failure | 以空格分隔的故障响应。`return code`,`{param type}`,`data type`,`comment` |
| response | 与success、failure作用相同 |
| header | 以空格分隔的头字段。 `return code`,`{param type}`,`data type`,`comment` |
| router | 以空格分隔的路径定义。 `path`,`[httpMethod]` |
| deprecatedrouter | 与router相同,但是是deprecated的。 |
| x-name | 扩展字段必须以`x-`开头,并且只能使用json值。 |
| deprecated | 将当前API操作的所有路径设置为deprecated |
## Mime类型
`swag` 接受所有格式正确的MIME类型, 即使匹配 `*/*`。除此之外,`swag`还接受某些MIME类型的别名,如下所示:
| Alias | MIME Type |
| --------------------- | --------------------------------- |
| json | application/json |
| xml | text/xml |
| plain | text/plain |
| html | text/html |
| mpfd | multipart/form-data |
| x-www-form-urlencoded | application/x-www-form-urlencoded |
| json-api | application/vnd.api+json |
| json-stream | application/x-json-stream |
| octet-stream | application/octet-stream |
| png | image/png |
| jpeg | image/jpeg |
| gif | image/gif |
| event-stream | text/event-stream |
## 参数类型
- query
- path
- header
- body
- formData
## 数据类型
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- user defined struct
## 安全性
| 注释 | 描述 | 参数 | 示例 |
| -------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------ |
| 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 |
| 参数注释 | 示例 |
| ---------------- | -------------------------------------------------------- |
| 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 |
## 属性
```go
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
也适用于结构体字段:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
```
### 当前可用的
| 字段名 | 类型 | 描述 |
| ---------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| default | * | 声明如果未提供任何参数,则服务器将使用的默认参数值,例如,如果请求中的客户端未提供该参数,则用于控制每页结果数的“计数”可能默认为100。 (注意:“default”对于必需的参数没有意义)。参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2。 与JSON模式不同,此值务必符合此参数的定义[类型](#parameterType)。 |
| maximum | `number` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. |
| minimum | `number` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. |
| maxLength | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. |
| minLength | `integer` | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. |
| enums | [\*] | 参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. |
| format | `string` | 上面提到的[类型](#parameterType)的扩展格式。有关更多详细信息,请参见[数据类型格式](https://swagger.io/specification/v2/#dataTypeFormat)。 |
| collectionFormat | `string` | 指定query数组参数的格式。 可能的值为: <ul><li>`csv` - 逗号分隔值 `foo,bar`. <li>`ssv` - 空格分隔值 `foo bar`. <li>`tsv` - 制表符分隔值 `foo\tbar`. <li>`pipes` - 管道符分隔值 <code>foo&#124;bar</code>. <li>`multi` - 对应于多个参数实例,而不是单个实例 `foo=bar&foo=baz` 的多个值。这仅对“`query`”或“`formData`”中的参数有效。 </ul> 默认值是 `csv`。 |
### 进一步的
| 字段名 | 类型 | 描述 |
| ----------- | :-------: | ---------------------------------------------------------------------------------- |
| multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
| pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. |
| maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. |
| minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. |
| uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. |
## 样例
### 多行的描述
可以在常规api描述或路由定义中添加跨越多行的描述,如下所示:
```go
// @description This is the first line
// @description This is the second line
// @description And so forth.
```
### 用户自定义的具有数组类型的结构
```go
// @Success 200 {array} model.Account <-- This is a user defined struct.
```
```go
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
```
### 响应对象中的模型组合
```go
// JSONResult的data字段类型将被proto.Order类型替换
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
```
```go
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
...
}
```
- 还支持对象数组和原始类型作为嵌套响应
```go
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- 替换多个字段的类型。如果某字段不存在,将添加该字段。
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
### 在响应中增加头字段
```go
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
```
### 使用多路径参数
```go
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
```
### 结构体的示例值
```go
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
```
### 结构体描述
```go
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
```
### 使用`swaggertype`标签更改字段类型
[#201](https://github.com/swaggo/swag/issues/201#issuecomment-475479409)
```go
type TimestampTime struct {
time.Time
}
///实现encoding.JSON.Marshaler接口
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
///实现encoding.JSON.Unmarshaler接口
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// 使用`swaggertype`标签将别名类型更改为内置类型integer
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// 使用`swaggertype`标签更改struct类型为内置类型integer
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
```
[#379](https://github.com/swaggo/swag/issues/379)
```go
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
```
生成的swagger文档如下:
```go
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
```
### 使用`swaggerignore`标签排除字段
```go
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
```
### 将扩展信息添加到结构字段
```go
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // 扩展字段必须以"x-"开头
}
```
生成swagger文档,如下所示:
```go
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
```
### 对展示的模型重命名
```go
type Resp struct {
Code int
}//@name Response
```
### 如何使用安全性注释
通用API信息。
```go
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
```
每个API操作。
```go
// @Security ApiKeyAuth
```
使用AND条件。
```go
// @Security ApiKeyAuth && OAuth2Application[write, admin]
```
## 项目相关
This project was inspired by [yvasiyarov/swagger](https://github.com/yvasiyarov/swagger) but we simplified the usage and added support a variety of [web frameworks](#supported-web-frameworks). Gopher image source is [tenntenn/gopher-stickers](https://github.com/tenntenn/gopher-stickers). It has licenses [creative commons licensing](http://creativecommons.org/licenses/by/3.0/deed.en).
## 贡献者
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/swaggo/swag/graphs/contributors"><img src="https://opencollective.com/swag/contributors.svg?width=890&button=false" /></a>
## 支持者
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/swag#backer)]
<a href="https://opencollective.com/swag#backers" target="_blank"><img src="https://opencollective.com/swag/backers.svg?width=890"></a>
## 赞助商
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/swag#sponsor)]
<a href="https://opencollective.com/swag/sponsor/0/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/1/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/2/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/3/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/4/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/5/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/6/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/7/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/8/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/swag/sponsor/9/website" target="_blank"><img src="https://opencollective.com/swag/sponsor/9/avatar.svg"></a>
## License
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_large)

580
vendor/github.com/swaggo/swag/const.go generated vendored Normal file
View File

@@ -0,0 +1,580 @@
package swag
import (
"go/ast"
"go/token"
"reflect"
"strconv"
"strings"
"unicode/utf8"
)
// ConstVariable a model to record a const variable
type ConstVariable struct {
Name *ast.Ident
Type ast.Expr
Value interface{}
Comment *ast.CommentGroup
File *ast.File
Pkg *PackageDefinitions
}
// VariableName gets the name for this const variable, taking into account comment overrides.
func (cv *ConstVariable) VariableName() string {
if ignoreNameOverride(cv.Name.Name) {
return cv.Name.Name[1:]
}
if overriddenName := nameOverride(cv.Comment); overriddenName != "" {
return overriddenName
}
return cv.Name.Name
}
var escapedChars = map[uint8]uint8{
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'\\': '\\',
'"': '"',
}
// EvaluateEscapedChar parse escaped character
func EvaluateEscapedChar(text string) rune {
if len(text) == 1 {
return rune(text[0])
}
if len(text) == 2 && text[0] == '\\' {
return rune(escapedChars[text[1]])
}
if len(text) == 6 && text[0:2] == "\\u" {
n, err := strconv.ParseInt(text[2:], 16, 32)
if err == nil {
return rune(n)
}
}
return 0
}
// EvaluateEscapedString parse escaped characters in string
func EvaluateEscapedString(text string) string {
if !strings.ContainsRune(text, '\\') {
return text
}
result := make([]byte, 0, len(text))
for i := 0; i < len(text); i++ {
if text[i] == '\\' {
i++
if text[i] == 'u' {
i++
char, err := strconv.ParseInt(text[i:i+4], 16, 32)
if err == nil {
result = utf8.AppendRune(result, rune(char))
}
i += 3
} else if c, ok := escapedChars[text[i]]; ok {
result = append(result, c)
}
} else {
result = append(result, text[i])
}
}
return string(result)
}
// EvaluateDataConversion evaluate the type a explicit type conversion
func EvaluateDataConversion(x interface{}, typeName string) interface{} {
switch value := x.(type) {
case int:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int8:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint8:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int16:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint16:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int32:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
case "string":
return string(value)
}
case uint32:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case int64:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case uint64:
switch typeName {
case "int":
return int(value)
case "byte":
return byte(value)
case "int8":
return int8(value)
case "int16":
return int16(value)
case "int32":
return int32(value)
case "int64":
return int64(value)
case "uint":
return uint(value)
case "uint8":
return uint8(value)
case "uint16":
return uint16(value)
case "uint32":
return uint32(value)
case "uint64":
return uint64(value)
case "rune":
return rune(value)
}
case string:
switch typeName {
case "string":
return value
}
}
return nil
}
// EvaluateUnary evaluate the type and value of a unary expression
func EvaluateUnary(x interface{}, operator token.Token, xtype ast.Expr) (interface{}, ast.Expr) {
switch operator {
case token.SUB:
switch value := x.(type) {
case int:
return -value, xtype
case int8:
return -value, xtype
case int16:
return -value, xtype
case int32:
return -value, xtype
case int64:
return -value, xtype
}
case token.XOR:
switch value := x.(type) {
case int:
return ^value, xtype
case int8:
return ^value, xtype
case int16:
return ^value, xtype
case int32:
return ^value, xtype
case int64:
return ^value, xtype
case uint:
return ^value, xtype
case uint8:
return ^value, xtype
case uint16:
return ^value, xtype
case uint32:
return ^value, xtype
case uint64:
return ^value, xtype
}
}
return nil, nil
}
// EvaluateBinary evaluate the type and value of a binary expression
func EvaluateBinary(x, y interface{}, operator token.Token, xtype, ytype ast.Expr) (interface{}, ast.Expr) {
if operator == token.SHR || operator == token.SHL {
var rightOperand uint64
yValue := reflect.ValueOf(y)
if yValue.CanUint() {
rightOperand = yValue.Uint()
} else if yValue.CanInt() {
rightOperand = uint64(yValue.Int())
}
switch operator {
case token.SHL:
switch xValue := x.(type) {
case int:
return xValue << rightOperand, xtype
case int8:
return xValue << rightOperand, xtype
case int16:
return xValue << rightOperand, xtype
case int32:
return xValue << rightOperand, xtype
case int64:
return xValue << rightOperand, xtype
case uint:
return xValue << rightOperand, xtype
case uint8:
return xValue << rightOperand, xtype
case uint16:
return xValue << rightOperand, xtype
case uint32:
return xValue << rightOperand, xtype
case uint64:
return xValue << rightOperand, xtype
}
case token.SHR:
switch xValue := x.(type) {
case int:
return xValue >> rightOperand, xtype
case int8:
return xValue >> rightOperand, xtype
case int16:
return xValue >> rightOperand, xtype
case int32:
return xValue >> rightOperand, xtype
case int64:
return xValue >> rightOperand, xtype
case uint:
return xValue >> rightOperand, xtype
case uint8:
return xValue >> rightOperand, xtype
case uint16:
return xValue >> rightOperand, xtype
case uint32:
return xValue >> rightOperand, xtype
case uint64:
return xValue >> rightOperand, xtype
}
}
return nil, nil
}
evalType := xtype
if evalType == nil {
evalType = ytype
}
xValue := reflect.ValueOf(x)
yValue := reflect.ValueOf(y)
if xValue.Kind() == reflect.String && yValue.Kind() == reflect.String {
return xValue.String() + yValue.String(), evalType
}
var targetValue reflect.Value
if xValue.Kind() != reflect.Int {
targetValue = reflect.New(xValue.Type()).Elem()
} else {
targetValue = reflect.New(yValue.Type()).Elem()
}
switch operator {
case token.ADD:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() + yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() + yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) + yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() + uint64(yValue.Int()))
}
case token.SUB:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() - yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() - yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) - yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() - uint64(yValue.Int()))
}
case token.MUL:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() * yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() * yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) * yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() * uint64(yValue.Int()))
}
case token.QUO:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() / yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() / yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) / yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() / uint64(yValue.Int()))
}
case token.REM:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() % yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() % yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) % yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() % uint64(yValue.Int()))
}
case token.AND:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() & yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() & yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) & yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() & uint64(yValue.Int()))
}
case token.OR:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() | yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() | yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) | yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() | uint64(yValue.Int()))
}
case token.XOR:
if xValue.CanInt() && yValue.CanInt() {
targetValue.SetInt(xValue.Int() ^ yValue.Int())
} else if xValue.CanUint() && yValue.CanUint() {
targetValue.SetUint(xValue.Uint() ^ yValue.Uint())
} else if xValue.CanInt() && yValue.CanUint() {
targetValue.SetUint(uint64(xValue.Int()) ^ yValue.Uint())
} else if xValue.CanUint() && yValue.CanInt() {
targetValue.SetUint(xValue.Uint() ^ uint64(yValue.Int()))
}
}
return targetValue.Interface(), evalType
}

5
vendor/github.com/swaggo/swag/doc.go generated vendored Normal file
View File

@@ -0,0 +1,5 @@
/*
Package swag converts Go annotations to Swagger Documentation 2.0.
See https://github.com/swaggo/swag for more information about swag.
*/
package swag // import "github.com/swaggo/swag"

14
vendor/github.com/swaggo/swag/enums.go generated vendored Normal file
View File

@@ -0,0 +1,14 @@
package swag
const (
enumVarNamesExtension = "x-enum-varnames"
enumCommentsExtension = "x-enum-comments"
enumDescriptionsExtension = "x-enum-descriptions"
)
// EnumValue a model to record an enum consts variable
type EnumValue struct {
key string
Value interface{}
Comment string
}

696
vendor/github.com/swaggo/swag/field_parser.go generated vendored Normal file
View File

@@ -0,0 +1,696 @@
package swag
import (
"fmt"
"go/ast"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"unicode"
"github.com/go-openapi/spec"
)
var _ FieldParser = &tagBaseFieldParser{p: nil, field: nil, tag: ""}
const (
requiredLabel = "required"
optionalLabel = "optional"
omitEmptyLabel = "omitempty"
swaggerTypeTag = "swaggertype"
swaggerIgnoreTag = "swaggerignore"
)
type tagBaseFieldParser struct {
p *Parser
field *ast.Field
tag reflect.StructTag
}
func newTagBaseFieldParser(p *Parser, field *ast.Field) FieldParser {
fieldParser := tagBaseFieldParser{
p: p,
field: field,
tag: "",
}
if fieldParser.field.Tag != nil {
fieldParser.tag = reflect.StructTag(strings.ReplaceAll(field.Tag.Value, "`", ""))
}
return &fieldParser
}
func (ps *tagBaseFieldParser) ShouldSkip() bool {
// Skip non-exported fields.
if ps.field.Names != nil && !ast.IsExported(ps.field.Names[0].Name) {
return true
}
if ps.field.Tag == nil {
return false
}
ignoreTag := ps.tag.Get(swaggerIgnoreTag)
if strings.EqualFold(ignoreTag, "true") {
return true
}
// json:"tag,hoge"
name := strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name == "-" {
return true
}
return false
}
func (ps *tagBaseFieldParser) FieldNames() ([]string, error) {
if len(ps.field.Names) <= 1 {
// if embedded but with a json/form name ??
if ps.field.Tag != nil {
// json:"tag,hoge"
name := strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name != "" {
return []string{name}, nil
}
// use "form" tag over json tag
name = ps.FormName()
if name != "" {
return []string{name}, nil
}
}
if len(ps.field.Names) == 0 {
return nil, nil
}
}
var names = make([]string, 0, len(ps.field.Names))
for _, name := range ps.field.Names {
switch ps.p.PropNamingStrategy {
case SnakeCase:
names = append(names, toSnakeCase(name.Name))
case PascalCase:
names = append(names, name.Name)
default:
names = append(names, toLowerCamelCase(name.Name))
}
}
return names, nil
}
func (ps *tagBaseFieldParser) FirstTagValue(tag string) string {
if ps.field.Tag != nil {
return strings.TrimRight(strings.TrimSpace(strings.Split(ps.tag.Get(tag), ",")[0]), "[]")
}
return ""
}
func (ps *tagBaseFieldParser) FormName() string {
return ps.FirstTagValue(formTag)
}
func (ps *tagBaseFieldParser) HeaderName() string {
return ps.FirstTagValue(headerTag)
}
func (ps *tagBaseFieldParser) PathName() string {
return ps.FirstTagValue(uriTag)
}
func toSnakeCase(in string) string {
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[idx]))
}
return string(out)
}
func toLowerCamelCase(in string) string {
var flag bool
out := make([]rune, len(in))
runes := []rune(in)
for i, curr := range runes {
if (i == 0 && unicode.IsUpper(curr)) || (flag && unicode.IsUpper(curr)) {
out[i] = unicode.ToLower(curr)
flag = true
continue
}
out[i] = curr
flag = false
}
return string(out)
}
func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
if ps.field.Tag == nil {
return nil, nil
}
typeTag := ps.tag.Get(swaggerTypeTag)
if typeTag != "" {
return BuildCustomSchema(strings.Split(typeTag, ","))
}
return nil, nil
}
type structField struct {
title string
schemaType string
arrayType string
formatType string
maximum *float64
minimum *float64
multipleOf *float64
maxLength *int64
minLength *int64
maxItems *int64
minItems *int64
exampleValue interface{}
enums []interface{}
enumVarNames []interface{}
unique bool
}
// splitNotWrapped slices s into all substrings separated by sep if sep is not
// wrapped by brackets and returns a slice of the substrings between those separators.
func splitNotWrapped(s string, sep rune) []string {
openCloseMap := map[rune]rune{
'(': ')',
'[': ']',
'{': '}',
}
var (
result = make([]string, 0)
current = strings.Builder{}
openCount = 0
openChar rune
)
for _, char := range s {
switch {
case openChar == 0 && openCloseMap[char] != 0:
openChar = char
openCount++
current.WriteRune(char)
case char == openChar:
openCount++
current.WriteRune(char)
case openCount > 0 && char == openCloseMap[openChar]:
openCount--
current.WriteRune(char)
case openCount == 0 && char == sep:
result = append(result, current.String())
openChar = 0
current = strings.Builder{}
default:
current.WriteRune(char)
}
}
if current.String() != "" {
result = append(result, current.String())
}
return result
}
// ComplementSchema complement schema with field properties
func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
types := ps.p.GetSchemaTypePath(schema, 2)
if len(types) == 0 {
return fmt.Errorf("invalid type for field: %s", ps.field.Names[0])
}
if IsRefSchema(schema) {
var newSchema = spec.Schema{}
err := ps.complementSchema(&newSchema, types)
if err != nil {
return err
}
if !reflect.ValueOf(newSchema).IsZero() {
*schema = *(newSchema.WithAllOf(*schema))
}
return nil
}
return ps.complementSchema(schema, types)
}
// complementSchema complement schema with field properties
func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, types []string) error {
if ps.field.Tag == nil {
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
}
field := &structField{
schemaType: types[0],
formatType: ps.tag.Get(formatTag),
title: ps.tag.Get(titleTag),
}
if len(types) > 1 && (types[0] == ARRAY || types[0] == OBJECT) {
field.arrayType = types[1]
}
jsonTagValue := ps.tag.Get(jsonTag)
bindingTagValue := ps.tag.Get(bindingTag)
if bindingTagValue != "" {
parseValidTags(bindingTagValue, field)
}
validateTagValue := ps.tag.Get(validateTag)
if validateTagValue != "" {
parseValidTags(validateTagValue, field)
}
enumsTagValue := ps.tag.Get(enumsTag)
if enumsTagValue != "" {
err := parseEnumTags(enumsTagValue, field)
if err != nil {
return err
}
}
if IsNumericType(field.schemaType) || IsNumericType(field.arrayType) {
maximum, err := getFloatTag(ps.tag, maximumTag)
if err != nil {
return err
}
if maximum != nil {
field.maximum = maximum
}
minimum, err := getFloatTag(ps.tag, minimumTag)
if err != nil {
return err
}
if minimum != nil {
field.minimum = minimum
}
multipleOf, err := getFloatTag(ps.tag, multipleOfTag)
if err != nil {
return err
}
if multipleOf != nil {
field.multipleOf = multipleOf
}
}
if field.schemaType == STRING || field.arrayType == STRING {
maxLength, err := getIntTag(ps.tag, maxLengthTag)
if err != nil {
return err
}
if maxLength != nil {
field.maxLength = maxLength
}
minLength, err := getIntTag(ps.tag, minLengthTag)
if err != nil {
return err
}
if minLength != nil {
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(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: "",
INTEGER: "0",
BOOLEAN: "false",
NUMBER: "0",
}
defaultValue, ok := defaultValues[field.schemaType]
if ok {
field.schemaType = STRING
*schema = *PrimitiveSchema(field.schemaType)
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")
field.exampleValue = defaultValue
}
}
}
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.ReadOnly = ps.tag.Get(readOnlyTag) == "true"
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.Title = field.title
extensionsTagValue := ps.tag.Get(extensionsTag)
if extensionsTagValue != "" {
schema.Extensions = setExtensionParam(extensionsTagValue)
}
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[enumVarNamesExtension] = field.enumVarNames
} else {
// Add to top level schema
if schema.Extensions == nil {
schema.Extensions = map[string]interface{}{}
}
schema.Extensions[enumVarNamesExtension] = field.enumVarNames
}
}
eleSchema := schema
if field.schemaType == ARRAY {
// For Array only
schema.MaxItems = field.maxItems
schema.MinItems = field.minItems
schema.UniqueItems = field.unique
eleSchema = schema.Items.Schema
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
}
func getFloatTag(structTag reflect.StructTag, tagName string) (*float64, error) {
strValue := structTag.Get(tagName)
if strValue == "" {
return nil, nil
}
value, err := strconv.ParseFloat(strValue, 64)
if err != nil {
return nil, fmt.Errorf("can't parse numeric value of %q tag: %v", tagName, err)
}
return &value, nil
}
func getIntTag(structTag reflect.StructTag, tagName string) (*int64, error) {
strValue := structTag.Get(tagName)
if strValue == "" {
return nil, nil
}
value, err := strconv.ParseInt(strValue, 10, 64)
if err != nil {
return nil, fmt.Errorf("can't parse numeric value of %q tag: %v", tagName, err)
}
return &value, nil
}
func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
if ps.field.Tag == nil {
return false, nil
}
bindingTag := ps.tag.Get(bindingTag)
if bindingTag != "" {
for _, val := range strings.Split(bindingTag, ",") {
switch val {
case requiredLabel:
return true, nil
case optionalLabel:
return false, nil
}
}
}
validateTag := ps.tag.Get(validateTag)
if validateTag != "" {
for _, val := range strings.Split(validateTag, ",") {
switch val {
case requiredLabel:
return true, nil
case optionalLabel:
return false, nil
}
}
}
jsonTag := ps.tag.Get(jsonTag)
if jsonTag != "" {
for _, val := range strings.Split(jsonTag, ",") {
if val == omitEmptyLabel {
return false, nil
}
}
}
return ps.p.RequiredByDefault, nil
}
func parseValidTags(validTag string, sf *structField) {
// `validate:"required,max=10,min=1"`
// ps. required checked by IsRequired().
for _, val := range strings.Split(validTag, ",") {
var (
valValue string
keyVal = strings.Split(val, "=")
)
switch len(keyVal) {
case 1:
case 2:
valValue = strings.ReplaceAll(strings.ReplaceAll(keyVal[1], utf8HexComma, ","), utf8Pipe, "|")
default:
continue
}
switch keyVal[0] {
case "max", "lte":
sf.setMax(valValue)
case "min", "gte":
sf.setMin(valValue)
case "oneof":
sf.setOneOf(valValue)
case "unique":
if sf.schemaType == ARRAY {
sf.unique = true
}
case "dive":
// ignore dive
return
default:
continue
}
}
}
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
}
enumType := sf.schemaType
if sf.schemaType == ARRAY {
enumType = sf.arrayType
}
valValues := parseOneOfParam2(valValue)
for i := range valValues {
value, err := defineType(enumType, valValues[i])
if err != nil {
continue
}
sf.enums = append(sf.enums, value)
}
}
func (sf *structField) setMin(valValue string) {
value, err := strconv.ParseFloat(valValue, 64)
if err != nil {
return
}
switch sf.schemaType {
case INTEGER, NUMBER:
sf.minimum = &value
case STRING:
intValue := int64(value)
sf.minLength = &intValue
case ARRAY:
intValue := int64(value)
sf.minItems = &intValue
}
}
func (sf *structField) setMax(valValue string) {
value, err := strconv.ParseFloat(valValue, 64)
if err != nil {
return
}
switch sf.schemaType {
case INTEGER, NUMBER:
sf.maximum = &value
case STRING:
intValue := int64(value)
sf.maxLength = &intValue
case ARRAY:
intValue := int64(value)
sf.maxItems = &intValue
}
}
const (
utf8HexComma = "0x2C"
utf8Pipe = "0x7C"
)
// 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(param string) []string {
oneofValsCacheRWLock.RLock()
values, ok := oneofValsCache[param]
oneofValsCacheRWLock.RUnlock()
if !ok {
oneofValsCacheRWLock.Lock()
values = splitParamsRegex.FindAllString(param, -1)
for i := 0; i < len(values); i++ {
values[i] = strings.ReplaceAll(values[i], "'", "")
}
oneofValsCache[param] = values
oneofValsCacheRWLock.Unlock()
}
return values
}
// ---.

187
vendor/github.com/swaggo/swag/formatter.go generated vendored Normal file
View File

@@ -0,0 +1,187 @@
package swag
import (
"bytes"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"log"
"os"
"regexp"
"sort"
"strings"
"text/tabwriter"
"golang.org/x/tools/imports"
)
// Check of @Param @Success @Failure @Response @Header
var specialTagForSplit = map[string]bool{
paramAttr: true,
successAttr: true,
failureAttr: true,
responseAttr: true,
headerAttr: true,
}
var skipChar = map[byte]byte{
'"': '"',
'(': ')',
'{': '}',
'[': ']',
}
// Formatter implements a formatter for Go source files.
type Formatter struct {
// debugging output goes here
debug Debugger
}
// NewFormatter create a new formatter instance.
func NewFormatter() *Formatter {
formatter := &Formatter{
debug: log.New(os.Stdout, "", log.LstdFlags),
}
return formatter
}
// Format formats swag comments in contents. It uses fileName to report errors
// that happen during parsing of contents.
func (f *Formatter) Format(fileName string, contents []byte) ([]byte, error) {
fileSet := token.NewFileSet()
ast, err := goparser.ParseFile(fileSet, fileName, contents, goparser.ParseComments)
if err != nil {
return nil, err
}
// Formatting changes are described as an edit list of byte range
// replacements. We make these content-level edits directly rather than
// changing the AST nodes and writing those out (via [go/printer] or
// [go/format]) so that we only change the formatting of Swag attribute
// comments. This won't touch the formatting of any other comments, or of
// functions, etc.
maxEdits := 0
for _, comment := range ast.Comments {
maxEdits += len(comment.List)
}
edits := make(edits, 0, maxEdits)
for _, comment := range ast.Comments {
formatFuncDoc(fileSet, comment.List, &edits)
}
formatted, err := imports.Process(fileName, edits.apply(contents), nil)
if err != nil {
return nil, err
}
return formatted, nil
}
type edit struct {
begin int
end int
replacement []byte
}
type edits []edit
func (edits edits) apply(contents []byte) []byte {
// Apply the edits with the highest offset first, so that earlier edits
// don't affect the offsets of later edits.
sort.Slice(edits, func(i, j int) bool {
return edits[i].begin > edits[j].begin
})
for _, edit := range edits {
prefix := contents[:edit.begin]
suffix := contents[edit.end:]
contents = append(prefix, append(edit.replacement, suffix...)...)
}
return contents
}
// formatFuncDoc reformats the comment lines in commentList, and appends any
// changes to the edit list.
func formatFuncDoc(fileSet *token.FileSet, commentList []*ast.Comment, edits *edits) {
// Building the edit list to format a comment block is a two-step process.
// First, we iterate over each comment line looking for Swag attributes. In
// each one we find, we replace alignment whitespace with a tab character,
// then write the result into a tab writer.
linesToComments := make(map[int]int, len(commentList))
buffer := &bytes.Buffer{}
w := tabwriter.NewWriter(buffer, 1, 4, 1, '\t', 0)
for commentIndex, comment := range commentList {
text := comment.Text
if attr, body, found := swagComment(text); found {
formatted := "//\t" + attr
if body != "" {
formatted += "\t" + splitComment2(attr, body)
}
_, _ = fmt.Fprintln(w, formatted)
linesToComments[len(linesToComments)] = commentIndex
}
}
// Once we've loaded all of the comment lines to be aligned into the tab
// writer, flushing it causes the aligned text to be written out to the
// backing buffer.
_ = w.Flush()
// Now the second step: we iterate over the aligned comment lines that were
// written into the backing buffer, pair each one up to its original
// comment line, and use the combination to describe the edit that needs to
// be made to the original input.
formattedComments := bytes.Split(buffer.Bytes(), []byte("\n"))
for lineIndex, commentIndex := range linesToComments {
comment := commentList[commentIndex]
*edits = append(*edits, edit{
begin: fileSet.Position(comment.Pos()).Offset,
end: fileSet.Position(comment.End()).Offset,
replacement: formattedComments[lineIndex],
})
}
}
func splitComment2(attr, body string) string {
if specialTagForSplit[strings.ToLower(attr)] {
for i := 0; i < len(body); i++ {
if skipEnd, ok := skipChar[body[i]]; ok {
skipStart, n := body[i], 1
for i++; i < len(body); i++ {
if skipStart != skipEnd && body[i] == skipStart {
n++
} else if body[i] == skipEnd {
n--
if n == 0 {
break
}
}
}
} else if body[i] == ' ' || body[i] == '\t' {
j := i
for ; j < len(body) && (body[j] == ' ' || body[j] == '\t'); 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
}

448
vendor/github.com/swaggo/swag/generics.go generated vendored Normal file
View File

@@ -0,0 +1,448 @@
//go:build go1.18
// +build go1.18
package swag
import (
"errors"
"fmt"
"go/ast"
"strings"
"unicode"
"github.com/go-openapi/spec"
)
type genericTypeSpec struct {
TypeSpec *TypeSpecDef
Name string
}
type formalParamType struct {
Name string
Type string
}
func (t *genericTypeSpec) TypeName() string {
if t.TypeSpec != nil {
return t.TypeSpec.TypeName()
}
return t.Name
}
func normalizeGenericTypeName(name string) string {
return strings.Replace(name, ".", "_", -1)
}
func (pkgDefs *PackagesDefinitions) getTypeFromGenericParam(genericParam string, file *ast.File) (typeSpecDef *TypeSpecDef) {
if strings.HasPrefix(genericParam, "[]") {
typeSpecDef = pkgDefs.getTypeFromGenericParam(genericParam[2:], file)
if typeSpecDef == nil {
return nil
}
var expr ast.Expr
switch typeSpecDef.TypeSpec.Type.(type) {
case *ast.ArrayType, *ast.MapType:
expr = typeSpecDef.TypeSpec.Type
default:
name := typeSpecDef.TypeName()
expr = ast.NewIdent(name)
if _, ok := pkgDefs.uniqueDefinitions[name]; !ok {
pkgDefs.uniqueDefinitions[name] = typeSpecDef
}
}
return &TypeSpecDef{
TypeSpec: &ast.TypeSpec{
Name: ast.NewIdent(string(IgnoreNameOverridePrefix) + "array_" + typeSpecDef.TypeName()),
Type: &ast.ArrayType{
Elt: expr,
},
},
Enums: typeSpecDef.Enums,
PkgPath: typeSpecDef.PkgPath,
ParentSpec: typeSpecDef.ParentSpec,
SchemaName: "array_" + typeSpecDef.SchemaName,
NotUnique: false,
}
}
if strings.HasPrefix(genericParam, "map[") {
parts := strings.SplitN(genericParam[4:], "]", 2)
if len(parts) != 2 {
return nil
}
typeSpecDef = pkgDefs.getTypeFromGenericParam(parts[1], file)
if typeSpecDef == nil {
return nil
}
var expr ast.Expr
switch typeSpecDef.TypeSpec.Type.(type) {
case *ast.ArrayType, *ast.MapType:
expr = typeSpecDef.TypeSpec.Type
default:
name := typeSpecDef.TypeName()
expr = ast.NewIdent(name)
if _, ok := pkgDefs.uniqueDefinitions[name]; !ok {
pkgDefs.uniqueDefinitions[name] = typeSpecDef
}
}
return &TypeSpecDef{
TypeSpec: &ast.TypeSpec{
Name: ast.NewIdent(string(IgnoreNameOverridePrefix) + "map_" + parts[0] + "_" + typeSpecDef.TypeName()),
Type: &ast.MapType{
Key: ast.NewIdent(parts[0]), //assume key is string or integer
Value: expr,
},
},
Enums: typeSpecDef.Enums,
PkgPath: typeSpecDef.PkgPath,
ParentSpec: typeSpecDef.ParentSpec,
SchemaName: "map_" + parts[0] + "_" + typeSpecDef.SchemaName,
NotUnique: false,
}
}
if IsGolangPrimitiveType(genericParam) {
return &TypeSpecDef{
TypeSpec: &ast.TypeSpec{
Name: ast.NewIdent(genericParam),
Type: ast.NewIdent(genericParam),
},
SchemaName: genericParam,
}
}
return pkgDefs.FindTypeSpec(genericParam, file)
}
func (pkgDefs *PackagesDefinitions) parametrizeGenericType(file *ast.File, original *TypeSpecDef, fullGenericForm string) *TypeSpecDef {
if original == nil || original.TypeSpec.TypeParams == nil || len(original.TypeSpec.TypeParams.List) == 0 {
return original
}
name, genericParams := splitGenericsTypeName(fullGenericForm)
if genericParams == nil {
return nil
}
//generic[x,y any,z any] considered, TODO what if the type is not `any`, but a concrete one, such as `int32|int64` or an certain interface{}
var formals []formalParamType
for _, field := range original.TypeSpec.TypeParams.List {
for _, ident := range field.Names {
formal := formalParamType{Name: ident.Name}
if ident, ok := field.Type.(*ast.Ident); ok {
formal.Type = ident.Name
}
formals = append(formals, formal)
}
}
if len(genericParams) != len(formals) {
return nil
}
genericParamTypeDefs := map[string]*genericTypeSpec{}
for i, genericParam := range genericParams {
var typeDef *TypeSpecDef
if !IsGolangPrimitiveType(genericParam) {
typeDef = pkgDefs.getTypeFromGenericParam(genericParam, file)
if typeDef != nil {
genericParam = typeDef.TypeName()
if _, ok := pkgDefs.uniqueDefinitions[genericParam]; !ok {
pkgDefs.uniqueDefinitions[genericParam] = typeDef
}
}
}
genericParamTypeDefs[formals[i].Name] = &genericTypeSpec{
TypeSpec: typeDef,
Name: genericParam,
}
}
name = fmt.Sprintf("%s%s-", string(IgnoreNameOverridePrefix), original.TypeName())
schemaName := fmt.Sprintf("%s-", original.SchemaName)
var nameParts []string
var schemaNameParts []string
for _, def := range formals {
if specDef, ok := genericParamTypeDefs[def.Name]; ok {
nameParts = append(nameParts, specDef.Name)
schemaNamePart := specDef.Name
if specDef.TypeSpec != nil {
schemaNamePart = specDef.TypeSpec.SchemaName
}
schemaNameParts = append(schemaNameParts, schemaNamePart)
}
}
name += normalizeGenericTypeName(strings.Join(nameParts, "-"))
schemaName += normalizeGenericTypeName(strings.Join(schemaNameParts, "-"))
if typeSpec, ok := pkgDefs.uniqueDefinitions[name]; ok {
return typeSpec
}
parametrizedTypeSpec := &TypeSpecDef{
File: original.File,
PkgPath: original.PkgPath,
TypeSpec: &ast.TypeSpec{
Name: &ast.Ident{
Name: name,
NamePos: original.TypeSpec.Name.NamePos,
Obj: original.TypeSpec.Name.Obj,
},
Doc: original.TypeSpec.Doc,
Assign: original.TypeSpec.Assign,
},
SchemaName: schemaName,
}
pkgDefs.uniqueDefinitions[name] = parametrizedTypeSpec
parametrizedTypeSpec.TypeSpec.Type = pkgDefs.resolveGenericType(original.File, original.TypeSpec.Type, genericParamTypeDefs)
return parametrizedTypeSpec
}
// splitGenericsTypeName splits a generic struct name in his parts
func splitGenericsTypeName(fullGenericForm string) (string, []string) {
//remove all spaces character
fullGenericForm = strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, fullGenericForm)
// split only at the first '[' and remove the last ']'
if fullGenericForm[len(fullGenericForm)-1] != ']' {
return "", nil
}
genericParams := strings.SplitN(fullGenericForm[:len(fullGenericForm)-1], "[", 2)
if len(genericParams) == 1 {
return "", nil
}
// generic type name
genericTypeName := genericParams[0]
depth := 0
genericParams = strings.FieldsFunc(genericParams[1], func(r rune) bool {
if r == '[' {
depth++
} else if r == ']' {
depth--
} else if r == ',' && depth == 0 {
return true
}
return false
})
if depth != 0 {
return "", nil
}
return genericTypeName, genericParams
}
func (pkgDefs *PackagesDefinitions) getParametrizedType(genTypeSpec *genericTypeSpec) ast.Expr {
if genTypeSpec.TypeSpec != nil && strings.Contains(genTypeSpec.Name, ".") {
parts := strings.SplitN(genTypeSpec.Name, ".", 2)
return &ast.SelectorExpr{
X: &ast.Ident{Name: parts[0]},
Sel: &ast.Ident{Name: parts[1]},
}
}
//a primitive type name or a type name in current package
return &ast.Ident{Name: genTypeSpec.Name}
}
func (pkgDefs *PackagesDefinitions) resolveGenericType(file *ast.File, expr ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) ast.Expr {
switch astExpr := expr.(type) {
case *ast.Ident:
if genTypeSpec, ok := genericParamTypeDefs[astExpr.Name]; ok {
return pkgDefs.getParametrizedType(genTypeSpec)
}
case *ast.ArrayType:
return &ast.ArrayType{
Elt: pkgDefs.resolveGenericType(file, astExpr.Elt, genericParamTypeDefs),
Len: astExpr.Len,
Lbrack: astExpr.Lbrack,
}
case *ast.MapType:
return &ast.MapType{
Map: astExpr.Map,
Key: pkgDefs.resolveGenericType(file, astExpr.Key, genericParamTypeDefs),
Value: pkgDefs.resolveGenericType(file, astExpr.Value, genericParamTypeDefs),
}
case *ast.StarExpr:
return &ast.StarExpr{
Star: astExpr.Star,
X: pkgDefs.resolveGenericType(file, astExpr.X, genericParamTypeDefs),
}
case *ast.IndexExpr, *ast.IndexListExpr:
fullGenericName, _ := getGenericFieldType(file, expr, genericParamTypeDefs)
typeDef := pkgDefs.FindTypeSpec(fullGenericName, file)
if typeDef != nil {
return typeDef.TypeSpec.Name
}
case *ast.StructType:
newStructTypeDef := &ast.StructType{
Struct: astExpr.Struct,
Incomplete: astExpr.Incomplete,
Fields: &ast.FieldList{
Opening: astExpr.Fields.Opening,
Closing: astExpr.Fields.Closing,
},
}
for _, field := range astExpr.Fields.List {
newField := &ast.Field{
Type: field.Type,
Doc: field.Doc,
Names: field.Names,
Tag: field.Tag,
Comment: field.Comment,
}
newField.Type = pkgDefs.resolveGenericType(file, field.Type, genericParamTypeDefs)
newStructTypeDef.Fields.List = append(newStructTypeDef.Fields.List, newField)
}
return newStructTypeDef
}
return expr
}
func getExtendedGenericFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) (string, error) {
switch fieldType := field.(type) {
case *ast.ArrayType:
fieldName, err := getExtendedGenericFieldType(file, fieldType.Elt, genericParamTypeDefs)
return "[]" + fieldName, err
case *ast.StarExpr:
return getExtendedGenericFieldType(file, fieldType.X, genericParamTypeDefs)
case *ast.Ident:
if genericParamTypeDefs != nil {
if typeSpec, ok := genericParamTypeDefs[fieldType.Name]; ok {
return typeSpec.Name, nil
}
}
if fieldType.Obj == nil {
return fieldType.Name, nil
}
tSpec := &TypeSpecDef{
File: file,
TypeSpec: fieldType.Obj.Decl.(*ast.TypeSpec),
PkgPath: file.Name.Name,
}
return tSpec.TypeName(), nil
default:
return getFieldType(file, field, genericParamTypeDefs)
}
}
func getGenericFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) (string, error) {
var fullName string
var baseName string
var err error
switch fieldType := field.(type) {
case *ast.IndexListExpr:
baseName, err = getGenericTypeName(file, fieldType.X)
if err != nil {
return "", err
}
fullName = baseName + "["
for _, index := range fieldType.Indices {
fieldName, err := getExtendedGenericFieldType(file, index, genericParamTypeDefs)
if err != nil {
return "", err
}
fullName += fieldName + ","
}
fullName = strings.TrimRight(fullName, ",") + "]"
case *ast.IndexExpr:
baseName, err = getGenericTypeName(file, fieldType.X)
if err != nil {
return "", err
}
indexName, err := getExtendedGenericFieldType(file, fieldType.Index, genericParamTypeDefs)
if err != nil {
return "", err
}
fullName = fmt.Sprintf("%s[%s]", baseName, indexName)
}
if fullName == "" {
return "", fmt.Errorf("unknown field type %#v", field)
}
var packageName string
if !strings.Contains(baseName, ".") {
if file.Name == nil {
return "", errors.New("file name is nil")
}
packageName, _ = getFieldType(file, file.Name, genericParamTypeDefs)
}
return strings.TrimLeft(fmt.Sprintf("%s.%s", packageName, fullName), "."), nil
}
func getGenericTypeName(file *ast.File, field ast.Expr) (string, error) {
switch fieldType := field.(type) {
case *ast.Ident:
if fieldType.Obj == nil {
return fieldType.Name, nil
}
tSpec := &TypeSpecDef{
File: file,
TypeSpec: fieldType.Obj.Decl.(*ast.TypeSpec),
PkgPath: file.Name.Name,
}
return tSpec.TypeName(), nil
case *ast.ArrayType:
tSpec := &TypeSpecDef{
File: file,
TypeSpec: fieldType.Elt.(*ast.Ident).Obj.Decl.(*ast.TypeSpec),
PkgPath: file.Name.Name,
}
return tSpec.TypeName(), nil
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", fieldType.X.(*ast.Ident).Name, fieldType.Sel.Name), nil
}
return "", fmt.Errorf("unknown type %#v", field)
}
func (parser *Parser) parseGenericTypeExpr(file *ast.File, typeExpr ast.Expr) (*spec.Schema, error) {
switch expr := typeExpr.(type) {
// suppress debug messages for these types
case *ast.InterfaceType:
case *ast.StructType:
case *ast.Ident:
case *ast.StarExpr:
case *ast.SelectorExpr:
case *ast.ArrayType:
case *ast.MapType:
case *ast.FuncType:
case *ast.IndexExpr, *ast.IndexListExpr:
name, err := getExtendedGenericFieldType(file, expr, nil)
if err == nil {
if schema, err := parser.getTypeSchema(name, file, false); err == nil {
return schema, nil
}
}
parser.debug.Printf("Type definition of type '%T' is not supported yet. Using 'object' instead. (%s)\n", typeExpr, err)
default:
parser.debug.Printf("Type definition of type '%T' is not supported yet. Using 'object' instead.\n", typeExpr)
}
return PrimitiveSchema(OBJECT), nil
}

78
vendor/github.com/swaggo/swag/golist.go generated vendored Normal file
View File

@@ -0,0 +1,78 @@
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 (finalErr != nil) && (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, parseFlag ParseFlag) error {
ignoreInternal := pkg.Goroot && !parser.ParseInternal
if ignoreInternal { // ignored internal
return nil
}
if parser.skipPackageByPrefix(pkg.ImportPath) {
return nil // ignored by user-defined package path prefixes
}
srcDir := pkg.Dir
var err error
for i := range pkg.GoFiles {
err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.GoFiles[i]), nil, parseFlag)
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, parseFlag)
if err != nil {
return err
}
}
return nil
}

21
vendor/github.com/swaggo/swag/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Eason Lin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1255
vendor/github.com/swaggo/swag/operation.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

187
vendor/github.com/swaggo/swag/package.go generated vendored Normal file
View File

@@ -0,0 +1,187 @@
package swag
import (
"go/ast"
"go/token"
"reflect"
"strconv"
"strings"
)
// PackageDefinitions files and definition in a package.
type PackageDefinitions struct {
// files in this package, map key is file's relative path starting package path
Files map[string]*ast.File
// definitions in this package, map key is typeName
TypeDefinitions map[string]*TypeSpecDef
// const variables in this package, map key is the name
ConstTable map[string]*ConstVariable
// const variables in order in this package
OrderedConst []*ConstVariable
// package name
Name string
// package path
Path string
}
// ConstVariableGlobalEvaluator an interface used to evaluate enums across packages
type ConstVariableGlobalEvaluator interface {
EvaluateConstValue(pkg *PackageDefinitions, cv *ConstVariable, recursiveStack map[string]struct{}) (interface{}, ast.Expr)
EvaluateConstValueByName(file *ast.File, pkgPath, constVariableName string, recursiveStack map[string]struct{}) (interface{}, ast.Expr)
FindTypeSpec(typeName string, file *ast.File) *TypeSpecDef
}
// NewPackageDefinitions new a PackageDefinitions object
func NewPackageDefinitions(name, pkgPath string) *PackageDefinitions {
return &PackageDefinitions{
Name: name,
Path: pkgPath,
Files: make(map[string]*ast.File),
TypeDefinitions: make(map[string]*TypeSpecDef),
ConstTable: make(map[string]*ConstVariable),
}
}
// AddFile add a file
func (pkg *PackageDefinitions) AddFile(pkgPath string, file *ast.File) *PackageDefinitions {
pkg.Files[pkgPath] = file
return pkg
}
// AddTypeSpec add a type spec.
func (pkg *PackageDefinitions) AddTypeSpec(name string, typeSpec *TypeSpecDef) *PackageDefinitions {
pkg.TypeDefinitions[name] = typeSpec
return pkg
}
// AddConst add a const variable.
func (pkg *PackageDefinitions) AddConst(astFile *ast.File, valueSpec *ast.ValueSpec) *PackageDefinitions {
for i := 0; i < len(valueSpec.Names) && i < len(valueSpec.Values); i++ {
variable := &ConstVariable{
Name: valueSpec.Names[i],
Type: valueSpec.Type,
Value: valueSpec.Values[i],
Comment: valueSpec.Comment,
File: astFile,
}
pkg.ConstTable[valueSpec.Names[i].Name] = variable
pkg.OrderedConst = append(pkg.OrderedConst, variable)
}
return pkg
}
func (pkg *PackageDefinitions) evaluateConstValue(file *ast.File, iota int, expr ast.Expr, globalEvaluator ConstVariableGlobalEvaluator, recursiveStack map[string]struct{}) (interface{}, ast.Expr) {
switch valueExpr := expr.(type) {
case *ast.Ident:
if valueExpr.Name == "iota" {
return iota, nil
}
if pkg.ConstTable != nil {
if cv, ok := pkg.ConstTable[valueExpr.Name]; ok {
return globalEvaluator.EvaluateConstValue(pkg, cv, recursiveStack)
}
}
case *ast.SelectorExpr:
pkgIdent, ok := valueExpr.X.(*ast.Ident)
if !ok {
return nil, nil
}
return globalEvaluator.EvaluateConstValueByName(file, pkgIdent.Name, valueExpr.Sel.Name, recursiveStack)
case *ast.BasicLit:
switch valueExpr.Kind {
case token.INT:
// handle underscored number, such as 1_000_000
if strings.ContainsRune(valueExpr.Value, '_') {
valueExpr.Value = strings.Replace(valueExpr.Value, "_", "", -1)
}
if len(valueExpr.Value) >= 2 && valueExpr.Value[0] == '0' {
var start, base = 2, 8
switch valueExpr.Value[1] {
case 'x', 'X':
//hex
base = 16
case 'b', 'B':
//binary
base = 2
default:
//octet
start = 1
}
if x, err := strconv.ParseInt(valueExpr.Value[start:], base, 64); err == nil {
return int(x), nil
} else if x, err := strconv.ParseUint(valueExpr.Value[start:], base, 64); err == nil {
return x, nil
} else {
panic(err)
}
}
//a basic literal integer is int type in default, or must have an explicit converting type in front
if x, err := strconv.ParseInt(valueExpr.Value, 10, 64); err == nil {
return int(x), nil
} else if x, err := strconv.ParseUint(valueExpr.Value, 10, 64); err == nil {
return x, nil
} else {
panic(err)
}
case token.STRING:
if valueExpr.Value[0] == '`' {
return valueExpr.Value[1 : len(valueExpr.Value)-1], nil
}
return EvaluateEscapedString(valueExpr.Value[1 : len(valueExpr.Value)-1]), nil
case token.CHAR:
return EvaluateEscapedChar(valueExpr.Value[1 : len(valueExpr.Value)-1]), nil
}
case *ast.UnaryExpr:
x, evalType := pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack)
if x == nil {
return x, evalType
}
return EvaluateUnary(x, valueExpr.Op, evalType)
case *ast.BinaryExpr:
x, evalTypex := pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack)
y, evalTypey := pkg.evaluateConstValue(file, iota, valueExpr.Y, globalEvaluator, recursiveStack)
if x == nil || y == nil {
return nil, nil
}
return EvaluateBinary(x, y, valueExpr.Op, evalTypex, evalTypey)
case *ast.ParenExpr:
return pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack)
case *ast.CallExpr:
//data conversion
if len(valueExpr.Args) != 1 {
return nil, nil
}
arg := valueExpr.Args[0]
if ident, ok := valueExpr.Fun.(*ast.Ident); ok {
name := ident.Name
if name == "uintptr" {
name = "uint"
}
value, _ := pkg.evaluateConstValue(file, iota, arg, globalEvaluator, recursiveStack)
if IsGolangPrimitiveType(name) {
value = EvaluateDataConversion(value, name)
return value, nil
} else if name == "len" {
return reflect.ValueOf(value).Len(), nil
}
typeDef := globalEvaluator.FindTypeSpec(name, file)
if typeDef == nil {
return nil, nil
}
return value, valueExpr.Fun
} else if selector, ok := valueExpr.Fun.(*ast.SelectorExpr); ok {
typeDef := globalEvaluator.FindTypeSpec(fullTypeName(selector.X.(*ast.Ident).Name, selector.Sel.Name), file)
if typeDef == nil {
return nil, nil
}
return arg, typeDef.TypeSpec.Type
}
}
return nil, nil
}

607
vendor/github.com/swaggo/swag/packages.go generated vendored Normal file
View File

@@ -0,0 +1,607 @@
package swag
import (
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"golang.org/x/tools/go/loader"
)
// PackagesDefinitions map[package import path]*PackageDefinitions.
type PackagesDefinitions struct {
files map[*ast.File]*AstFileInfo
packages map[string]*PackageDefinitions
uniqueDefinitions map[string]*TypeSpecDef
parseDependency ParseFlag
debug Debugger
}
// NewPackagesDefinitions create object PackagesDefinitions.
func NewPackagesDefinitions() *PackagesDefinitions {
return &PackagesDefinitions{
files: make(map[*ast.File]*AstFileInfo),
packages: make(map[string]*PackageDefinitions),
uniqueDefinitions: make(map[string]*TypeSpecDef),
}
}
// ParseFile parse a source file.
func (pkgDefs *PackagesDefinitions) ParseFile(packageDir, path string, src interface{}, flag ParseFlag) error {
// positions are relative to FileSet
fileSet := token.NewFileSet()
astFile, err := goparser.ParseFile(fileSet, path, src, goparser.ParseComments)
if err != nil {
return fmt.Errorf("failed to parse file %s, error:%+v", path, err)
}
return pkgDefs.collectAstFile(fileSet, packageDir, path, astFile, flag)
}
// collectAstFile collect ast.file.
func (pkgDefs *PackagesDefinitions) collectAstFile(fileSet *token.FileSet, packageDir, path string, astFile *ast.File, flag ParseFlag) error {
if pkgDefs.files == nil {
pkgDefs.files = make(map[*ast.File]*AstFileInfo)
}
if pkgDefs.packages == nil {
pkgDefs.packages = make(map[string]*PackageDefinitions)
}
// return without storing the file if we lack a packageDir
if packageDir == "" {
return nil
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
dependency, ok := pkgDefs.packages[packageDir]
if ok {
// return without storing the file if it already exists
_, exists := dependency.Files[path]
if exists {
return nil
}
dependency.Files[path] = astFile
} else {
pkgDefs.packages[packageDir] = NewPackageDefinitions(astFile.Name.Name, packageDir).AddFile(path, astFile)
}
pkgDefs.files[astFile] = &AstFileInfo{
FileSet: fileSet,
File: astFile,
Path: path,
PackagePath: packageDir,
ParseFlag: flag,
}
return nil
}
// RangeFiles for range the collection of ast.File in alphabetic order.
func (pkgDefs *PackagesDefinitions) RangeFiles(handle func(info *AstFileInfo) error) error {
sortedFiles := make([]*AstFileInfo, 0, len(pkgDefs.files))
for _, info := range pkgDefs.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") || (runtime.GOROOT() != "" && strings.HasPrefix(info.Path, runtime.GOROOT()+string(filepath.Separator))) {
continue
}
sortedFiles = append(sortedFiles, info)
}
sort.Slice(sortedFiles, func(i, j int) bool {
return strings.Compare(sortedFiles[i].Path, sortedFiles[j].Path) < 0
})
for _, info := range sortedFiles {
err := handle(info)
if err != nil {
return err
}
}
return nil
}
// ParseTypes parse types
// @Return parsed definitions.
func (pkgDefs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) {
parsedSchemas := make(map[*TypeSpecDef]*Schema)
for astFile, info := range pkgDefs.files {
pkgDefs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas)
pkgDefs.parseFunctionScopedTypesFromFile(astFile, info.PackagePath, parsedSchemas)
}
pkgDefs.removeAllNotUniqueTypes()
pkgDefs.evaluateAllConstVariables()
pkgDefs.collectConstEnums(parsedSchemas)
return parsedSchemas, nil
}
func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
for _, astDeclaration := range astFile.Decls {
generalDeclaration, ok := astDeclaration.(*ast.GenDecl)
if !ok {
continue
}
if generalDeclaration.Tok == token.TYPE {
for _, astSpec := range generalDeclaration.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
typeSpecDef := &TypeSpecDef{
PkgPath: packagePath,
File: astFile,
TypeSpec: typeSpec,
}
if idt, ok := typeSpec.Type.(*ast.Ident); ok && IsGolangPrimitiveType(idt.Name) && parsedSchemas != nil {
parsedSchemas[typeSpecDef] = &Schema{
PkgPath: typeSpecDef.PkgPath,
Name: astFile.Name.Name,
Schema: TransToValidPrimitiveSchema(idt.Name),
}
}
if pkgDefs.uniqueDefinitions == nil {
pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef)
}
fullName := typeSpecDef.TypeName()
anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName]
if ok {
if anotherTypeDef == nil {
typeSpecDef.NotUnique = true
fullName = typeSpecDef.TypeName()
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
} else if typeSpecDef.PkgPath != anotherTypeDef.PkgPath {
pkgDefs.uniqueDefinitions[fullName] = nil
anotherTypeDef.NotUnique = true
pkgDefs.uniqueDefinitions[anotherTypeDef.TypeName()] = anotherTypeDef
anotherTypeDef.SetSchemaName()
typeSpecDef.NotUnique = true
fullName = typeSpecDef.TypeName()
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
}
} else {
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
}
typeSpecDef.SetSchemaName()
if pkgDefs.packages[typeSpecDef.PkgPath] == nil {
pkgDefs.packages[typeSpecDef.PkgPath] = NewPackageDefinitions(astFile.Name.Name, typeSpecDef.PkgPath).AddTypeSpec(typeSpecDef.Name(), typeSpecDef)
} else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok {
pkgDefs.packages[typeSpecDef.PkgPath].AddTypeSpec(typeSpecDef.Name(), typeSpecDef)
}
}
}
} else if generalDeclaration.Tok == token.CONST {
// collect consts
pkgDefs.collectConstVariables(astFile, packagePath, generalDeclaration)
}
}
}
func (pkgDefs *PackagesDefinitions) parseFunctionScopedTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
for _, astDeclaration := range astFile.Decls {
funcDeclaration, ok := astDeclaration.(*ast.FuncDecl)
if ok && funcDeclaration.Body != nil {
functionScopedTypes := make(map[string]*TypeSpecDef)
for _, stmt := range funcDeclaration.Body.List {
if declStmt, ok := (stmt).(*ast.DeclStmt); ok {
if genDecl, ok := (declStmt.Decl).(*ast.GenDecl); ok && genDecl.Tok == token.TYPE {
for _, astSpec := range genDecl.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
typeSpecDef := &TypeSpecDef{
PkgPath: packagePath,
File: astFile,
TypeSpec: typeSpec,
ParentSpec: astDeclaration,
}
if idt, ok := typeSpec.Type.(*ast.Ident); ok && IsGolangPrimitiveType(idt.Name) && parsedSchemas != nil {
parsedSchemas[typeSpecDef] = &Schema{
PkgPath: typeSpecDef.PkgPath,
Name: astFile.Name.Name,
Schema: TransToValidPrimitiveSchema(idt.Name),
}
}
fullName := typeSpecDef.TypeName()
if structType, ok := typeSpecDef.TypeSpec.Type.(*ast.StructType); ok {
for _, field := range structType.Fields.List {
var idt *ast.Ident
var ok bool
switch field.Type.(type) {
case *ast.Ident:
idt, ok = field.Type.(*ast.Ident)
case *ast.StarExpr:
idt, ok = field.Type.(*ast.StarExpr).X.(*ast.Ident)
case *ast.ArrayType:
idt, ok = field.Type.(*ast.ArrayType).Elt.(*ast.Ident)
}
if ok && !IsGolangPrimitiveType(idt.Name) {
if functype, ok := functionScopedTypes[idt.Name]; ok {
idt.Name = functype.TypeName()
}
}
}
}
if pkgDefs.uniqueDefinitions == nil {
pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef)
}
anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName]
if ok {
if anotherTypeDef == nil {
typeSpecDef.NotUnique = true
fullName = typeSpecDef.TypeName()
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
} else if typeSpecDef.PkgPath != anotherTypeDef.PkgPath {
pkgDefs.uniqueDefinitions[fullName] = nil
anotherTypeDef.NotUnique = true
pkgDefs.uniqueDefinitions[anotherTypeDef.TypeName()] = anotherTypeDef
anotherTypeDef.SetSchemaName()
typeSpecDef.NotUnique = true
fullName = typeSpecDef.TypeName()
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
}
} else {
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
functionScopedTypes[typeSpec.Name.Name] = typeSpecDef
}
typeSpecDef.SetSchemaName()
if pkgDefs.packages[typeSpecDef.PkgPath] == nil {
pkgDefs.packages[typeSpecDef.PkgPath] = NewPackageDefinitions(astFile.Name.Name, typeSpecDef.PkgPath).AddTypeSpec(fullName, typeSpecDef)
} else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[fullName]; !ok {
pkgDefs.packages[typeSpecDef.PkgPath].AddTypeSpec(fullName, typeSpecDef)
}
}
}
}
}
}
}
}
}
func (pkgDefs *PackagesDefinitions) collectConstVariables(astFile *ast.File, packagePath string, generalDeclaration *ast.GenDecl) {
pkg, ok := pkgDefs.packages[packagePath]
if !ok {
pkg = NewPackageDefinitions(astFile.Name.Name, packagePath)
pkgDefs.packages[packagePath] = pkg
}
var lastValueSpec *ast.ValueSpec
for _, astSpec := range generalDeclaration.Specs {
valueSpec, ok := astSpec.(*ast.ValueSpec)
if !ok {
continue
}
if len(valueSpec.Names) == 1 && len(valueSpec.Values) == 1 {
lastValueSpec = valueSpec
} else if len(valueSpec.Names) == 1 && len(valueSpec.Values) == 0 && valueSpec.Type == nil && lastValueSpec != nil {
valueSpec.Type = lastValueSpec.Type
valueSpec.Values = lastValueSpec.Values
}
pkg.AddConst(astFile, valueSpec)
}
}
func (pkgDefs *PackagesDefinitions) evaluateAllConstVariables() {
for _, pkg := range pkgDefs.packages {
for _, constVar := range pkg.OrderedConst {
pkgDefs.EvaluateConstValue(pkg, constVar, nil)
}
}
}
// EvaluateConstValue evaluate a const variable.
func (pkgDefs *PackagesDefinitions) EvaluateConstValue(pkg *PackageDefinitions, cv *ConstVariable, recursiveStack map[string]struct{}) (interface{}, ast.Expr) {
if expr, ok := cv.Value.(ast.Expr); ok {
defer func() {
if err := recover(); err != nil {
if fi, ok := pkgDefs.files[cv.File]; ok {
pos := fi.FileSet.Position(cv.Name.NamePos)
pkgDefs.debug.Printf("warning: failed to evaluate const %s at %s:%d:%d, %v", cv.Name.Name, fi.Path, pos.Line, pos.Column, err)
}
}
}()
if recursiveStack == nil {
recursiveStack = make(map[string]struct{})
}
fullConstName := fullTypeName(pkg.Path, cv.Name.Name)
if _, ok = recursiveStack[fullConstName]; ok {
return nil, nil
}
recursiveStack[fullConstName] = struct{}{}
value, evalType := pkg.evaluateConstValue(cv.File, cv.Name.Obj.Data.(int), expr, pkgDefs, recursiveStack)
if cv.Type == nil && evalType != nil {
cv.Type = evalType
}
if value != nil {
cv.Value = value
}
return value, cv.Type
}
return cv.Value, cv.Type
}
// EvaluateConstValueByName evaluate a const variable by name.
func (pkgDefs *PackagesDefinitions) EvaluateConstValueByName(file *ast.File, pkgName, constVariableName string, recursiveStack map[string]struct{}) (interface{}, ast.Expr) {
matchedPkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports(pkgName, file)
for _, pkgPath := range matchedPkgPaths {
if pkg, ok := pkgDefs.packages[pkgPath]; ok {
if cv, ok := pkg.ConstTable[constVariableName]; ok {
return pkgDefs.EvaluateConstValue(pkg, cv, recursiveStack)
}
}
}
if pkgDefs.parseDependency > 0 {
for _, pkgPath := range externalPkgPaths {
if err := pkgDefs.loadExternalPackage(pkgPath); err == nil {
if pkg, ok := pkgDefs.packages[pkgPath]; ok {
if cv, ok := pkg.ConstTable[constVariableName]; ok {
return pkgDefs.EvaluateConstValue(pkg, cv, recursiveStack)
}
}
}
}
}
return nil, nil
}
func (pkgDefs *PackagesDefinitions) collectConstEnums(parsedSchemas map[*TypeSpecDef]*Schema) {
for _, pkg := range pkgDefs.packages {
for _, constVar := range pkg.OrderedConst {
if constVar.Type == nil {
continue
}
ident, ok := constVar.Type.(*ast.Ident)
if !ok || IsGolangPrimitiveType(ident.Name) {
continue
}
typeDef, ok := pkg.TypeDefinitions[ident.Name]
if !ok {
continue
}
// delete it from parsed schemas, and will parse it again
if _, ok = parsedSchemas[typeDef]; ok {
delete(parsedSchemas, typeDef)
}
if typeDef.Enums == nil {
typeDef.Enums = make([]EnumValue, 0)
}
name := constVar.VariableName()
if _, ok = constVar.Value.(ast.Expr); ok {
continue
}
enumValue := EnumValue{
key: name,
Value: constVar.Value,
Comment: commentWithoutNameOverride(constVar.Comment),
}
typeDef.Enums = append(typeDef.Enums, enumValue)
}
}
}
func (pkgDefs *PackagesDefinitions) removeAllNotUniqueTypes() {
for key, ud := range pkgDefs.uniqueDefinitions {
if ud == nil {
delete(pkgDefs.uniqueDefinitions, key)
}
}
}
func (pkgDefs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef {
if pkgDefs.packages == nil {
return nil
}
pd, found := pkgDefs.packages[pkgPath]
if found {
typeSpec, ok := pd.TypeDefinitions[typeName]
if ok {
return typeSpec
}
}
return nil
}
func (pkgDefs *PackagesDefinitions) loadExternalPackage(importPath string) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
conf := loader.Config{
ParserMode: goparser.ParseComments,
Cwd: cwd,
}
conf.Import(importPath)
loaderProgram, err := conf.Load()
if err != nil {
return err
}
for _, info := range loaderProgram.AllPackages {
pkgPath := strings.TrimPrefix(info.Pkg.Path(), "vendor/")
for _, astFile := range info.Files {
pkgDefs.parseTypesFromFile(astFile, pkgPath, nil)
}
}
return nil
}
// findPackagePathFromImports finds out the package path of a package via ranging imports of an ast.File
// @pkg the name of the target package
// @file current ast.File in which to search imports
// @return the package paths of a package of @pkg.
func (pkgDefs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File) (matchedPkgPaths, externalPkgPaths []string) {
if file == nil {
return
}
if strings.ContainsRune(pkg, '.') {
pkg = strings.Split(pkg, ".")[0]
}
matchLastPathPart := func(pkgPath string) bool {
paths := strings.Split(pkgPath, "/")
return paths[len(paths)-1] == pkg
}
// prior to match named package
for _, imp := range file.Imports {
path := strings.Trim(imp.Path.Value, `"`)
if imp.Name != nil {
if imp.Name.Name == pkg {
// if name match, break loop and return
_, ok := pkgDefs.packages[path]
if ok {
matchedPkgPaths = []string{path}
externalPkgPaths = nil
} else {
externalPkgPaths = []string{path}
matchedPkgPaths = nil
}
break
} else if imp.Name.Name == "_" && len(pkg) > 0 {
// for unused types
pd, ok := pkgDefs.packages[path]
if ok {
if pd.Name == pkg {
matchedPkgPaths = append(matchedPkgPaths, path)
}
} else if matchLastPathPart(path) {
externalPkgPaths = append(externalPkgPaths, path)
}
} else if imp.Name.Name == "." && len(pkg) == 0 {
_, ok := pkgDefs.packages[path]
if ok {
matchedPkgPaths = append(matchedPkgPaths, path)
} else if len(pkg) == 0 || matchLastPathPart(path) {
externalPkgPaths = append(externalPkgPaths, path)
}
}
} else if pkgDefs.packages != nil && len(pkg) > 0 {
pd, ok := pkgDefs.packages[path]
if ok {
if pd.Name == pkg {
matchedPkgPaths = append(matchedPkgPaths, path)
}
} else if matchLastPathPart(path) {
externalPkgPaths = append(externalPkgPaths, path)
}
}
}
if len(pkg) == 0 || file.Name.Name == pkg {
matchedPkgPaths = append(matchedPkgPaths, pkgDefs.files[file].PackagePath)
}
return
}
func (pkgDefs *PackagesDefinitions) findTypeSpecFromPackagePaths(matchedPkgPaths, externalPkgPaths []string, name string) (typeDef *TypeSpecDef) {
if pkgDefs.parseDependency > 0 {
for _, pkgPath := range externalPkgPaths {
if err := pkgDefs.loadExternalPackage(pkgPath); err == nil {
typeDef = pkgDefs.findTypeSpec(pkgPath, name)
if typeDef != nil {
return typeDef
}
}
}
}
for _, pkgPath := range matchedPkgPaths {
typeDef = pkgDefs.findTypeSpec(pkgPath, name)
if typeDef != nil {
return typeDef
}
}
return typeDef
}
// FindTypeSpec finds out TypeSpecDef of a type by typeName
// @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 (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File) *TypeSpecDef {
if IsGolangPrimitiveType(typeName) {
return nil
}
if file == nil { // for test
return pkgDefs.uniqueDefinitions[typeName]
}
parts := strings.Split(strings.Split(typeName, "[")[0], ".")
if len(parts) > 1 {
pkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports(parts[0], file)
if len(externalPkgPaths) == 0 || pkgDefs.parseDependency == ParseNone {
typeDef, ok := pkgDefs.uniqueDefinitions[typeName]
if ok {
return typeDef
}
}
typeDef := pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, parts[1])
return pkgDefs.parametrizeGenericType(file, typeDef, typeName)
}
typeDef, ok := pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)]
if ok {
return typeDef
}
name := parts[0]
typeDef, ok = pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, name)]
if !ok {
pkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports("", file)
typeDef = pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, name)
}
if typeDef != nil {
return pkgDefs.parametrizeGenericType(file, typeDef, typeName)
}
// in case that comment //@name renamed the type with a name without a dot
for k, v := range pkgDefs.uniqueDefinitions {
if v == nil {
pkgDefs.debug.Printf("%s TypeSpecDef is nil", k)
continue
}
if v.SchemaName == typeName {
return v
}
}
return nil
}

1991
vendor/github.com/swaggo/swag/parser.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

372
vendor/github.com/swaggo/swag/schema.go generated vendored Normal file
View File

@@ -0,0 +1,372 @@
package swag
import (
"errors"
"fmt"
"github.com/go-openapi/spec"
"go/ast"
"regexp"
"strings"
)
const (
// ARRAY represent a array value.
ARRAY = "array"
// OBJECT represent a object value.
OBJECT = "object"
// PRIMITIVE represent a primitive value.
PRIMITIVE = "primitive"
// BOOLEAN represent a boolean value.
BOOLEAN = "boolean"
// INTEGER represent a integer value.
INTEGER = "integer"
// NUMBER represent a number value.
NUMBER = "number"
// STRING represent a string value.
STRING = "string"
// FUNC represent a function value.
FUNC = "func"
// ERROR represent a error value.
ERROR = "error"
// INTERFACE represent a interface value.
INTERFACE = "interface{}"
// ANY represent a any value.
ANY = "any"
// NIL represent a empty value.
NIL = "nil"
// IgnoreNameOverridePrefix Prepend to model to avoid renaming based on comment.
IgnoreNameOverridePrefix = '$'
)
// CheckSchemaType checks if typeName is not a name of primitive type.
func CheckSchemaType(typeName string) error {
if !IsPrimitiveType(typeName) {
return fmt.Errorf("%s is not basic types", typeName)
}
return nil
}
// IsSimplePrimitiveType determine whether the type name is a simple primitive type.
func IsSimplePrimitiveType(typeName string) bool {
switch typeName {
case STRING, NUMBER, INTEGER, BOOLEAN:
return true
}
return false
}
// IsPrimitiveType determine whether the type name is a primitive type.
func IsPrimitiveType(typeName string) bool {
switch typeName {
case STRING, NUMBER, INTEGER, BOOLEAN, ARRAY, OBJECT, FUNC:
return true
}
return false
}
// IsInterfaceLike determines whether the swagger type name is an go named interface type like error type.
func IsInterfaceLike(typeName string) bool {
return typeName == ERROR || typeName == ANY
}
// IsNumericType determines whether the swagger type name is a numeric type.
func IsNumericType(typeName string) bool {
return typeName == INTEGER || typeName == NUMBER
}
// TransToValidPrimitiveSchema transfer golang basic type to swagger schema with format considered.
func TransToValidPrimitiveSchema(typeName string) *spec.Schema {
switch typeName {
case "int", "uint":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{INTEGER}}}
case "uint8", "int8", "uint16", "int16", "byte", "int32", "uint32", "rune":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{INTEGER}, Format: "int32"}}
case "uint64", "int64":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{INTEGER}, Format: "int64"}}
case "float32", "float64":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{NUMBER}, Format: typeName}}
case "bool":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{BOOLEAN}}}
case "string":
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{STRING}}}
}
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{typeName}}}
}
// TransToValidSchemeTypeWithFormat indicates type will transfer golang basic type to swagger supported type with format.
func TransToValidSchemeTypeWithFormat(typeName string) (string, string) {
switch typeName {
case "int", "uint":
return INTEGER, ""
case "uint8", "int8", "uint16", "int16", "byte", "int32", "uint32", "rune":
return INTEGER, "int32"
case "uint64", "int64":
return INTEGER, "int64"
case "float32", "float64":
return NUMBER, typeName
case "bool":
return BOOLEAN, ""
case "string":
return STRING, ""
}
return typeName, ""
}
// TransToValidSchemeType indicates type will transfer golang basic type to swagger supported type.
func TransToValidSchemeType(typeName string) string {
switch typeName {
case "uint", "int", "uint8", "int8", "uint16", "int16", "byte":
return INTEGER
case "uint32", "int32", "rune":
return INTEGER
case "uint64", "int64":
return INTEGER
case "float32", "float64":
return NUMBER
case "bool":
return BOOLEAN
case "string":
return STRING
}
return typeName
}
// IsGolangPrimitiveType determine whether the type name is a golang primitive type.
func IsGolangPrimitiveType(typeName string) bool {
switch typeName {
case "uint",
"int",
"uint8",
"int8",
"uint16",
"int16",
"byte",
"uint32",
"int32",
"rune",
"uint64",
"int64",
"float32",
"float64",
"bool",
"string":
return true
}
return false
}
// TransToValidCollectionFormat determine valid collection format.
func TransToValidCollectionFormat(format string) string {
switch format {
case "csv", "multi", "pipes", "tsv", "ssv":
return format
}
return ""
}
func ignoreNameOverride(name string) bool {
return len(name) != 0 && name[0] == IgnoreNameOverridePrefix
}
var overrideNameRegex = regexp.MustCompile(`(?i)^@name\s+(\S+)`)
func nameOverride(commentGroup *ast.CommentGroup) string {
if commentGroup == nil {
return ""
}
// get alias from comment '// @name '
for _, comment := range commentGroup.List {
trimmedComment := strings.TrimSpace(strings.TrimLeft(comment.Text, "/"))
texts := overrideNameRegex.FindStringSubmatch(trimmedComment)
if len(texts) > 1 {
return texts[1]
}
}
return ""
}
func commentWithoutNameOverride(commentGroup *ast.CommentGroup) string {
if commentGroup == nil {
return ""
}
commentBuilder := strings.Builder{}
for _, comment := range commentGroup.List {
commentText := comment.Text
commentText = strings.TrimPrefix(commentText, "//")
commentText = strings.TrimPrefix(commentText, "/*")
commentText = strings.TrimSuffix(commentText, "*/")
commentText = strings.TrimSpace(commentText)
commentText = overrideNameRegex.ReplaceAllString(commentText, "")
commentText = strings.TrimSpace(commentText)
commentBuilder.WriteString(commentText)
}
return commentBuilder.String()
}
// IsComplexSchema whether a schema is complex and should be a ref schema
func IsComplexSchema(schema *spec.Schema) bool {
// a enum type should be complex
if len(schema.Enum) > 0 {
return true
}
// a deep array type is complex, how to determine deep? here more than 2 ,for example: [][]object,[][][]int
if len(schema.Type) > 2 {
return true
}
//Object included, such as Object or []Object
for _, st := range schema.Type {
if st == OBJECT {
return true
}
}
return false
}
// IsRefSchema whether a schema is a reference schema.
func IsRefSchema(schema *spec.Schema) bool {
return schema.Ref.Ref.GetURL() != nil
}
// RefSchema build a reference schema.
func RefSchema(refType string) *spec.Schema {
return spec.RefSchema("#/definitions/" + refType)
}
// PrimitiveSchema build a primitive schema.
func PrimitiveSchema(refType string) *spec.Schema {
return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{refType}}}
}
// BuildCustomSchema build custom schema specified by tag swaggertype.
func BuildCustomSchema(types []string) (*spec.Schema, error) {
if len(types) == 0 {
return nil, nil
}
switch types[0] {
case PRIMITIVE:
if len(types) == 1 {
return nil, errors.New("need primitive type after primitive")
}
return BuildCustomSchema(types[1:])
case ARRAY:
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
}
return spec.ArrayProperty(schema), nil
case OBJECT:
if len(types) == 1 {
return PrimitiveSchema(types[0]), nil
}
schema, err := BuildCustomSchema(types[1:])
if err != nil {
return nil, err
}
return spec.MapProperty(schema), nil
default:
err := CheckSchemaType(types[0])
if err != nil {
return nil, err
}
return PrimitiveSchema(types[0]), nil
}
}
// MergeSchema merge schemas
func MergeSchema(dst *spec.Schema, src *spec.Schema) *spec.Schema {
if len(src.Type) > 0 {
dst.Type = src.Type
}
if len(src.Properties) > 0 {
dst.Properties = src.Properties
}
if src.Items != nil {
dst.Items = src.Items
}
if src.AdditionalProperties != nil {
dst.AdditionalProperties = src.AdditionalProperties
}
if len(src.Description) > 0 {
dst.Description = src.Description
}
if src.Nullable {
dst.Nullable = src.Nullable
}
if len(src.Format) > 0 {
dst.Format = src.Format
}
if src.Default != nil {
dst.Default = src.Default
}
if src.Example != nil {
dst.Example = src.Example
}
if len(src.Extensions) > 0 {
dst.Extensions = src.Extensions
}
if src.Maximum != nil {
dst.Maximum = src.Maximum
}
if src.Minimum != nil {
dst.Minimum = src.Minimum
}
if src.ExclusiveMaximum {
dst.ExclusiveMaximum = src.ExclusiveMaximum
}
if src.ExclusiveMinimum {
dst.ExclusiveMinimum = src.ExclusiveMinimum
}
if src.MaxLength != nil {
dst.MaxLength = src.MaxLength
}
if src.MinLength != nil {
dst.MinLength = src.MinLength
}
if len(src.Pattern) > 0 {
dst.Pattern = src.Pattern
}
if src.MaxItems != nil {
dst.MaxItems = src.MaxItems
}
if src.MinItems != nil {
dst.MinItems = src.MinItems
}
if src.UniqueItems {
dst.UniqueItems = src.UniqueItems
}
if src.MultipleOf != nil {
dst.MultipleOf = src.MultipleOf
}
if len(src.Enum) > 0 {
dst.Enum = src.Enum
}
if len(src.Extensions) > 0 {
dst.Extensions = src.Extensions
}
if len(src.ExtraProps) > 0 {
dst.ExtraProps = src.ExtraProps
}
return dst
}

64
vendor/github.com/swaggo/swag/spec.go generated vendored Normal file
View File

@@ -0,0 +1,64 @@
package swag
import (
"bytes"
"encoding/json"
"strings"
"text/template"
)
// Spec holds exported Swagger Info so clients can modify it.
type Spec struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
InfoInstanceName string
SwaggerTemplate string
LeftDelim string
RightDelim string
}
// ReadDoc parses SwaggerTemplate into swagger document.
func (i *Spec) ReadDoc() string {
i.Description = strings.ReplaceAll(i.Description, "\n", "\\n")
tpl := 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
var str = strings.ReplaceAll(v.(string), "\t", "\\t")
// replace " with \", and if that results in \\", replace that with \\\"
str = strings.ReplaceAll(str, "\"", "\\\"")
return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"")
},
})
if i.LeftDelim != "" && i.RightDelim != "" {
tpl = tpl.Delims(i.LeftDelim, i.RightDelim)
}
parsed, err := tpl.Parse(i.SwaggerTemplate)
if err != nil {
return i.SwaggerTemplate
}
var doc bytes.Buffer
if err = parsed.Execute(&doc, i); err != nil {
return i.SwaggerTemplate
}
return doc.String()
}
// InstanceName returns Spec instance name.
func (i *Spec) InstanceName() string {
return i.InfoInstanceName
}

72
vendor/github.com/swaggo/swag/swagger.go generated vendored Normal file
View File

@@ -0,0 +1,72 @@
package swag
import (
"errors"
"fmt"
"sync"
)
// Name is a unique name be used to register swag instance.
const Name = "swagger"
var (
swaggerMu sync.RWMutex
swags map[string]Swagger
)
// Swagger is an interface to read swagger document.
type Swagger interface {
ReadDoc() string
}
// Register registers swagger for given name.
func Register(name string, swagger Swagger) {
swaggerMu.Lock()
defer swaggerMu.Unlock()
if swagger == nil {
panic("swagger is nil")
}
if swags == nil {
swags = make(map[string]Swagger)
}
if _, ok := swags[name]; ok {
panic("Register called twice for swag: " + name)
}
swags[name] = swagger
}
// GetSwagger returns the swagger instance for given name.
// If not found, returns nil.
func GetSwagger(name string) Swagger {
swaggerMu.RLock()
defer swaggerMu.RUnlock()
return swags[name]
}
// ReadDoc reads swagger document. An optional name parameter can be passed to read a specific document.
// The default name is "swagger".
func ReadDoc(optionalName ...string) (string, error) {
swaggerMu.RLock()
defer swaggerMu.RUnlock()
if swags == nil {
return "", errors.New("no swag has yet been registered")
}
name := Name
if len(optionalName) != 0 && optionalName[0] != "" {
name = optionalName[0]
}
swag, ok := swags[name]
if !ok {
return "", fmt.Errorf("no swag named \"%s\" was registered", name)
}
return swag.ReadDoc(), nil
}

105
vendor/github.com/swaggo/swag/types.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package swag
import (
"go/ast"
"go/token"
"strings"
"github.com/go-openapi/spec"
)
// Schema parsed schema.
type Schema struct {
*spec.Schema //
PkgPath string // package import path used to rename Name of a definition int case of conflict
Name string // Name in definitions
}
// TypeSpecDef the whole information of a typeSpec.
type TypeSpecDef struct {
// ast file where TypeSpec is
File *ast.File
// the TypeSpec of this type definition
TypeSpec *ast.TypeSpec
Enums []EnumValue
// path of package starting from under ${GOPATH}/src or from module path in go.mod
PkgPath string
ParentSpec ast.Decl
SchemaName string
NotUnique bool
}
// Name the name of the typeSpec.
func (t *TypeSpecDef) Name() string {
if t.TypeSpec != nil && t.TypeSpec.Name != nil {
return t.TypeSpec.Name.Name
}
return ""
}
// TypeName the type name of the typeSpec.
func (t *TypeSpecDef) TypeName() string {
if ignoreNameOverride(t.TypeSpec.Name.Name) {
return t.TypeSpec.Name.Name[1:]
}
var names []string
if t.NotUnique {
pkgPath := strings.Map(func(r rune) rune {
if r == '\\' || r == '/' || r == '.' {
return '_'
}
return r
}, t.PkgPath)
names = append(names, pkgPath)
} else if t.File != nil {
names = append(names, t.File.Name.Name)
}
if parentFun, ok := (t.ParentSpec).(*ast.FuncDecl); ok && parentFun != nil {
names = append(names, parentFun.Name.Name)
}
names = append(names, t.TypeSpec.Name.Name)
return fullTypeName(names...)
}
// FullPath return the full path of the typeSpec.
func (t *TypeSpecDef) FullPath() string {
return t.PkgPath + "." + t.Name()
}
func (t *TypeSpecDef) Alias() string {
return nameOverride(t.TypeSpec.Comment)
}
func (t *TypeSpecDef) SetSchemaName() {
if alias := t.Alias(); alias != "" {
t.SchemaName = alias
return
}
t.SchemaName = t.TypeName()
}
// AstFileInfo information of an ast.File.
type AstFileInfo struct {
//FileSet the FileSet object which is used to parse this go source file
FileSet *token.FileSet
// File ast.File
File *ast.File
// Path the path of the ast.File
Path string
// PackagePath package import path of the ast.File
PackagePath string
// ParseFlag determine what to parse
ParseFlag ParseFlag
}

67
vendor/github.com/swaggo/swag/utils.go generated vendored Normal file
View File

@@ -0,0 +1,67 @@
package swag
import (
"strings"
"unicode"
)
// FieldsFunc split a string s by a func splitter into max n parts
func FieldsFunc(s string, f func(rune2 rune) bool, n int) []string {
// A span is used to record a slice of s of the form s[start:end].
// The start index is inclusive and the end index is exclusive.
type span struct {
start int
end int
}
spans := make([]span, 0, 32)
// Find the field start and end indices.
// Doing this in a separate pass (rather than slicing the string s
// and collecting the result substrings right away) is significantly
// more efficient, possibly due to cache effects.
start := -1 // valid span start if >= 0
for end, rune := range s {
if f(rune) {
if start >= 0 {
spans = append(spans, span{start, end})
// Set start to a negative value.
// Note: using -1 here consistently and reproducibly
// slows down this code by a several percent on amd64.
start = ^start
}
} else {
if start < 0 {
start = end
if n > 0 && len(spans)+1 >= n {
break
}
}
}
}
// Last field might end at EOF.
if start >= 0 {
spans = append(spans, span{start, len(s)})
}
// Create strings from recorded field indices.
a := make([]string, len(spans))
for i, span := range spans {
a[i] = s[span.start:span.end]
}
return a
}
// FieldsByAnySpace split a string s by any space character into max n parts
func FieldsByAnySpace(s string, n int) []string {
return FieldsFunc(s, unicode.IsSpace, n)
}
// AppendDescription appends a new string to the existing description, treating
// a trailing backslash as a line continuation.
func AppendDescription(current, addition string) string {
if strings.HasSuffix(current, "\\") {
return current[:len(current)-1] + addition
}
return current + "\n" + addition
}

4
vendor/github.com/swaggo/swag/version.go generated vendored Normal file
View File

@@ -0,0 +1,4 @@
package swag
// Version of swag.
const Version = "v1.16.4"