省流版:这是一个用go 代码生成swagger/openApi文档的库,不需要写注释!;这个库基于
go-openapi,可以嵌入到web项目中。文档连接
安装: go get -u github.com/the-pawn-2017/r5t
为什么写这个软件
- 我想实现很多的特性,比如支持Gin和Echo的集成、分页、OAuth2。
- 我真的需要这个库,所以我有动力去写、去维护。
version
v0.5
TODO
- ✅ 支持所有OpenApi的组件(req,res,param等)
- ✅ 支持结构体注册,res,req中均中直接注册
- ✅ 支持OAuth2验证
- 🚧 完全的测试代码
- 🚧 完全的文档
- ✅ 支持web服务器嵌入,如echo 在这里可以看到
example/echo
一些有用的特性
1. 快捷分页
s := r5t.NewSpec(spec.Title("pagination.yaml"))
s.Get("/test-pagination").PageInQuery("page", 1, "pageSize", 10).ResString(http.StatusOK, res.Example("hi"))
2. 快捷使用OAuth2
s := spec.NewSpec()
s.Security(
security.WithOAuth2Code("ziteal", "http://10.45.8.189:8080/oauth/v2/authorize", "http://10.45.8.189:8080/oauth/v2/token",
security.AddScope("openid", "OPENID IS USING FOR ID")),
)
3. 精练有效的API, 如 Reqjson,ResJson,ResString.
s := r5t.NewSpec(spec.Title("example reqString"))
s.Get("/test-resString").ResString(http.StatusOK, res.Example("hi!"))
example:
在此目录下看一些例子 /examples/spec_test
type Test struct {
A string
B string `validate:"required"`
}
s := spec.NewSpec()
s.Security(
security.WithOAuth2Code("ziteal", "http://10.45.8.189:8080/oauth/v2/authorize", "http://10.45.8.189:8080/oauth/v2/token",
security.AddScope("openid", "OPENID IS USING FOR ID")),
)
// than, you can use OAuth2 code mode now
s.Post("/gkd").NeedSecurify("ziteal", []string{"openid"}).
ReqJSON(model.ModelOf[Test](), req.WithExample(Test{A: "A", B: "B"})).
ResJSON(http.StatusOK, model.ModelOf[Test](), res.WithExample(Test{A: "A", B: "B"}))
embed swagger-ui
package main
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/the-pawn-2017/r5t"
"github.com/the-pawn-2017/r5t/model"
"github.com/the-pawn-2017/r5t/req"
"github.com/the-pawn-2017/r5t/res"
"github.com/the-pawn-2017/r5t/security"
"github.com/the-pawn-2017/r5t/swaggerui"
)
type TestBasic struct {
A string
B string `validate:"required"`
}
func main() {
e := echo.New()
e.Use(middleware.Logger())
s := r5t.NewSpec()
s.Security(
security.OAuth2Code("ziteal", "http://10.45.8.189:8080/oauth/v2/authorize", "http://10.45.8.189:8080/oauth/v2/token",
security.AddScope("openid", "OPENID IS USING FOR ID")),
).
Post("/gkd").NeedSecurify("ziteal", []string{"openid"}).
ReqJSON(model.ModelOf[TestBasic](), req.Example(TestBasic{A: "A", B: "B"})).
ResJSON(http.StatusOK, model.ModelOf[TestBasic](), res.Example(TestBasic{A: "A", B: "B"}))
e.GET("/swagger-test.json", func(c echo.Context) error {
re, err := swaggerui.GenSpec(s)
if err == nil {
return c.JSONBlob(http.StatusOK, re)
} else {
return c.String(http.StatusInternalServerError, err.Error())
}
})
e.GET("/swagger/*", func(c echo.Context) error {
paramStr := c.Param("*")
kind, content, err := swaggerui.GetSwaggerUIFile("/swagger-test.json", paramStr)
if err == nil {
return c.Blob(http.StatusOK, kind, content)
}
return c.String(http.StatusInternalServerError, err.Error())
})
e.Start(":2333")
}
尽管快开发好了,但是还是不要直接在正式项目中使用
被 a-h/rest项目启发