Gloang Swagger——自动生产接口文档

功能

自动生产接口文档

安装

# 安装swag
go get -u github.com/swaggo/swag/cmd/swag # 安装 gin-swagger go get -u github.com/swaggo/gin-swagger go get -u github.com/swaggo/gin-swagger/swaggerFiles

编写API注释

例1-新增

// @Summary 新增文章标签
// @Produce  json
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param created_by query string false "CreatedBy"
// @Success 200 {object} app.Response
// @Success 500 {object} app.Response
// @Router /api/tags [post]
func AddTag(c *gin.Context) {
...
}

例2-编辑

// @Summary 编辑文章标签
// @Produce  json
// @Param id path int true "ID"
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param modified_by query string false "ModifiedBy"
// @Success 200 {object} app.Response
// @Success 500 {object} app.Response
// @Router /api/tags/{id} [put]
func EditTag(c *gin.Context) {
...
}

参数格式说明

@Param state query int false "State"

@Params 实际参数 query/path 类型 是否必须 别名

路由中初始化

package routers

import (
    ...

    _ "your_module_name/docs"

    ...
)

// InitRouter initialize routing information
func InitRouter() *gin.Engine {
    ...
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    ...

    return r
}

生成

在项目根目录执行

swag init

执行完后,生成

获取在线接口文档

 http://127.0.0.1:8000/swagger/index.html

原文地址:https://www.cnblogs.com/kaituorensheng/p/12274956.html