为它加上Swagger

    要开发纯手写 API 文档,不存在的 :=)

    项目地址:

    1、go get

    $GOPATH/bin 没有加入$PATH中,你需要执行将其可执行文件移动到$GOBIN

    1. mv $GOPATH/bin/swag /usr/local/go/bin

    2、gopm get

    1. gopm get -g -v github.com/swaggo/swag/cmd/swag
    2. cd $GOPATH/src/github.com/swaggo/swag/cmd/swag
    3. go install

    同理将其可执行文件移动到$GOBIN

    安装 gin-swagger

    1. $ go get -u github.com/swaggo/gin-swagger

    注:三个包都有一定大小,安装需要等一会或要科学上网

    编写API注释

    Swagger 中需要将相应的注释或注解编写到方法上,再利用生成器自动生成说明文件

    gin-swagger 给出的范例:

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

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

    1. // @Produce json
    2. // @Param id param int true "ID"
    3. // @Param state query int false "State"
    4. // @Param modified_by query string true "ModifiedBy"
    5. // @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
    6. // @Router /api/v1/tags/{id} [put]
    7. func EditTag(c *gin.Context) {

    我们进入到gin-blog的项目根目录中,执行初始化命令

    1. [$ gin-blog]# swag init
    2. 2018/03/13 23:32:10 Generate swagger docs....
    3. 2018/03/13 23:32:10 Generate general API Info
    4. 2018/03/13 23:32:10 create docs.go at docs/docs.go

    完毕后会在项目根目录下生成docs

    我们可以检查 docs.go 文件中的 doc 变量,详细记载中我们文件中所编写的注解和说明

    验证

    大功告成,访问一下 http://127.0.0.1:8000/swagger/index.html, 查看 API 文档生成是否正确

    swagger

    本系列示例代码