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()
}
选项类型默认描述
URLstring“doc.json”URL pointing to API definition
DocExpansionstring“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).
DeepLinkingbooltrueIf set to true, enables deep linking for tags and operations. See the Deep Linking documentation for more information.
DefaultModelsExpandDepthint1Default expansion depth for models (set to -1 completely hide the models).
InstanceNamestring“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).
PersistAuthotizationboolfalseIf set to true, it persists authorization data and it would not be lost on browser close/refresh.
posted @   南瓜头pumpkin  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示