webapi 注解调试工具swaggo 介绍和使用

发布时间 2023-10-31 11:56:22作者: 橙皮^-^

swaggo 介绍和使用

介绍

  • Swag是一个开源项目,用于web框架下接口调试和文档管理,可以将代码中的接口注释转换为文档格式,并提供界面在线调试接口的功能。
  • 项目地址:https://github.com/swaggo/swag
  • 目前项目可以支持的web框架
    • gin,echo,buffalo,net/http,gorilla/mux,go-chi/chi,flamingo,fiber,atreugo,hertz
  • 在线界面调试和文档效果图

使用

  • 文档用的测试环境

    • go version go1.20.1 linux/amd64
    • swag version v1.16.2(测试时尽量更新到最新版本,旧版本有其他bug)
    • 更新操作 go get -u github.com/swaggo/swag/cmd/swag@latest
    • 示例用到的web框架为gin
  • 安装swag

    • go install github.com/swaggo/swag/cmd/swag@latest
  • 先实现一个简单的web api 计算俩个值的积

    • 目录结构 go mod init demo

      ├── go.mod
      ├── go.sum
      └── main.go

    • main.go

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    	"strconv"
    )
    
    // HTTPError example
    type HTTPError struct {
    	Code    int    `json:"code" example:"400"`
    	Message string `json:"message" example:"status bad request"`
    }
    
    func CalcExample(ctx *gin.Context) {
    	val1, err := strconv.Atoi(ctx.Query("val1"))
    	if err != nil {
    		er := HTTPError{
    			Code:    http.StatusBadRequest,
    			Message: err.Error(),
    		}
    		ctx.JSON(http.StatusBadRequest, er)
    		return
    	}
    	val2, err := strconv.Atoi(ctx.Query("val2"))
    	if err != nil {
    		er := HTTPError{
    			Code:    http.StatusBadRequest,
    			Message: err.Error(),
    		}
    		ctx.JSON(http.StatusBadRequest, er)
    		return
    	}
    	ans := val1 + val2
    	ctx.String(http.StatusOK, "%d", ans)
    }
    
    func main() {
    	r := gin.Default()
    
    	api := r.Group("/examples")
    	api.GET("calc", CalcExample)
    	r.Run(":8080")
    }
    
  • 对调用api进行注释

    //	@title			Swagger Example API
    //	@version		1.0
    //	@description	This is a sample swap server
    
    // CalcExample godoc
    //
    //	@Summary		calc example
    //	@Description	plus
    //	@Tags			example
    //	@Accept			json
    //	@Produce		plain
    //	@Param			val1	query		int		true	"used for calc"
    //	@Param			val2	query		int		true	"used for calc"
    //	@Success		200		{integer}	string	"answer"
    //	@Failure		400		{string}	string	"ok"
    //	@Failure		404		{string}	string	"ok"
    //	@Failure		500		{string}	string	"ok"
    //	@Router			/examples/calc [get]
    func CalcExample(ctx *gin.Context) {
    	val1, err := strconv.Atoi(ctx.Query("val1"))
    	if err != nil {
    		er := HTTPError{
    			Code:    http.StatusBadRequest,
    			Message: err.Error(),
    		}
    		ctx.JSON(http.StatusBadRequest, er)
    		return
    	}
    	val2, err := strconv.Atoi(ctx.Query("val2"))
    	if err != nil {
    		er := HTTPError{
    			Code:    http.StatusBadRequest,
    			Message: err.Error(),
    		}
    		ctx.JSON(http.StatusBadRequest, er)
    		return
    	}
    	ans := val1 + val2
    	ctx.String(http.StatusOK, "%d", ans)
    }
    
  • 生成文档目录

swag init -g main.go -o ./docs
# -g 指定main.go文件路径,默认当前路径下查找main.go文件
# -o 指定输出路径,默认为当前路径
  • 在项目根目录下执行执行会在当前目录生成docs目录以及目录下相关文件
    • ├── docs
      │ ├── docs.go
      │ ├── swagger.json
      │ └── swagger.yaml
      ├── go.mod
      ├── go.sum
      └── main.go
  • 在项目中配置gin-swagger插件和调用重定向代码
	import(
        _ "demo/docs" //swag init -g main.go 生成的目录模块
		swaggerFiles "github.com/swaggo/files"
		ginSwagger "github.com/swaggo/gin-swagger" //适配gin框架插件
    )

    func main() {
        r := gin.Default()

        api := r.Group("/examples")
        api.POST("calc", CalcExample)
        //重定向接口 usr = basePath + @Router 拼接而成
       	docs.SwaggerInfo.BasePath = "/"
        r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
        r.Run(":8080")
    }

注释规则

  • 主要常用注释关键字

    • @title 应用程序名(这里官方文档描述必填选项, 实测去掉也行)
    • @version api版本号(这里官方文档描述必填选项, 实测去掉也行)
    • @Summary 接口概述
    • @Description 接口的详细描述
    • @Tags 接口类型标记,用来管理界面显示接口,用来进行分类
    • @Param 参数说明格式: param name,param type,data type,is mandatory?,comment attribute(optional)
    • @Success 以空格分隔的成功响应。return code,{param type},data type,comment
    • @Router url请求地址 [get/post/或其他方法]
  • 更多的注释格式说明