golang-swagger安装步骤

文章介绍了如何在Go语言中利用Gin框架和Swag工具来构建SwaggerAPI文档。首先,详细说明了Swag和Gin-Swagger的安装步骤,然后展示了如何编写main函数和控制器以定义API接口。最后提到了初始化Swag和解决访问文档时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、下载swagger

  1. 安装swag 
    1. https://github.com/swaggo/swag/releases/   安装包
    2. chmod +x ./swag 
    3. mv swag /usr/local/bin
    4. swag cli:go install github.com/swaggo/swag/cmd/swag@latest
  2. 安装gin-swagger
    1. go get github.com/swaggo/gin-swagger
  3. 安装swaggerfiles
    1.  go get github.com/swaggo/gin-swagger/swaggerFiles

二、代码编写

  1. main()函数
    import (
       "github.com/gin-gonic/gin"
       swaggerFiles "github.com/swaggo/files"
       ginSwagger "github.com/swaggo/gin-swagger"
       _ "golib/docs"
    )
    
    // @title golang api 框架
    // @version 1.0
    // @contact.name   API Support
    // @contact.url    http://www.swagger.io/support
    // @contact.email  support@swagger.io
    
    // @host                 localhost:8080
    // @BasePath             /
    // @query.collection.format   multi
    func main() {
            engine := gin.Default()
            engine.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))     
            testGroup := engine.Group("/test")
            {
                    testGroup.GET("/hello", HelloWorld)
            }
    
            engine.Run("8080")
    }
  2. controller
    1. // List godoc
      // @Summary      测试helloworld
      // @Description  测试helloworld
      // @Tags         测试
      // @Accept       json
      // @Produce      json
      // @Param        name  query     string      true  "姓名"
      // @Success      200    {string} json "{"msg":"","code":200}"
      // @Failure      400    {string} json "{"msg":"","code":400}"
      // @Router       /test/hello [get]
      func HelloWorld(ctx *gin.Context) {
              ctx.Json(http.StatusOK, gin.H{"msg":"hello world", "code":200})
      }

三、初始化

  1. 如果main.go在根目录
    1. swag init
  2. 如果main.go 函数不在根目录,例如:inter/main.go
    1. swag init -g ./inter/main.go
  3. 会在根目录生成:docs/ 目录
  4. 访问方式
    1. http://127.0.0.1:8080/docs/index.html

四、问题描述

  1. 访问的时候可能会报出:
    1. Fetch errorInternal Server Error doc.json
  2. 需要引入 docs目录才行

    import (

         "github.com/gin-gonic/gin" ginSwagger

         "github.com/swaggo/gin-swagger"

         "github.com/swaggo/gin-swagger/swaggerFiles"

         _ "gin-admin/docs"

    )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值