当前位置: 代码网 > it编程>前端脚本>Golang > Golang中使用Swagger生成API文档的流程步骤

Golang中使用Swagger生成API文档的流程步骤

2024年09月06日 Golang 我要评论
swagger 是一款强大的api文档生成工具,可以帮助开发者轻松创建、管理和展示 restful api 文档。在本文中,我们将介绍如何在 golang 项目中使用 swagger 来生成 api

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

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

swag --v

第二步:安装 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

第三步:编写 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",
    })
}

第四步:生成 swagger 文档

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

swag init

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

第五步:运行项目并访问 swagger ui

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

go run main.go

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

以上就是golang中使用swagger生成api文档的流程步骤的详细内容,更多关于golang swagger生成api文档的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com