swagger (GO) API文档工具入门

时间:2022-07-23
本文章向大家介绍swagger (GO) API文档工具入门,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  • swaggo
  • swagger

安装 swag 命令

go get -u github.com/swaggo/swag/cmd/swag

编写注释

  • 服务基础信息
// @title swagger使用例子
// @version 1.0
// @description swagger 入门使用例子
func main(){
    r := gin.Default()
    r.GET("/check", connectCheck)
    ...
}
  • api信息
type Response struct{
    Code uint32 `json:"code"`
    Message uint32 `json:"message"`
    Data interface{} `json:"data"`
}

type ResponseError struct{
    Code uint32 `json:"code"`
    Message uint32 `json:"message"`
}

// @summary 服务连接校验 --> 接口简介
// @Description 服务初始连接测试 --> 接口描述
// @Accept json   --> 接收类型
// @Produce json  --> 返回类型
// Success 200 {object} Response --> 成功后返回数据结构
// Failure 400 {object} ResponseError --> 失败后返回数据结构
// Failure 404 {object} ResponseError
// Failure 500 {object} ResponseError
// @Router /check [get] --> 路由地址及请求方法
func connectCheck(c *gin.Context){
    res := Response{ Code: 1001, Message: "OK", Data: "connect success !!!"}
    c.JSON(http.StatusOK, res)
}

生成文档

// 根目录执行
swag init

配置文档路由

import (
     ...
     _ "go-server/docs"  // 这里需要引入本地已生成文档
     ginSwagger "github.com/swaggo/gin-swagger" 
     swaggerFiles "github.com/swaggo/files"
)


func main(){
    ...
    
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run(":8080")
}

启动服务并访问

go run main.go

// 当前文档路径: localhost:swagger/index.html 

API 注释定义

  • summary 简介 // @Summary 简介
  • accept 可使用的MIME类型 // @Accept json
  • produce 可生成的MIME类型,既响应返回类型 // @Produce json // @Produce png 可设置多条
  • param 参数 格式: [ 参数名称 参数类型 数据类型 是否必须 备注 限制属性 ] 空格分割 @Params userId query string true "用户id" minlength(3) maxlength(100) @Params status query integer false "状态:0 1" Enums(0, 1) defualt(0)
    • 参数可用类型 [param type]
      • query
      • path
      • header
      • body
      • formDate
    • 数据可用类型 [data type]
      • string(string)
      • integer(int, uint, uint32, uint64)
      • boolean(bool)
      • user defined struct
    • 可配置属性
      • defualt * 参数默认值
      • maximum number 最大值
      • mininum number 最小值
      • maxLength integer 最大长度
      • minLength integer 最小长度
      • enums [*] 枚举类型
      • format string
      • collectionFormat string query数组分割模式
  • security 安全性
  • success 成功响应 格式: [ 状态码 {数据类型} 数据类型 备注 ] @Success 200 {object} Response "返回空对象"
  • failure 失败响应 格式: [ 状态码 {数据类型} 数据类型 备注 ] @Failure 400 {object} ResponseError
  • header 请求头字段 格式: [ 状态码 {数据类型} 数据类型 备注 ] // @Header 200 {string} Token "qwerty"
  • router 路由路径 // @Router /user/{userId} [get]
  • x-name 扩展字段 type Account struct { ID string `json:"id" extensions:"x-nullable,x-abc=def"` // 扩展字段必须以"x-"开头 }

结构体描述

  • example 例子
type User struct{
  ID int `json:"id" example:"232323"`
  Name string `json:"name" example:"Coco" `
}
  • 限制属性 type User struct{ ID int `json:"id" minLength:"3" maxLength:"100"` }
  • swaggerignore 排除字段 type Account struct { ID string `json:"id"` Name string `json:"name"` Ignored int `swaggerignore:"true"` // 排除Ignored字段 }
  • 重命名 type Resp struct { Code int }//@name Response 必须放在结构体末尾

注意事项

  • 多字段定义时不能跨字段 // @Accept json // @Produce json // @param id query string false "用户id" default("") minlength(3) maxlength(100) // @Produce json 这里将报错
  • 修改定义后需要重新执行,生成命令并重启服务
  • 路由配置时,引入文档