[Golang]如何在Golang安裝swagger
[Golang]如何在Golang安裝swagger

[Golang]如何在Golang安裝swagger

  1. 下載swag

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

    go 1.7之後採用

    go install github.com/swaggo/swag/cmd/swag@latest
  2. 在您的 Go 項目根路徑(例如) 運行Swag , Swag將解析註釋並生成所需的文件。~/root/go-peoject-namedocsdocs/doc.go~/root/go-peoject-name/docs

    swag init
  3. 下載gin-swagger

    go get -u github.com/swaggo/gin-swagger
    go get -u github.com/swaggo/files
  4. 檔案頭設定

    // @title Gin swagger test
    // @version 1.0
    // @description Gin swagger ini
    
    // @contact.name Sam Chen
    // @contact.url https://github.com/sam80719
    
    // @host localhost:8088
    註解 描述
    title 必須簡單API專案的標題或主要的業務功能
    version 必須目前這專案/API的版本
    description 簡單描述
    tersOfService 服務條款
    contact.name 作者名稱
    contact.url 作者blog
    contact.email 作者email
    license.name 必須許可證名稱
    license.url 許可證網址
    host 服務名稱或者是ip
    BasePath 基本URL路徑, (/api/v1, /v2...)
    schemes 提供的協定, (http, https)
  5. 在router增加路由

    url := ginSwagger.URL("http://localhost:8088/swagger/doc.json")
        router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) // http://localhost:8088/swagger/index.html
  6. 完成後下指令,重新跑一次

    swag init; go run main.go
    http://localhost:8080/swagger/index.html

    swagger的畫面就出現了

參考代碼