golang 生成swagger 文档
2023-02-18 16:50 糯米粥 阅读(159) 评论(0) 编辑 收藏 举报
github:
https://github.com/swaggo/swag/blob/master/README_zh-CN.md
参考:https://www.cnblogs.com/cxykhaos/p/15345317.html
第一步:下载swag
命令:go install github.com/swaggo/swag/cmd/swag@latest
通过swag -v 查看命令
通过swag init 生成文档
项目结构:
controller -》 user.go

package controller import ( "github.com/gin-gonic/gin" "net/http" "strconv" "swagger/model" ) // @Summary 用户服务 (摘要) // @Description 用户服务2 // @Tags 用户服务 // @Accept mpfd // @Produce json // @Param Id query int true "用户id" // @Success 200 {object} model.User // @Failure 400 {string} string "{"msg": "who are you"}" // @Router /GetUserById [get] func GetUserById(c *gin.Context) { userId, _ := strconv.Atoi(c.Query("Id")) c.JSON(http.StatusOK, gin.H{ "code": 200, "msg": "success", "data": model.User{ Id: userId, UserName: "tom", Mobile: "15888888888", }, }) return }
model -> user.go

package model import "github.com/gofrs/uuid" type User struct { Id int /*主键*/ UserName string //用户名 Mobile string //手机号码 UUID uuid.UUID }
main.go
要引入doc

package main import ( "github.com/gin-gonic/gin" "github.com/swaggo/files" "github.com/swaggo/gin-swagger" "swagger/controller" _ "swagger/docs" ) // gin-swagger middleware // swagger embed files // @title Swagger Example API // @version 1.0 // @description This is a sample server celler server. // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:8080 // @BasePath /api/v1 // @securityDefinitions.basic BasicAuth func main() { ///////////// r := gin.Default() //c := controller.NewController() v1 := r.Group("/api/v1") { v1.GET("/GetUserById", controller.GetUserById) //accounts := v1.Group("/accounts") //{ // //accounts.GET(":id", controller.HandleHello) // accounts.GET("/GetUserById", controller.GetUserById) // //accounts.GET("", c.ListAccounts) // //accounts.POST("", c.AddAccount) // //accounts.DELETE(":id", c.DeleteAccount) // //accounts.PATCH(":id", c.UpdateAccount) // //accounts.POST(":id/images", c.UploadAccountImage) //} //... } r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) r.Run(":8080") }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
2019-02-18 Centos7安装Docker
2013-02-18 收集一些常用的正则表达式【转载】