1 Star 1 Fork 0

kade/library

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
swagger.go 2.21 KB
一键复制 编辑 原始数据 按行查看 历史
kade 提交于 2024-04-22 17:14 . v1.2.6
package restful
import (
"gitee.com/go-kade/library/ioc"
"gitee.com/go-kade/library/ioc/apps/apidoc"
"gitee.com/go-kade/library/ioc/config/http"
"gitee.com/go-kade/library/ioc/config/log"
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/emicklei/go-restful/v3"
"github.com/rs/zerolog"
)
func init() {
ioc.Api().Registry(&SwaggerApiDoc{
ApiDoc: apidoc.ApiDoc{},
})
}
type SwaggerApiDoc struct {
ioc.ObjectImpl
log *zerolog.Logger
apidoc.ApiDoc
// Path string `json:"path" yaml:"path" toml:"path" env:"HTTP_API_DOC_PATH"`
}
func (h *SwaggerApiDoc) Name() string {
return apidoc.AppName
}
func (h *SwaggerApiDoc) Init() error {
h.log = log.Sub("api_doc")
return nil
}
func (i *SwaggerApiDoc) Priority() int {
return -100
}
func (h *SwaggerApiDoc) Registry(ws *restful.WebService) {
// 1.该 RESTful Web 服务可以产生 JSON 格式的响应
ws.Produces(restful.MIME_JSON)
//2.restfulspec.BuildSwagger() 方法使用这个配置来生成对应的 Swagger 文档
swagger := restfulspec.BuildSwagger(h.SwaggerDocConfig())
ws.Route(ws.GET("/").To(func(r *restful.Request, w *restful.Response) {
w.WriteAsJson(swagger)
}))
if h.Meta().CustomPathPrefix != "" {
h.log.Info().Msgf("Get the API Doc using %s", http.Get().ApiObjectAddrCustom(h))
} else {
h.log.Info().Msgf("Get the API Doc using %s", http.Get().ApiObjectAddr(h))
}
}
// API Doc config
func (h *SwaggerApiDoc) SwaggerDocConfig() restfulspec.Config {
return restfulspec.Config{
// 1.是用于获取当前已注册的 Web 服务列表的函数
WebServices: restful.RegisteredWebServices(),
// APIPath: "/swagger.json",
// APIPath: http.Get().ApiObjectPathPrefix(h),
PostBuildSwaggerObjectHandler: http.Get().SwagerDocs,
DefinitionNameHandler: func(name string) string {
if name == "state" || name == "sizeCache" || name == "unknownFields" {
return ""
}
return name
},
}
}
func (i *SwaggerApiDoc) Meta() ioc.ObjectMeta {
return DefaultObjectMeta1()
}
func DefaultObjectMeta1() ioc.ObjectMeta {
return ioc.ObjectMeta{
// CustomPathPrefix: "/s", 必须要/号 http://127.0.0.1:8080/s
CustomPathPrefix: "/swagger.json",
// CustomPathPrefix: "/s",
Extra: map[string]string{},
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/go-kade/library.git
git@gitee.com:go-kade/library.git
go-kade
library
library
v1.3.5

搜索帮助