1.安装 swag

go get github.com/swaggo/swag/cmd/swag
swag 用于生成 docs 文件夹(swagger文档程序使用)

安装完成后会在 ${GOPATH}/bin生成一个执行文件

2.编写代码

/**
* Created by liuyusnhengsir on 23/01/2022
*/

package main

import (
_ "lys_gin_swag/docs"

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

// @title lys_gin_swag微服务api
// @version 0.0.1
// @description lys_gin_swag微服务 code by 刘云生
// @BasePath /
func main() {
r := gin.New()

// 创建路由组
v1 := r.Group("/api/v1")

v1.GET("/sayHello/:name", sayHello)

v2 := r.Group("/api/v2")

v2.GET("/sayHello/:name", sayHello2)

// 文档界面访问URL
// http://127.0.0.1:8080/swagger/index.html
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

r.Run(":8080")
}

// @sayHello
// @Description sayHello
// @Accept json
// @Produce json
// @Param name path string true "name"
// @Success 200 {string} string "name,helloWorld"
// @Router /api/v1/sayHello/{name} [get]
func sayHello(c *gin.Context) {
name := c.Param("name")

c.JSON(200, gin.H{
"describe": "this is /api/v1 ",
"name": name,
})
}

// @sayHello2
// @Description sayHello2
// @Accept json
// @Produce json
// @Param name path string true "name"
// @Success 200 {string} string "name,helloWorld"
// @Router /api/v2/sayHello/{name} [get]
func sayHello2(c *gin.Context) {
name := c.Param("name")

c.JSON(200, gin.H{
"describe": "this is /api/v2",
"action": name,
})
}

3.swag init

执行 swag init

go集成gin+swagger_golang


go集成gin+swagger_golang_02

4.运行效果

go run main.go

进入 http://127.0.0.1:8080/swagger/index.html 查看文档

go集成gin+swagger_json_03