Swagger 是一款强大的 API 文档生成工具,可以帮助开发者轻松创建、管理和展示 RESTful API 文档。在本文中,我们将介绍如何在 Golang 项目中使用 Swagger 来生成 API 文档。

官网地址 :  gin-swagger

前提条件

  • Golang 开发环境(推荐使用 Go 1.16 或更高版本)
  • Go Modules 管理工具
  • 已安装的 Git 工具

第一步:安装 Swagger 工具

在开始之前,我们需要安装 Swagger 工具。你可以使用以下命令来安装 Swagger:

go install github.com/swaggo/swag/cmd/swag@latest
  • 1.

安装完成后,可以通过运行以下命令来验证安装是否成功:

swag --v
  • 1.

第二步:安装 Swaggo 依赖

Swaggo 是一个用于 Golang 的 Swagger 文档生成器。我们需要在项目中安装 Swaggo 依赖:

go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
go get -u github.com/swaggo/swag
  • 1.
  • 2.
  • 3.
  • 4.

第三步:编写 API 代码

接下来,我们编写一个简单的 API 示例。在项目根目录下创建一个 main.go 文件,并添加以下内容:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
    _ "go-swagger-example/docs"
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore 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

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

    // Simple group: v1
    v1 := r.Group("/api/v1")
    {
        v1.GET("/hello", helloHandler)
    }

    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    r.Run()
}

// helloHandler godoc
// @Summary Show a hello message
// @Description get string message
// @Tags example
// @Accept  json
// @Produce  json
// @Success 200 {string} string "ok"
// @Router /hello [get]
func helloHandler(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "hello world",
    })
}
  • 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.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.

第四步:生成 Swagger 文档

在编写好 API 代码后,我们可以使用 Swaggo 生成 Swagger 文档。在项目根目录下运行以下命令:

swag init
  • 1.

运行此命令后,会在项目根目录下生成 docs 文件夹,其中包含生成的 Swagger 文档。

第五步:运行项目并访问 Swagger UI

最后,我们运行项目,并访问 Swagger UI。运行以下命令启动项目:

go run main.go
  • 1.

在浏览器中访问 http://localhost:8080/swagger/index.html,即可看到生成的 Swagger UI 页面,其中包含了我们编写的 API 文档。