使用swaggo時要注意的一點


安裝swag cli 及下載相關包

要使用swaggo,首先需要安裝swag cli。

$ go get -u github.com/swaggo/swag/cmd/swag

然后我們還需要兩個包。

gin-swagger 中間件

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

swagger 內置文件

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

在api處根據api添加描述

import (
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)


// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService https://razeen.me

// @contact.name Razeen
// @contact.url https://razeen.me
// @contact.email me@razeen.me

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host 127.0.0.1:8080
// @BasePath /api/v1


func main() {

	r := gin.Default()
    store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	v1 := r.Group("/api/v1")
	{
		v1.GET("/hello", HandleHello)
	}

	r.Run(":8080")
}
 // @Summary 測試SayHello
// @Description 向你說Hello
// @Tags 測試
// @Accept mpfd
// @Produce json
// @Param who query string true "人名"
// @Success 200 {string} json "{"msg": "hello Razeen"}"
// @Failure 400 {string} json "{"msg": "who are you"}"
// @Router /hello [get]
func HandleHello(c *gin.Context) {
	who := c.Query("who")

	if who == "" {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "who are u?"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"msg": "hello " + who})
}

保存之后再命令行寫

swag init

成功后在統計目錄會生成一個docs目錄,里面有三個文件:

  • docs.go
  • swagger.json
  • swagger.yaml

最后go run main,go 也成功

原以為在瀏覽器訪問 http://127.0.0.1:8080/swagger/index.html 肯定是成功的,沒想到頁面顯示是 Fetch errorInternal Server Error doc.json

一開始可能是注釋寫漏了或者是寫錯了,但是各種嘗試修改都不行。
最后查到說是需要引入docs目錄才行。

import (
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"

        _ "gin-admin/docs"
)

最后用上面的方式果然成功


免責聲明!

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



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