swaggo自动生成Restful API文档

1.安装swag

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

2.添加注释

注释项:
titile: 文档标题
version: 版本
descriptiontermsOfServicecontact 非必要声明。
license.name apache2.0。
hostBasePath: 如果直接swagger调试API,需要填写正确,host为服务文档的端口ip,BasePath为基础路径, 这里是“/api/v1”。
还有securityDefinitions.basicsecurityDefinitions.apikey

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
    _ "test/docs" // docs is generated by Swag CLI, you have to import it.
    "github.com/iris-contrib/swagger/swaggerFiles"
    "github.com/iris-contrib/swagger/v12"
    "github.com/kataras/iris/v12"
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://localhost
// @contact.name Razeen
// @contact.url https://razeen.me
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
func main() {
  app := iris.new()
  swgCfg := &swagger.Config{
        URL: "http://localhost:8080/swagger/doc.json",
  }
  // use swagger middleware to
  app.Get("/swagger/{any:path}", swagger.CustomWrapHandler(swgCfg, swaggerFiles.Handler))
  v1 := app.Party("/api/v1")
  v1.Get("/test", testHandle)
  app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

// @Summary test
// @Description say Hello
// @Tags 测试
// @Accept mpfd
// @Produce json
// @Param arg query string true "name"
// @Success 200 {string} json "{"msg": "hello Kity"}"
// @Failure 400 {string} json "{"msg": "arg is null"}"
// @Router /test [get]
func testHandle(ctx *iris.Context) {
    arg := ctx.URLParam("arg")
    if arg == "" {
        ctx.StatusCode(iris.StatusBadRequest)
        ctx.JSON(iris.Map{"msg": "arg is null"})
    } else {
        ctx.StatusCode(iris.StatusOK)
        ctx.JSON(iris.Map{"msg": "Hello "+ arg})
    }
}

3.生成(更新)api文档

1
2
3
// 进入项目根目录(即main.go所在)
$ cd proj
$ swag init

4.编译运行试试看

1
2
$ go mod init test
$ go build && ./test

浏览器查看http://localhost:8080/swagger/index.html