go-swagger

gin-swagger

  1. 下载 swagger
  2. 加载 swagger
  3. 执行 swagger命令
  4. 使用Cors中间件
  5. 测试

1 下载swagger

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

2 安装swagger

安装go-swagger,移动到下载的go-swagger包目录(应该是GOPATH/src/pkg/github.com/go-swagger,理解这个意思就好,路径不一定对)。

go install ./cmd/swagger

测试是否安装成功 cmd 执行 swag -V 反馈 swag 版本

执行后,会生成docs/doc.go以及docs/swagger.json,docs/swagger.yaml

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

2 加载 swagger

package router

import (
    "gin_t/middelwares"
    "gin_t/service"
    "net/http"

    "github.com/gin-gonic/gin"
    swaggerfiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"
)

// @Tags 标签
// @Summary 标题
// @description 描述,可以有多个

// @Success 200 {string} json "{"code":"200","data":"message":"string"}"
// @Router /ping [get]
func Router() *gin.Engine {
    r := gin.Default()
    r.Use(middelwares.Cors())
    r.GET("/ping", func(ctx *gin.Context) {
        ctx.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    })
    // Swagger 配置
    r.GET("swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
    return r
}

package service

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func Ping(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
        "message": "pong",
    })
}

package main

import (
    _ "gin_t/docs"
    "gin_t/router"
)

// @title API文档
// @version 1.0
// @description API 文档
// @host 127.0.0.01:8080
// @BasePath

func main() {
    
    r := router.Router()

    r.Run()
}

3 执行 swagger命令

cmd 项目执行  swag init  

4 使用Cors中间件

package middelwares

import (
    "fmt"
    "strings"

    "github.com/gin-gonic/gin"
)

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() //  处理请求
    }
}

5 测试

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

swag注解开发方法

swagger主文件注解-通用API信息

注释 说明 示例
title 必填 应用程序的名称。 // @title Swagger Example API
version 必填 提供应用程序API的版本。 // @version 1.0
description 应用程序的简短描述。 // @description This is a sample server celler server.
tag.name 标签的名称。 // @tag.name This is the name of the tag
tag.description 标签的描述。 // @tag.description Cool Description
tag.docs.url 标签的外部文档的URL。 // @tag.docs.url https://example.com
tag.docs.description 标签的外部文档说明。 // @tag.docs.description Best example documentation
termsOfService API的服务条款。 // @termsOfService http://swagger.io/terms/
contact.name 公开的API的联系信息。 // @contact.name API Support
contact.url 联系信息的URL。 必须采用网址格式。 // @contact.url http://www.swagger.io/support
contact.email 联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。 // @contact.email support@swagger.io
license.name 必填 用于API的许可证名称。 // @license.name Apache 2.0
license.url 用于API的许可证的URL。 必须采用网址格式。 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html
host 运行API的主机(主机名或IP地址)。 // @host localhost:8080
BasePath 运行API的基本路径。 // @BasePath /api/v1
accept API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。 // @accept json
produce API可以生成的MIME类型的列表。值必须如“Mime类型”中所述。 // @produce json
query.collection.format 请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。 // @query.collection.format multi
schemes 用空格分隔的请求的传输协议。 // @schemes http https
x-name 扩展的键必须以x-开头,并且只能使用json值 // @x-example-key {“key”: “value”}

每个API的注释编写-单个api

注释 描述
description 操作行为的详细说明。
description.markdown 应用程序的简短描述。该描述将从名为endpointname.md的文件中读取。
id 用于标识操作的唯一字符串。在所有API操作中必须唯一。
tags 每个API操作的标签列表,以逗号分隔。
summary 该操作的简短摘要。
accept API 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。
produce API可以生成的MIME类型的列表。值必须如“Mime类型”中所述。
param 用空格分隔的参数。param name,param type,data type,is mandatory?,comment attribute(optional)
security 每个API操作的安全性
success 以空格分隔的成功响应。return code,{param type},data type,comment
failure 以空格分隔的故障响应。return code,{param type},data type,comment
response 与success、failure作用相同
header 以空格分隔的头字段。 return code,{param type},data type,comment
router 以空格分隔的路径定义。 path,[httpMethod]
x-name 扩展字段必须以x-开头,并且只能使用json值。
//各个api.go
// GetProblemList
// @Tags 公共方法
// @Summary 问题列表
// @Param page query int false "page"
// @Param size query int false "size"
// @Param keyword query string false "keyword"
// @Param category_identity query string false "category_identity"
// @Success 200 {string} json "{"code":"200","data":""}"
// @Router /problem-list [get]

//各个api.go
// @Summary 支付列表
// @Description 获取支付列表
// @Accept  json
// @Produce  json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param  body body st.PaySearch true "交款查询参数"
// @Success 200 {object} response.Response{data=st.PayListResponse}
// @Failure 500 {object} response.Response
// @Router /app/pay/list [post]


//main.go
// @title 这里写标题`
// @version 1.0`
// @description 这里写描述信息`
// @termsOfService [http://swagger.io/terms/](http://swagger.io/terms/)`
// @contact.name 这里写联系人信息`
// @contact.url [http://www.swagger.io/support](http://www.swagger.io/support)`
// @contact.email support@swagger.io`
// @license.name Apache 2.0`
// @license.url [http://www.apache.org/licenses/LICENSE-2.0.html](http://www.apache.org/licenses/LICENSE-2.0.html)`
// @host 这里写接口服务的host`
// @BasePath 这里写base path`


//main.go
// @title API文档
// @version 1.0
// @description API 文档
// @host 127.0.0.01:8080
// @BasePath
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容