swaggo自动生成Restful API文档
2020-06-25 本文已影响0人
炎鸿
1.安装swag
$ go get -u github.com/swaggo/swag/cmd/swag
2.添加注释
注释项:
titile: 文档标题
version: 版本
description、termsOfService、 contact 非必要声明。
license.name apache2.0。
host、 BasePath: 如果直接swagger调试API,需要填写正确,host为服务文档的端口ip,BasePath为基础路径, 这里是“/api/v1”。
还有securityDefinitions.basic、securityDefinitions.apikey等
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 me@razeen.me
// @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文档
// 进入项目根目录(即main.go所在)
$ cd proj
$ swag init
4.编译运行试试看
$ go mod init test
$ go build && ./test