1.装置
swag cli : go get -u github.com/swaggo/swag/cmd/swaggin-swagger 中间件: go get github.com/swaggo/gin-swaggerswagger 内置文件: go get github.com/swaggo/gin-swagger/swaggerFiles
2.样例
具体正文信息请参考
http://www.topgoer.com/%E5%85...
package mainimport ( "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/v1func 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 initinit之后,须要导入生成的包 _ "golangdemo/docs"go run main.go
3.生产环境不须要swaggo的文档
能够应用go build -tags "dev" 来指定生成文档
定义一个全局变量
var swagHandler gin.HandlerFuncfunc main() { ----- if swagHandler != nil { //如果不为nil才初始化 engine.GET("/swagger/*any",swagHandler) } -----}
创立另外一个文件,指定build tag
// +build dev package mainimport ( 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
后果