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

相关推荐
蒙娜丽宁2 天前
Go语言错误处理详解
ios·golang·go·xcode·go1.19
qq_172805592 天前
GO Govaluate
开发语言·后端·golang·go
littleschemer3 天前
Go缓存系统
缓存·go·cache·bigcache
程序者王大川4 天前
【GO开发】MacOS上搭建GO的基础环境-Hello World
开发语言·后端·macos·golang·go
Grassto4 天前
Gitlab 中几种不同的认证机制(Access Tokens,SSH Keys,Deploy Tokens,Deploy Keys)
go·ssh·gitlab·ci
高兴的才哥5 天前
kubevpn 教程
kubernetes·go·开发工具·telepresence·bridge to k8s
少林码僧5 天前
sqlx1.3.4版本的问题
go
蒙娜丽宁5 天前
Go语言结构体和元组全面解析
开发语言·后端·golang·go
蒙娜丽宁6 天前
深入解析Go语言的类型方法、接口与反射
java·开发语言·golang·go
三里清风_6 天前
Docker概述
运维·docker·容器·go