gin集成Swagger-UI
gin 中间件使用 Swagger 2.0 自动生成 RESTFUL API 文档。
1. 安装Swagger
使用以下命令下载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. |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现