- 整合swagger 文档https://github.com/swaggo/gin-swagge
- 下载依赖
go get github.com/swaggo/swag/cmd/swag go get github.com/swaggo/gin-swagger go get github.com/swaggo/files
- 创建文件
main.go注意
package main import ( "fmt" "net/http" _ "go_work/gin/swagger/docs" // swag init 生成的docs "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" ) type UserDTO struct { Id string `json:"id"` Name string `json:"name"` Age int `json:"age"` } type WebVo struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } func main() { engine := gin.Default() // 使用swagger中间件 engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) engine.POST("addUser", addUserHandler) engine.GET("getUser", getUserHandler) engine.Run(":9009") } // @Tags 添加用户 // @Summary 添加用户 // @Description 添加用户 // @Accept json // @Produce json // @Param id formData string true "用户id" // @Param name formData string true "用户名" // @Param age formData int false "年龄" // @Success 200 {string} json "{"code":200,"msg":"ok"}" // @Router /addUser [post] func addUserHandler(c *gin.Context) { // 绑定参数 var dto UserDTO err := c.BindQuery(&dto) if err != nil { c.JSON(http.StatusBadRequest, "绑定失败") return } vo := WebVo{ Code: 0, Msg: "添加成功", Data: nil, } c.JSON(http.StatusOK, vo) } // @Tags 查询用户 // @Summary 查询用户 // @Description 通过id查询用户 // @Accept json // @Produce json // @Param id query string true "用户id" // @Success 200 {string} json "{"code":200,"msg":"ok","data":"{"id":""123456,"name":"admin","age":18}"}" // @Router /getUser [get] func getUserHandler(c *gin.Context) { id := c.Query("id") fmt.Println(id) vo := WebVo{ Code: 0, Msg: "查询成功", Data: UserDTO{Id: id, Name: "admin", Age: 18}, } c.JSON(http.StatusOK, vo) }
- 初始化swagger
// 如****/swagger/main.go, 则需要在****/swagger目录下执行 swag init
执行成功后,会在当前文件目录下生成docs文件 - 引入docs
在main.go引入docs包
- 测试
- 完成