https://github.com/Mzihao/go-logistics
使用以下命令下载Swag for Go:
go get -u github.com/swaggo/swag/cmd/swag
在 Go 项目根路径运行Swag , Swag将解析注释并生成所需的文件和文件夹。
swag init
# 可加载外部包
swag init --parseDependency --
参数解释:
参数名 | 含义解释 |
---|---|
parseInternal | 解析内部依赖包,默认值: false |
parseDependency | 解析外部依赖包,默认值: false |
parseDepth | 解析依赖包深度,默认值:100 |
生成目录如下:
.
├── docs
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── go.mod
├── go.sum
└── main.go
使用以下命令下载gin-swagger:
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
代码中引入:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
一个完整的例子:
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")
}
在http://localhost:8080/swagger/index.html 中查看
您可以使用不同的配置选项来配置 Swagger
func main() {
r := gin.New()
ginSwagger.WrapHandler(swaggerFiles.Handler,
ginSwagger.URL("http://localhost:8080/swagger/doc.json"),
ginSwagger.DefaultModelsExpandDepth(-1))
r.Run()
}
选项 | 类型 | 默认 | 描述 |
---|---|---|---|
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). |
PersistAuthotization | bool | false | If set to true, it persists authorization data and it would not be lost on browser close/refresh. |