• GO语言gin框架实战-03-swagger和接口文档


    1. swag 安装

    2. main函数注释

    - 简单示例

    // @title crow-logger
    // @version 1.0
    // @termsOfService http://10.10.xxx.65
    // @contact.name 刘炜
    // @contact.url http://10.10.xxx.65
    // @contact.email liuwei-cto@xxx.com.cn
    // @BasePath /
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 以后这些信息会出现在swagger页面头
      在这里插入图片描述

    - 官方完整示例

    //  @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
    
    //  @securityDefinitions.apikey  ApiKeyAuth
    //  @in                          header
    //  @name                        Authorization
    //  @description                 Description for what is this security definition being used
    
    //  @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
    
    //  @securitydefinitions.oauth2.implicit  OAuth2Implicit
    //  @authorizationUrl                     https://example.com/oauth/authorize
    //  @scope.write                          Grants write access
    //  @scope.admin                          Grants read and write access to administrative information
    
    //  @securitydefinitions.oauth2.password  OAuth2Password
    //  @tokenUrl                             https://example.com/oauth/token
    //  @scope.read                           Grants read access
    //  @scope.write                          Grants write access
    //  @scope.admin                          Grants read and write access to administrative information
    
    //  @securitydefinitions.oauth2.accessCode  OAuth2AccessCode
    //  @tokenUrl                               https://example.com/oauth/token
    //  @authorizationUrl                       https://example.com/oauth/authorize
    //  @scope.admin                            Grants read and write access to administrative information
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    - 官方说明

    注释说明示例
    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
    termsOfServiceAPI的服务条款。// @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
    acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。// @accept json
    produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。// @produce json
    query.collection.format请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。// @query.collection.format multi
    schemes用空格分隔的请求的传输协议。// @schemes http https
    x-name扩展的键必须以x-开头,并且只能使用json值// @x-example-key {“key”: “value”}

    3. 路由设置

    • 示例

    gin路由中添加一条路由配置:

    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    
    • 1
    • 完整示例

    注意:_ "crow-logger/docs" 这条必须引用,不然访问swagger的时候回找不到docs文件。

    • 后边 swagger init的时候会将生成的文件放入项目根下 docs 目录。
    • crow-logger 是我的项目名,你需要替换成自己的。
    import (
    	_ "crow-logger/docs"
    	"github.com/gin-gonic/gin"
    	ginSwagger "github.com/swaggo/gin-swagger"
    	"github.com/swaggo/gin-swagger/swaggerFiles"
    )
    
    func ServerWebsocket()  {
    	r := gin.Default()
    	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    	
    	groupV1 := r.Group("/api/v1")
    	{
    		groupV1.GET("/ping", Ping)
    		groupV1.GET("/version", Version)
    	}
    	deployment := r.Group("/api/v1/logger")
    	{
    		deployment.GET("/",GetLog)
    		deployment.GET("/file",DownLog)
    	}
    	r.Run(":1911")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    4. 接口的注释

    4.1 GET

    - query模式

    • 代码
    // SelectPrjs 获取项目信息
    // @Summary 获取项目信息
    // @Description 获取项目信息
    // @Tags 项目管理
    // @Param prj_id query string false "项目Id"
    // @Param prj_nbr query string false "项目编号"
    // @Param prj_nm query string false "项目名称"
    // @Param page_num query string false "页数"
    // @Param page_size query string false "每页行数"
    // @Success 200 {object} response.Response{data=apimodels.ProjectListResponse} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/projects [get]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    说明:
    // @Param prj_id query string false "项目Id"

    • prj_id: 要传入的变量名
    • query :传入变量的模式(本例是query模式)
    • string:传入变量值的类型(本例是字串)
    • false:是否必填(本例非必须)
    • 项目Id:变量说明
    • swagger显示

    在这里插入图片描述

    • 附:postman调用

    在这里插入图片描述

    - path 模式

    • 代码
    // SelectPrj 获取指定项目信息
    // @Summary 获取指定项目信息
    // @Description 获取指定项目信息
    // @Tags 项目管理
    // @Param uuid path string true "项目id"
    // @Success 200 {object} response.Response{data=models.PjmProject} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/projects/{uuid} [get]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    说明:
    @Param uuid path string true "项目id"

    • uuid: 要传入的变量名
    • path :传入变量的模式(本例是path模式)
    • string:传入变量值的类型(本例是字串)
    • true:是否必填(本例非必须)
    • 项目Id:变量说明
    • swagger显示

    在这里插入图片描述

    • 附:postman调用

    在这里插入图片描述

    4.2 POST

    - body模式

    • 代码
    // AddProject 创建项目
    // @Summary 创建项目
    // @Description 创建项目
    // @Tags 项目管理
    // @Accept  application/json
    // @Product application/json
    // @Param data body ProjectInput true "项目编号,项目缩写"
    // @Success 200 {object} response.Response{data=string} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/projects [post]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    说明:
    // @Param data body ProjectInput true "项目编号,项目缩写""

    • data: 用body模式传入,变量名是data
    • body :传入变量的模式(本例是body模式)
    • ProjectInput:传入变量值的类型(本例是自定义的一个结构体)
    • true:是否必填(本例必须)
    • 项目编号,项目缩写:传入json的说明
    • swagger显示

    在这里插入图片描述

    • 附:postman调用
      在这里插入图片描述

    - formData模式

    同PUT,见下文 PUT 的 formData 模式

    4.3 PUT

    - body模式

    • 代码
    // UpdateProject 从数据中台更新项目信息
    // @Summary 从数据中台更新项目信息
    // @Description 从数据中台更新项目信息
    // @Tags 项目管理
    // @Accept  application/json
    // @Product application/json
    // @Param data body models.PjmProject true "prj_nbr必填"
    // @Success 200 {object} response.Response{data=string} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/projects [put]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    说明:
    和POST相同,参加上文

    • swagger显示
      在这里插入图片描述

    • 附:postman调用
      在这里插入图片描述

    - formData模式

    • 代码
    // AutoModifyIp 自动修改smartX服务器IP
    // @Summary 自动修改smartX服务器IP
    // @Description 自动修改smartX服务器IP
    // @Tags 服务器管理
    // @Accept  application/x-www-form-urlencoded
    // @Product application/json
    // @Param uuid formData string true "服务器UUID"
    // @Success 200 {object} response.Response{data=string} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/my_server/smart_x_ip [put]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • swagger 显示
      在这里插入图片描述

    • 附:postman调用
      在这里插入图片描述

    4.4 DELETE

    - query

    • 代码
    // DeleteProject 删除项目
    // @Summary 删除项目
    // @Description 删除项目
    // @Tags 项目管理
    // @Param prj_id query string true "项目Id"
    // @Success 200 {object} response.Response{data=string} "{"code": 200, "data": [...]}"
    // @Router /api/v1/projects [delete]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    说明:
    说明参考上文 GET

    • swagger 显示

    在这里插入图片描述

    • 附: postman调用
      在这里插入图片描述

    - Path

    • 代码
    // DeleteServer 删除指定服务器
    // @Summary 删除指定服务器
    // @Description 删除指定服务器
    // @Tags 服务器管理
    // @Param uuid path string true "服务器uuid"
    // @Param project_num formData string true "项目编号"
    // @Success 200 {object} response.Response{data=string} "{"code": 200, "data": [...]}"
    // @Router /api/v1/my_server/{uuid} [delete]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    说明:
    参照GET的path,本例除了path还包含了一个formData

    • swagger显示
      在这里插入图片描述
    • 附:postman调用

    在这里插入图片描述

    4.5 Header

    • 代码
    // @Param DevopsToken header string false "token"
    
    • 1

    说明:

    • DevopsToken :header 的key
    • header : 指明类型时header
    • string : value类型
    • false :是否必须
    • "tocken":说明
    • 完整示例
    // GetMyServiceForBub 获取服务信息
    // @Summary 获取服务信息
    // @Description 获取服务信息
    // @Tags Public
    // @Param project_num query string false "项目编号"
    // @Param DevopsToken header string false "token"
    // @Success 200 {object} response.Response{data=[]service.GetServiceResponse} "{"code": 200, "data": [...]}"
    // @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
    // @Router /api/v1/pub/service/list [get]
    // @Security Bearer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • swagger显示

    在这里插入图片描述
    这里填上之后会从header传入,相当于:

    在这里插入图片描述

    5. 初始化

     swag init --parseDependency 
    
    • 1

    --parseDependency:使用外部依赖

    之后正常编辑即可。

    6. 访问

    • url : http://127.0.0.1/swagger/index.html

    在这里插入图片描述

  • 相关阅读:
    Ubuntu22.04 LTS+NVIDIA 4090+Cuda12.1+cudnn8.8.1
    mysql常用函数
    腾讯云我的世界mc服务器配置怎么选择?
    从0构建神经网络(1)从感知机到神经网络
    javascript复习之旅 9.1 从0到1认识`call apply`
    uni-app——网络请求、数据缓存
    基于JAVA的电子书城系统(Web)
    fastapi 基本介绍+使用
    OpenHarmony开源软件供应链安全风险
    关于Jetson空间不足的解决问题(sd卡挂载和conda更改环境安装路径)
  • 原文地址:https://blog.csdn.net/xingzuo_1840/article/details/126398282