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
具體註釋信息請參考
http://www.topgoer.com/%E5%85...html
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}) }
執行命令git
swag init init以後,須要導入生成的包 _ "golangdemo/docs" go run main.go
能夠使用go build -tags "dev" 來指定生成文檔
定義一個全局變量github
var swagHandler gin.HandlerFunc func main() { ----- if swagHandler != nil { //若是不爲nil才初始化 engine.GET("/swagger/*any",swagHandler) } ----- }
建立另一個文件,指定build taggolang
// +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不指定tagjson
go build -tags "dev" .\golangdemo.exe
結果
segmentfault