- 安裝swag 工具
go get -u github.com/swaggo/swag/cmd/swag
- 在入口文件寫上項(xiàng)目的簡(jiǎn)介
package main
import (
"flag"
"open-api/internal/app/fund"
)
// @title 這里寫標(biāo)題`
// @version 1.0`
// @description 這里寫描述信息`
// @termsOfService [http://swagger.io/terms/](http://swagger.io/terms/)`
// @contact.name 這里寫聯(lián)系人信息`
// @contact.url [http://www.swagger.io/support](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](http://www.apache.org/licenses/LICENSE-2.0.html)`
// @host 這里寫接口服務(wù)的host`
// @BasePath 這里寫base path`
func main() {
var configPath string
flag.StringVar(&configPath, "config", "./configs", "config path")
flag.Parse()
fund.Run(configPath)
}
- 在你代碼中處理請(qǐng)求的接口函數(shù)(通常位于controller層)按如下方式寫上注釋:
// @Summary 支付列表
// @Description 獲取支付列表
// @Accept json
// @Produce json
// @param Authorization header string true "驗(yàn)證參數(shù)Bearer和token空格拼接"
// @Param body body st.PaySearch true "交款查詢參數(shù)"
// @Success 200 {object} response.Response{data=st.PayListResponse}
// @Failure 500 {object} response.Response
// @Router /app/pay/list [post]
func PayList(ctx *gin.Context) {
var (
paySearch st.PaySearch
data []st.PayListResponse
err error
)
if err := ctx.Bind(&paySearch); err != nil {
response.Failed(ctx, response.InvalidParams, response.GetMsg(response.InvalidParams), data, err)
return
}
data, err = logic.GetPayListNew(p)
if err != nil {
response.Failed(ctx, response.Error, response.GetMsg(response.Error), data, err)
return
}
response.Successed(ctx, response.Success, response.GetMsg(response.Success), data)
}
- 上面注釋中參數(shù)類型使用了
object
污淋,st.PaySearch
st.PayListResponse
response.Response
具體定義如下:
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type PayListResponse struct {
HouseBase
Id int `json:"id"`
Name string `json:"name"`
PayAmount decimal.Decimal `json:"pay_amount"`
PayArea decimal.Decimal `json:"pay_area"`
BankAccountingTime TimeShowDay `json:"bank_accounting_time"`
BankName string `json:"bank_name"`
AccountCode string `json:"account_code"`
BankCode string `json:"bank_code"`
}
type PaySearch struct {
Phone string `form:"phone" binding:"required,phoneValid"`
Status string `form:"status" binding:"required,oneof='0' '1'"`
}
- 生成文檔
swag init -g cmd/main.go // -g 指定main.go 的位置忍弛, 我這邊是在cmd文件中
此時(shí)目錄中多了docs
./docs
├── docs.go
├── swagger.json
└── swagger.yaml
image.png
- 引入gin-swagger渲染文檔數(shù)據(jù), 利用條件編譯來決定是否編譯swagger英上,因?yàn)榫€上運(yùn)行時(shí)弓乙,不需要swagger
image.png
doc_swag.go
// +build doc
package router
import (
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
func init() {
swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
}
swag.go 目前是空的
router.go
package router
import (
_ "open-api/docs"
"open-api/internal/app/fund/controller"
"open-api/internal/app/fund/middleware"
validator2 "open-api/pkg/validator"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
"github.com/gin-gonic/gin"
)
var swagHandler gin.HandlerFunc
func InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(middleware.Cors())
// 開啟swag
if swagHandler != nil {
r.GET("/swagger/*any", swagHandler)
}
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
_ = v.RegisterValidation("phoneValid", validator2.PhoneValidHook)
}
return r
}
- 在goland中配置build參數(shù)危纫,以便本地調(diào)試
image.png
至此就完成了盗忱。 如有問題請(qǐng)私信我凌唬。