1. 程式人生 > 其它 >使用swaggo時要注意的一點

使用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 [email protected]

// @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"
)

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