使用 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 文档。

相关推荐
喵个咪1 小时前
AI重构软件开发范式:框架与脚手架为何仍是生产级开发的刚需?
架构·go·ai编程
夜悊3 小时前
Go并发编程的学习代码示例:生产者消费者模型
go
久违 °17 小时前
【AI-Agent】TagMatrix 数据标注工具开发
人工智能·数据分析·go·agent·数据隐私
小羊在睡觉17 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
用户398346161201 天前
Go-Spring 实战第 15 课 —— Condition:根据配置和上下文激活 Bean
spring·go
暗冰ཏོ1 天前
Go 语言从入门到后端项目实战完整指南
开发语言·后端·golang·go·go语言
逻极1 天前
Go 从入门到精通:并发编程与云原生实践
微服务·云原生·go·并发
basketball6161 天前
Go语言介绍
开发语言·go
10ms指针2 天前
【高性能Go实践02】深水区重构:规避 sync.Pool 大对象缺陷与 Cgo 边界内存安全实践
go
鹏北海3 天前
Go 语言基础笔记 — 面向 JS/TS 前端开发者
go