1. 装置
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
2. 样例
具体正文信息请参考
http://www.topgoer.com/%E5%85…
package main
import (
"github.com/gin-gonic/gin"
_ "golangdemo/docs"
"net/http"
)
var swagHandler gin.HandlerFunc
// @title xiayuedu backend api
// @version 1.0
// @description this is xiayuedu backend server
// @termsOfService https://xiayuedu.com
//
// @contact.name xiayuedu.com
// @contact.url https://xiayuedu.com
// @contact.name www.xiayuedu.com
//
// @contact.email
// @license.name Apache 2.0
// @license.url https://xiayuedu.com
// @host 127.0.0.1:8089
// @BasePath /api/v1
func main() {engine := gin.Default()
if swagHandler != nil {engine.GET("/swagger/*any",swagHandler)
}
v1 := engine.Group("/api/v1")
{v1.GET("/hello", HelloHandler)
}
engine.Run(":8089")
}
// @Summary hellohandler
// @Description hellohandler
// @Tags 测试
// @Accept json
// @Produce json
// @Param name query string true "名字"
// @Param age query string true "年龄"
// @Success 200 {string} string "{"msg":""hello razeen"}"
// @Failure 400 {string} string "{"msg":""who are you"}"
// @Router /hello [get]
func HelloHandler(ctx *gin.Context){name := ctx.Query("name")
age := ctx.Query("age")
if name == "" {ctx.JSON(http.StatusBadRequest,gin.H{"message":"who are you"})
return
}
ctx.JSON(http.StatusOK,gin.H{"message":"hello" + name + " " + age})
}
执行命令
swag init
init 之后,须要导入生成的包 _ "golangdemo/docs"
go run main.go
3. 生产环境不须要 swaggo 的文档
能够应用 go build -tags “dev” 来指定生成文档
定义一个全局变量
var swagHandler gin.HandlerFunc
func main() {
-----
if swagHandler != nil { // 如果不为 nil 才初始化
engine.GET("/swagger/*any",swagHandler)
}
-----
}
创立另外一个文件,指定 build tag
// +build dev
package main
import (
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "golangdemo/docs"
)
func init() {swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
}
go build 指定 tag 生产环境 build 不指定 tag
go build -tags "dev"
.\golangdemo.exe
后果