1. 程式人生 > 其它 >gin-swagger生成API文件

gin-swagger生成API文件

github地址:https://github.com/swaggo/gin-swagger

下載安裝cmd/swag命令工具包

先下載cmd包,才能執行相關命令

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

我開始沒成功,後來進入$GOPATH/bin/ 目錄執行go get github.com/swaggo/swag/cmd/swag ,在bin目錄下生成一個swag.exe檔案,把$GOPATH/bin/ 新增到Path環境變數才算成功

回到頂部

執行初始化命令

swag init  // 注意,一定要和main.go處於同一級目錄

初始化命令,在根目錄生成一個docs資料夾

  • docs/docs.go
回到頂部

示例程式

package main

import (
    "apiwendang/controller"
    _ "apiwendang/docs"
    "github.com/gin-gonic/gin"
    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"
)


// @title Docker監控服務
// @version 1.0
// @description docker監控服務後端API介面文件

// @contact.name API Support
// @contact.url http://www.swagger.io/support

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

// @host 127.0.0.1:9009
// @BasePath
func main() {
    r := gin.New()

    r.Use(Cors())
    //url := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition
    r.POST("/test/:id", controller.Test)
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    r.Run(":9009")
}


func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Header("Access-Control-Allow-Origin", "*")
        c.Next()
    }
}
回到頂部

再次執行初始化命令

swag init  // 注意,一定要和main.go處於同一級目錄

初始化命令,在根目錄生成一個docs資料夾,內含三個檔案

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

訪問swagger文件:http://localhost:9009/swagger/index.html

====

回到頂部

API操作

// @Summary 介面概要說明
// @Description 介面詳細描述資訊
// @Tags 使用者資訊   //swagger API分類標籤, 同一個tag為一組
// @accept json  //瀏覽器可處理資料型別,瀏覽器預設發 Accept: */*
// @Produce  json  //設定返回資料的型別和編碼
// @Param id path int true "ID"    //url引數:(name;引數型別[query(?id=),path(/123)];資料型別;required;引數描述)
// @Param name query string false "name"
// @Success 200 {object} Res {"code":200,"data":null,"msg":""}  //成功返回的資料結構, 最後是示例
// @Failure 400 {object} Res {"code":200,"data":null,"msg":""}
// @Router /test/{id} [get]    //路由資訊,一定要寫上

如果引數是body

// @Param user body models.User true "user"

1. 返回字串

// @Summary 測試介面
// @Description 描述資訊
// @Success 200 {string} string    "ok"
// @Router / [get]
func Test(ctx *gin.Context)  {
    ctx.JSON(200, "ok")
}

2. 返回gin.H

// @Summary 測試介面
// @Description 描述資訊
// @Success 200 {object} gin.H
// @Router / [get]
func Test(ctx *gin.Context)  {
    ctx.JSON(200, gin.H{
        "code":200,
    })
}

如果直接返回gin.H這種json結構,要用@Success 200 {object} gin.H,但是這種編譯很慢,最好還是返回一種固定的結構體

3. 返回固定struct結構體

type Res struct {
    Code int `json:"code"`
    Data interface{} `json:"data"`
    Msg string `json:"msg"`
}
func returnMsg(ctx *gin.Context, code int, data interface{}, msg string) {
    ctx.JSON(200, Res{
        Code:code,
        Data:data,
        Msg:msg,
    })
}

// @Summary 測試介面
// @Description 描述資訊
// @Success 200 {object} Res {"code":200,"data":null,"msg":""}
// @Router / [get]
func Test(ctx *gin.Context)  {
    ctx.JSON(200, Res{
        Code:200,
        Data:nil,
        Msg:"",
    })
}

POST請求:

models/user.go
  
type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
==================

type Res struct {
    Code int `json:"code"`
    Data interface{} `json:"data"`
    Msg string `json:"msg"`
}
func returnMsg(ctx *gin.Context, code int, data interface{}, msg string) {
    ctx.JSON(200, Res{
        Code:code,
        Data:data,
        Msg:msg,
    })
}


func Test1(ctx *gin.Context)  {
    returnMsg(ctx, 500, "aaa", "bbb")
}

// @Summary 介面概要說明
// @Description 介面詳細描述資訊
// @Tags 測試
// @Security Bearer
// @Produce  json
// @Param id path int true "ID"
// @Param user body models.User true "user"
// @Success 200 {object} Res {"code":200,"data":null,"msg":""}
// @Router /test/{id} [post]
func Test(ctx *gin.Context)  {
    fmt.Println(ctx.Param("id"))
    var input models.User
    if err := ctx.ShouldBindJSON(&input); err!=nil{
        returnMsg(ctx, 402, nil, err.Error())
        return
    }
    fmt.Println(input)
    returnMsg(ctx, 200, "aaa", "bbb")
}
回到頂部

如果出現錯誤:Undocumented TypeError: Failed to fetch

檢視具體錯誤資訊,瀏覽器F12,發現是跨域問題:

Failed to load http://127.0.0.1:9009/test/2: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9009' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

設定允許跨域就OK了

簡單版本:

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Header("Access-Control-Allow-Origin", "*")
        c.Next()
    }
}

複雜的可以根據實際需求新增:

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method  
        origin := c.Request.Header.Get("Origin")
        var headerKeys []string
        for k, _ := range c.Request.Header {
            headerKeys = append(headerKeys, k)
        }
        headerStr := strings.Join(headerKeys, ", ")
        if headerStr != "" {
            headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
        } else {
            headerStr = "access-control-allow-origin, access-control-allow-headers"
        }
        if origin != "" {
            c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
            c.Header("Access-Control-Allow-Origin", "*")                                       // 這是允許訪問所有域
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //伺服器支援的所有跨域請求的方法,為了避免瀏覽次請求的多次'預檢'請求
            //  header的型別
            c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
            //              允許跨域設定                                                                                                      可以返回其他子段
            c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域關鍵設定 讓瀏覽器可以解析
            c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                           // 快取請求資訊 單位為秒
            c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                  //  跨域請求是否需要帶cookie資訊 預設設定為true
            c.Set("content-type", "application/json")                                                                                                                                                              // 設定返回格式是json
        }

        //放行所有OPTIONS方法
        //if method == "OPTIONS" {
        //    c.JSON(http.StatusOK, "Options Request!")
        //}
        if method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }
        // 處理請求
        c.Next() //  處理請求
    }
}

https://www.ctolib.com/swaggo-swag.html

https://github.com/swaggo/swag

原文https://www.cnblogs.com/zhzhlong/p/11800787.html