Demo
官方文档https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html
main:
// main:
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore 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 petstore.swagger.io
// @BasePath /v2
func main() {
http.HandleFunc("/testapi/get-string-by-int/", api.GetStringByInt)
http.HandleFunc("//testapi/get-struct-array-by-string/", api.GetStructArrayByString)
http.HandleFunc("/testapi/upload", api.Upload)
http.ListenAndServe(":8080", nil)
}
query string:
// query string:
// GetPostListHandler 获取帖子列表的接口升级版
// 根据前端传来的参数动态的获取帖子列表
// 按创建时间排序,或者按照分数排序
// 1.获取参数
// 2.去redis查询id列表
// 3.根据id去数据库查询帖子详细信息
// @Summary 升级版根据page, size, score获取帖子
// @Description 升级版根据page, size, score获取帖子
// @Tags 帖子相关接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer JWT"
// @Param object query models.ParamPostList false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
// @Router /posts2 [get]
func GetPostListHandler(c *gin.Context) {
// GET请求参数:/api/v1/posts2?page=1&size=10&order=time
// 初始化结构体时指定初始参数
// 一定要取地址
p := &models.ParamPostList{
Page: models.OrderPage,
Size: models.OrderSize,
Order: models.OrderTime,
}
if err := c.ShouldBindQuery(p); err != nil {
zap.L().Error("GetPostListHandler with invalid params", zap.Error(err))
ResponseError(c, CodeInvalidParam)
return
}
//offset, limit := getPageInfo(c)
// 获取数据
data, err := logic.GetPostList2(p)
//fmt.Println("----------------------", data)
if err != nil {
zap.L().Error("logic.GetPostList() failed:", zap.Error(err))
ResponseError(c, CodeServerBusy)
return
}
// 返回响应
ResponseSuccess(c, data)
}
post:
// post:
// CreatePostHandler 创建帖子的处理函数
// @Summary 创建帖子
// @Description 创建帖子
// @Tags 帖子相关接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string true "Bearer 用户令牌"
// @Param object message body _RequestCreatePost false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
// @Router /post [post]
func CreatePostHandler(c *gin.Context) {
// 获取参数校验
p := new(models.Post)
if err := c.ShouldBindJSON(p); err != nil {
zap.L().Debug("c.ShouldBindJSON() error", zap.Any("err", err))
zap.L().Error("create post with invalid param")
ResponseError(c, CodeInvalidParam)
return
}
// 从c中取到当前发请求的用户id值
uid, err := GetCurrentUser(c)
if err != nil {
ResponseError(c, CodeServerBusy)
return
}
p.AuthorID = uid
//fmt.Println("controllers.post:", uid)
// 创建帖子
if err := logic.CreatePost(p); err != nil {
zap.L().Error("logic.CreatePost failed", zap.Error(err))
ResponseError(c, CodeServerBusy)
return
}
// 返回响应
ResponseSuccess(c, nil)
}
结构体
// _ResponsePostList 用于存放文档中用到的model
// 此结构体用于存放文档中用到的model
// 因为接口文档返回的数据都是一致的,但是具体的data类型不一致
type _ResponsePostList struct {
Code ResCode `json:"code"`
Message string `json:"message"`
Data []*models.ApiPostDetail `json:"data"`
}
// _RequestCreatePost post请求,创建结构体的struct
type _RequestCreatePost struct {
CommunityID int64 `json:"community_id" db:"community_id" binding:"required"`
Title string `json:"title" db:"title" binding:"required"`
Content string `json:"content" db:"content" binding:"required"`
}
安装
go get
go get -u github.com/swaggo/swag/cmd/swag
初始化
swag init
没问题的话会生成一个文件夹
./docs
├── docs.go
├── swagger.json
└── swagger.yaml
引入文件
import (
// liwenzhou.com ...
_ "skyfall/docs" // 千万不要忘了导入把你上一步生成的docs
gs "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
加入一条路由
r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))
访问
http://127.0.0.1:8081/swagger/index.html
官方Demo
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
)
// PingExample godoc
// @Summary ping example
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} string "pong"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/ping [get]
func (c *Controller) PingExample(ctx *gin.Context) {
ctx.String(http.StatusOK, "pong")
}
// CalcExample godoc
// @Summary calc example
// @Description plus
// @Tags example
// @Accept json
// @Produce json
// @Param val1 query int true "used for calc"
// @Param val2 query int true "used for calc"
// @Success 200 {integer} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/calc [get]
func (c *Controller) CalcExample(ctx *gin.Context) {
val1, err := strconv.Atoi(ctx.Query("val1"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
val2, err := strconv.Atoi(ctx.Query("val2"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
ans := val1 + val2
ctx.String(http.StatusOK, "%d", ans)
}
// PathParamsExample godoc
// @Summary path params example
// @Description path params
// @Tags example
// @Accept json
// @Produce json
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
func (c *Controller) PathParamsExample(ctx *gin.Context) {
groupID, err := strconv.Atoi(ctx.Param("group_id"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
accountID, err := strconv.Atoi(ctx.Param("account_id"))
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
ctx.String(http.StatusOK, "group_id=%d account_id=%d", groupID, accountID)
}
// HeaderExample godoc
// @Summary custome header example
// @Description custome header
// @Tags example
// @Accept json
// @Produce json
// @Param Authorization header string true "Authentication header"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/header [get]
func (c *Controller) HeaderExample(ctx *gin.Context) {
ctx.String(http.StatusOK, ctx.GetHeader("Authorization"))
}
// SecuritiesExample godoc
// @Summary custome header example
// @Description custome header
// @Tags example
// @Accept json
// @Produce json
// @Param Authorization header string true "Authentication header"
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Security ApiKeyAuth
// @Security OAuth2Implicit[admin, write]
// @Router /examples/securities [get]
func (c *Controller) SecuritiesExample(ctx *gin.Context) {
}
// AttributeExample godoc
// @Summary attribute example
// @Description attribute
// @Tags example
// @Accept json
// @Produce json
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Success 200 {string} string "answer"
// @Failure 400 {string} string "ok"
// @Failure 404 {string} string "ok"
// @Failure 500 {string} string "ok"
// @Router /examples/attribute [get]
func (c *Controller) AttributeExample(ctx *gin.Context) {
ctx.String(http.StatusOK, fmt.Sprintf("enumstring=%s enumint=%s enumnumber=%s string=%s int=%s default=%s",
ctx.Query("enumstring"),
ctx.Query("enumint"),
ctx.Query("enumnumber"),
ctx.Query("string"),
ctx.Query("int"),
ctx.Query("default"),
))
}
// PostExample godoc
// @Summary post request example
// @Description post request example
// @Accept json
// @Produce plain
// @Param message body model.Account true "Account Info"
// @Success 200 {string} string "success"
// @Failure 500 {string} string "fail"
// @Router /examples/post [post]
func (c *Controller) PostExample(ctx *gin.Context) {
}