安装swaggo
go install github.com/swaggo/swag/cmd/swag@latest
编写swag
import ("github.com/gin-gonic/gin""goWeb/internal/service""goWeb/model/response"
)// UserRouter 路由
func UserRouter(ctx *gin.RouterGroup) {ctx.GET("/login", login)ctx.POST("/addUser", addUser)ctx.GET("/delUser/:id", delUser)ctx.GET("/getUser", getUser)ctx.GET("/pageUser", pageUser)
}// Login
//
// @Description Java学习Golang开发
// @Tags user接口
// @Router /user/login [get]
func login(ctx *gin.Context) {response.Success(ctx, service.Login())
}// @Description 添加用户信息
// @Tags user接口
// @Param user body model.User true "用户实体"
// @Success 200 {string} string "success"
// @Failure 500 {string} string "fail"
// @Router /user/addUser [post]
func addUser(ctx *gin.Context) {response.Success(ctx, service.AddUser(ctx))
}// @Description 删除用户
// @Tags user接口
// @Param id path int true "用户id"
// @Router /user/delUser/{id} [get]
func delUser(ctx *gin.Context) {service.DelUser(ctx)response.Ok(ctx)
}// @Description 删除用户
// @Tags user接口
// @Param id query int true "用户id"
// @Router /user/getUser [get]
func getUser(ctx *gin.Context) {response.Success(ctx, service.GetUser(ctx))
}// @Description 分页查询用户数据
// @Tags user接口
// @Param page query int false "当前页码"
// @Param pageSize query int false "每页数量"
// @Router /user/pageUser [get]
func pageUser(ctx *gin.Context) {response.Success(ctx, service.PageUser(ctx))
}
启动类
import (swaggerFiles "github.com/swaggo/files" // swagger embed filesginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware_ "goWeb/docs"
)// @title Swagger Example API
// @version 1.0
// @description go web 框架gin集成swagger.
// @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// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {}
初始化doc
swag init
访问
http://127.0.0.1:8081/swagger/index.html#/
更多
请探索官网
swag package - github.com/swaggo/swag/v2 - Go Packages