gin+gorm HelloWorld(为它加上Swagger)

为它加上Swagger

下载golang.org/x相关包
由于这些包需要科学上网才能下载,使用下面方式曲线救国:

mkdir -p $GOPATH/src/github.com/golang/
git clone https://github.com/golang/sys.git $GOPATH/src/github.com/golang/sys
git clone https://github.com/golang/net.git $GOPATH/src/github.com/golang/net
git clone https://github.com/golang/text.git $GOPATH/src/github.com/golang/text
git clone https://github.com/golang/lint.git $GOPATH/src/github.com/golang/lint
git clone https://github.com/golang/tools.git $GOPATH/src/github.com/golang/tools
git clone https://github.com/golang/crypto.git $GOPATH/src/github.com/golang/crypto

mkdir -p $GOPATH/src/golang.org
ln -s $GOPATH/src/github.com/golang $GOPATH/src/golang.org/x

go get -u github.com/swaggo/swag/cmd/swag

验证是否安装成功

swag -v
swag version v1.4.1

安装 gin-swagger

go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles

编写API注释
  • gin-swagger
  • swagger-doc
  • 其他参考文档
    Swagger 中需要将相应的注释或注解编写到方法上,再利用生成器自动生成说明文件

gin-swagger 给出的范例:

// @Summary Add a new pet to the store
// @Description get string by ID
// @Accept  json
// @Produce  json
// @Param   some_id     path    int     true        "Some ID"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]

我们可以参照 Swagger 的注解规范和范例去编写

// @Summary 新增文章标签
// @Produce  json
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param created_by query int false "CreatedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /api/v1/tags [post]
func AddTag(c *gin.Context) {
// @Summary 修改文章标签
// @Produce  json
// @Param id path int true "ID"
// @Param name query string true "ID"
// @Param state query int false "State"
// @Param modified_by query string true "ModifiedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /api/v1/tags/{id} [put]
func EditTag(c *gin.Context) {
生成

我们进入到gin-blog的项目根目录中,执行初始化命令
swag init
完毕后会在项目根目录下生成docs

docs/
├── docs.go
└── swagger
    ├── swagger.json
    └── swagger.yaml
效果

to be continued

你可能感兴趣的:(gin+gorm HelloWorld(为它加上Swagger))