Skip to content

go gin swagger

在 Go 中使用 Gin 框架时,集成 Swagger 可以帮助自动化生成 API 文档。Swagger 是一个流行的 API 文档工具,它基于 OpenAPI 规范,允许开发者通过注释、结构体等方式自动生成接口文档。

1. 安装必要的依赖

要在 Go 项目中集成 Swagger,你需要一些工具和库。以下是步骤:

1.1 安装 gin-swaggerswag 工具

gin-swagger 是一个用于将 Gin 路由与 Swagger UI 集成的库,swag 是一个用于自动生成 Swagger 文档的工具。

首先,安装 swag 工具(用于生成 Swagger 文件):

bash
go install github.com/swaggo/swag/cmd/swag@latest

然后,安装 gin-swaggerswag 的相关依赖:

bash
go get -u github.com/gin-contrib/static
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/swag

1.2 配置 Go 项目中的 Swagger 注解

Swagger 注解基于 Go 代码中的注释和结构体,可以通过这些注释自动生成 API 文档。

2. 基本流程

2.1 定义基本的 API 和文档注解

我们可以在路由处理函数上方使用注释来定义 Swagger 文档。

示例代码

go
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/swag/example/basic/docs"
	"net/http"
)

// @title Go Gin Swagger Example API
// @version 1.0
// @description This is a sample server Gin Swagger API
// @termsOfService https://example.com/terms/

// @contact.name API Support
// @contact.url https://example.com/support
// @contact.email support@example.com

// @host localhost:8080
// @BasePath /api/v1
func main() {
	r := gin.Default()

	// Swagger路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler)

	// API 路由
	r.GET("/api/v1/hello", func(c *gin.Context) {
		// 返回 JSON 响应
		c.JSON(http.StatusOK, gin.H{
			"message": "Hello, world!",
		})
	})

	r.Run(":8080")
}

2.2 使用 swag 工具生成 Swagger 文档

一旦你的注释完成了,运行 swag init 来生成 Swagger 文档。

bash
swag init

swag init 会自动解析代码中的注释,并生成一个 docs 文件夹,该文件夹包含了生成的 Swagger 文档。

3. Swagger 注释详解

Swagger 文档是通过注释来生成的,以下是常见的注释格式:

3.1 API 基本信息注释

go
// @title Go Gin Swagger Example API
// @version 1.0
// @description This is a sample server Gin Swagger API
// @termsOfService https://example.com/terms/

// @contact.name API Support
// @contact.url https://example.com/support
// @contact.email support@example.com

// @host localhost:8080
// @BasePath /api/v1

这些注释提供了 API 的基本信息,例如标题、版本、描述、Terms of Service、联系方式、主机信息等。

3.2 路由方法注释

对于每个路由,你可以在处理函数上方添加注释来定义请求的详细信息:

go
// @Summary Returns a hello message
// @Description Get a hello message
// @Tags hello
// @Accept  json
// @Produce  json
// @Success 200 {object} map[string]string
// @Router /api/v1/hello [get]
  • @Summary:简短描述接口的作用。
  • @Description:接口的详细描述。
  • @Tags:给接口分配标签(用于分类)。
  • @Accept:请求数据的类型(例如 json)。
  • @Produce:响应数据的类型。
  • @Success:成功响应的 HTTP 状态码和返回的数据结构。
  • @Router:路由的 URL 和 HTTP 方法。

4. 集成 Swagger UI

要访问自动生成的 Swagger UI 页面,可以通过 gin-swagger 提供的 WrapHandler 方法来设置 Swagger 路由。前面的示例中,我们已经集成了这个步骤:

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

这会将 localhost:8080/swagger/index.html 设置为 Swagger UI 的入口,打开该 URL 即可访问 API 文档界面。

5. 继承和扩展 Swagger 注解

在 Go 中,Swagger 注解继承和扩展的方式主要体现在结构体和接口文档的继承上。Gin 中的 API 路由函数是通过注释来实现自动文档生成的,而对于复杂的 API 文档,继承和复用 Swagger 注解通常是通过结构体嵌套和复用同样的注解来实现的。

示例:使用结构体嵌套继承 Swagger 注解

假设我们有多个 API 路由共享相同的请求和响应体,你可以通过定义基础结构体来共享字段和注解。

go
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/swag/example/basic/docs"
	"net/http"
)

// 基本的响应结构体
type BaseResponse struct {
	Message string `json:"message"`
}

// @title Go Gin Swagger Example API
// @version 1.0
// @description This is a sample server Gin Swagger API
// @termsOfService https://example.com/terms/
func main() {
	r := gin.Default()

	// Swagger路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler)

	// API 路由
	r.GET("/api/v1/hello", func(c *gin.Context) {
		// 返回继承的结构体
		c.JSON(http.StatusOK, BaseResponse{
			Message: "Hello, world!",
		})
	})

	r.GET("/api/v1/greet", func(c *gin.Context) {
		// 返回相同结构体,不需要重复注释
		c.JSON(http.StatusOK, BaseResponse{
			Message: "Greetings!",
		})
	})

	r.Run(":8080")
}

这样,BaseResponse 结构体的定义可以在多个路由中复用,并且共享字段注解。Swagger 会自动生成文档,包含相同的响应结构。

进一步的结构体嵌套

如果你有更加复杂的嵌套结构体,可以使用 Go 结构体嵌套的特性,并在 Swagger 注释中描述这种嵌套。

go
type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

type UserResponse struct {
	User  User   `json:"user"`
	Error string `json:"error,omitempty"`
}

在 Swagger 文档中,它会显示 UserResponse 类型包含一个 User 对象。

6. 总结

  • 生成 Swagger 文档:通过在代码中添加注释来生成 Swagger 文档。使用 swag 工具来自动生成文档。
  • 文档注释格式:使用特定的注释标记(如 @Summary@Description)来描述 API。
  • 继承和复用:可以通过结构体嵌套和复用共享字段,减少重复的注释工作。
  • 集成 Swagger UI:通过 gin-swagger 将 Swagger UI 集成到 Gin 应用中,方便用户浏览 API 文档。

通过这种方式,你可以轻松地在 Gin 中实现自动化的 API 文档生成,并且使用 Swagger UI 来可视化和交互地查看你的 API。