一、下载swagger
- 安装swag
- https://github.com/swaggo/swag/releases/ 安装包
- chmod +x ./swag
- mv swag /usr/local/bin
- swag cli:go install github.com/swaggo/swag/cmd/swag@latest
- 安装gin-swagger
- go get github.com/swaggo/gin-swagger
- 安装swaggerfiles
- go get github.com/swaggo/gin-swagger/swaggerFiles
二、代码编写
- main()函数
import ( "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" _ "golib/docs" ) // @title golang api 框架 // @version 1.0 // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @host localhost:8080 // @BasePath / // @query.collection.format multi func main() { engine := gin.Default() engine.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler)) testGroup := engine.Group("/test") { testGroup.GET("/hello", HelloWorld) } engine.Run("8080") }
- controller
-
// List godoc // @Summary 测试helloworld // @Description 测试helloworld // @Tags 测试 // @Accept json // @Produce json // @Param name query string true "姓名" // @Success 200 {string} json "{"msg":"","code":200}" // @Failure 400 {string} json "{"msg":"","code":400}" // @Router /test/hello [get] func HelloWorld(ctx *gin.Context) { ctx.Json(http.StatusOK, gin.H{"msg":"hello world", "code":200}) }
-
三、初始化
- 如果main.go在根目录
- swag init
- 如果main.go 函数不在根目录,例如:inter/main.go
- swag init -g ./inter/main.go
- 会在根目录生成:docs/ 目录
- 访问方式
四、问题描述
- 访问的时候可能会报出:
- Fetch errorInternal Server Error doc.json
- 需要引入 docs目录才行
import (
"github.com/gin-gonic/gin" ginSwagger
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "gin-admin/docs"
)