golang gin框架 swag在線api文檔


一 安裝swag

go get github.com/swaggo/swag/cmd/swag

 

二 安裝gin-swagger

go get -u github.com/swaggo/gin-swagger

go get -u github.com/swaggo/gin-swagger/swaggerFiles

 

三 生成docs文件夾

 

swag init  
  • swag init一定要和main.go處於同一級目錄
  • main程序名稱必須為main.go, 本人嘗試過別的名字比如wbw.go的時候會報如下錯誤,有知道如何解決的朋友可教我一下
    cannot parse source files /home/wbw/go/src/debuggrpc/test/testswag/main.go: open /home/wbw/go/src/debuggrpc/test/testswag/main.go: no such file or directory      

 

四 gin引用swag

 

  main.go

package main

import (
    "debuggrpc/test/testswag/controller"
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger/swaggerFiles"

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

    _ "debuggrpc/test/testswag/docs"

)

// @title TestSwg API
// @version 1.0

// @host 127.0.0.1:9501
// @BasePath /testswag/v1.0
func main(){
    router := gin.Default()
    // v1
    r1 := router.Group("/testswag/v1.0")
    {
        r1.GET("/Baseinfo", controller.Baseinfo)

    }
    router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    router.Run( "0.0.0.0:8080")
}

  base.go

 

package controller

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

// @Summary 獲取基礎信息列表
// @Description 獲取基礎信息列表
// @Tags 基礎信息
// @Accept json
// @Success 200 {json} json "{"errno":0,"errmsg": "成功","data":infolist}"
// @Failure 400 {json} json "{"errno":4502,"errmsg": "查詢失敗"}"
// @Router /Baseinfo [post]
func Baseinfo(ctx *gin.Context) {
    resp := make(map[string]interface{})
    resp["data"] = "baseinfo"
    resp["errno"] = 200
    resp["errmsg"] = "success"
    ctx.JSON(http.StatusOK, resp)
    return
}

  運行main.go之后,瀏覽器分別訪問 http://localhost:8080/testswag/v1.0/Baseinfo   

 

http://localhost:8080/swagger/index.html

 

 

  • 請注意main代碼中的import
  • 請記住導入  _ "debuggrpc/test/testswag/docs"
  • swag其他注釋比如param等請自行查閱 Swaggo · Go語言中文文檔 (topgoer.com)
  • 記得更新文檔(swag注釋)后要swag init一下並重啟gin
  • gin的分組為router.group; swag的分組為tag標簽

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM