1.先安裝Go對應的開源Swagger相關(guān)的庫
go get?github.com/swaggo/swag/cmd/swag
go get github.com/swaggo/gin-swagger
go get?github.com/swaggo/files
go get?github.com/alecthomas/template
2.驗證是否安裝成功:swag -v
3.針對接口寫入注解
// @Summary 獲取多個標簽
// @Tags 標簽
// @Produce? json
// @Param name query string false "標簽名稱" maxlength(100)
// @Param state query int false "狀態(tài)" Enums(0, 1) default(1)
// @Param page query int false "頁碼"
// @Param page_size query int false "每頁數(shù)量"
// @Success 200 {object} model.TagSwagger "成功"
// @Failure 400 {object} errcode.Error "請求錯誤"
// @Failure 500 {object} errcode.Error "內(nèi)部錯誤"
// @Router /api/v1/tags [get]
func (t Tag) List(c *gin.Context) {
}
// @Summary 新增標簽
// @Tags 標簽
// @Produce? json
// @Param name body string true "標簽名稱" minlength(3) maxlength(100)
// @Param state body int false "狀態(tài)" Enums(0, 1) default(1)
// @Param created_by body string false "創(chuàng)建者" minlength(3) maxlength(100)
// @Success 200 {object} model.Tag "成功"
// @Failure 400 {object} errcode.Error "請求錯誤"
// @Failure 500 {object} errcode.Error "內(nèi)部錯誤"
// @Router /api/v1/tags [post]
func (t Tag) Create(c *gin.Context) {
}
// @Summary 更新標簽
// @Tags 標簽
// @Produce? json
// @Param id path int true "標簽ID"
// @Param name body string false "標簽名稱" minlength(3) maxlength(100)
// @Param state body int false "狀態(tài) (0為未刪除、1為已刪除)" Enums(0, 1) default(1)
// @Param modified_by body string true "修改者" minlength(3) maxlength(100)
// @Success 200 {array} model.Tag "成功"
// @Failure 400 {object} errcode.Error "請求錯誤"
// @Failure 500 {object} errcode.Error "內(nèi)部錯誤"
// @Router /api/v1/tags/{id} [put]
func (t Tag) Update(c *gin.Context) {
}
4.針對整個項目進行注解,直接在main方法寫入如下注解
//@title 項目名稱
//@version 1.0
//@description 這里是描述
func main() {
5.生成執(zhí)行 swag init
這時會在我項目的docs文件夾下面生成docs.go、swagger.json、swagger.yaml三個文件
6.要在routers中進行默認初始化和注冊對應的路由:
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
同時要引用_"blog-service/docs",不然會報錯
7.查看接口文檔:http://localhost:9090/swagger/index.html
8.ok,完成