使用 Swagger 在 Golang 中进行 API 文档生成

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

官网地址 : gin-swagger

前提条件

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

第一步:安装 Swagger 工具

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

go 复制代码
go install github.com/swaggo/swag/cmd/swag@latest

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

go 复制代码
swag --v

第二步:安装 Swaggo 依赖

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

go 复制代码
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

第三步:编写 API 代码

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

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",
    })
}

第四步:生成 Swagger 文档

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

go 复制代码
swag init

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

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

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

bash 复制代码
go run main.go

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

相关推荐
microrain22 分钟前
从云端到边缘:SagooIoT边缘计算架构的落地实践
物联网·开源·go·sagooiot
TunerT_TQ1 天前
Valhalla 静态工程审阅 #007|AgentENV 源码证据驱动评测【大厂开源基础设施特辑】
rust·开源·go·github·sandbox·分布式系统·ai基础设施
名字还没想好☜1 天前
Go 表驱动测试实战:用 t.Run 子测试组织可维护的单元测试
golang·单元测试·log4j·go·testing
深念Y1 天前
技术探索记录 在 Android 手机上运行 One API
android·linux·服务器·智能手机·go·交叉编译·服务
名字还没想好☜2 天前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
捧 花2 天前
从同步生成到异步任务:YoudaoNoteLM 的生成队列模块设计
go·agent·worker·eino
小满zs2 天前
Go语言第四章(类型转换)
后端·go
妙码生花4 天前
从 PHP 到 AI + Golang,程序员自救转型手记(四十三):前后端数据验证
后端·go·ai编程
半夜里咳嗽的狼4 天前
Go 1.25 的 WaitGroup.Go 省了两行代码,也补不上这三个并发边界
后端·go