展示接口文档的几种方式

之前的文章《Golang项目自动生成swagger格式接口文档方法(一)》已经介绍过Golang项目借助swaggo来自动生成接口文档方法,生成接口文档主的主要目的是用来做更好的展示使用,展示方法一般有三种:

  1. 启动一个swagger服务来展示;

  1. 将生成的swagger文档导入三方接口管理工具进行展示;

  1. 三方工具请求swagger服务,定期将文档同步到自己系统里面展示。

gin框架集成swagger服务

可以看出如果是使用第二种展示方式的话,上篇介绍的内容就够了。如果要实现第一和第三种方式,项目就需要集成swagger服务了。本文就以gin框架为例,来说明一下项目如何集成swagger服务。

先按照上篇文章介绍的方法安装swag工具。然后创建示例项目,假如项目名称为go-project-name,创建main.go文件(先只定义包名即可),main.go内容如下

package main

使用swag init生成docs文件夹,目录结构如下:

├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
│── go.mod
│── go.sum
└── main.go

修改main.go文件,写入如下示例代码(需要好好体会示例代码):

package main

import (
  "net/http"
  
   "github.com/gin-gonic/gin"
   docs "github.com/go-project-name/docs"
   swaggerfiles "github.com/swaggo/files"
   ginSwagger "github.com/swaggo/gin-swagger"
)
// @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")
}

执行swag init后运行代码,访问http://localhost:8080/swagger/index.html即可看到接口定义列表。主流的三方接口文档管理系统都会实现从swagger服务自动同步的功能,即访问swagger服务的doc.json文件,将内容同步到自己系统里,即定期访问http://localhost:8080/swagger/doc.json。