Skip to content

Commit

Permalink
integration swagger
Browse files Browse the repository at this point in the history
  • Loading branch information
yoyofx committed Feb 5, 2024
1 parent ede023e commit e456b9c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
7 changes: 6 additions & 1 deletion examples/simpleweb/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,12 @@ func registerEndpointRouterConfig(rb router.IRouterBuilder) {
endpoints.UseLiveness(rb)
endpoints.UseJwt(rb)
endpoints.UseRouteInfo(rb)
endpoints.UseSwaggerDoc(rb, swagger.Info{Title: "simple web swagger", Version: "10.0.0", Description: "尝试对接swagger文档"})
endpoints.UseSwaggerDoc(rb,
swagger.Info{
Title: "YoyoGO 框架文档演示",
Version: "1.0.0 beta",
Description: "框架文档演示swagger文档 1.0",
})

rb.GET("/error", func(ctx *context.HttpContext) {
panic("http get error")
Expand Down
2 changes: 1 addition & 1 deletion pkg/swagger/swagger_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ type Path struct {
Summary string `json:"summary"`
Description string `json:"description"`
OperationId string `json:"operationId"`
Parameters []Parameters `json:"parameters"`
Parameters interface{} `json:"parameters,omitempty"`
RequestBody RequestBody `json:"requestBody,omitempty"`
Responses map[string]ResponsesItem `json:"responses"`
Security []Security `json:"security"`
Expand Down
27 changes: 17 additions & 10 deletions web/endpoints/swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,25 @@ func UseSwaggerDoc(router router.IRouterBuilder, info swagger.Info) {
xlog.GetXLogger("Endpoint").Debug("loaded swagger ui endpoint.")

// swagger.json
router.GET("/swagger.json", func(ctx *context.HttpContext) {
router.GET("/resources/swagger.json", func(ctx *context.HttpContext) {
var env *abstractions.HostEnvironment
_ = ctx.RequiredServices.GetService(&env)

openapi := &swagger.OpenApi{
Openapi: "3.1.0",
Openapi: "3.0.0",
Paths: make(map[string]map[string]swagger.Path)}
openapi.Info = info
GetSwaggerRouteInfomation(openapi, router, env)
ctx.JSON(200, openapi)
})

// swagger ui
router.GET("/swagger", func(ctx *context.HttpContext) {
router.GET("/resources/swagger", func(ctx *context.HttpContext) {
var env *abstractions.HostEnvironment
_ = ctx.RequiredServices.GetService(&env)
serverPath := env.MetaData["server.path"]
// swagger json address
swaggerJsonUri := fmt.Sprintf("/%s/resources/swagger.json", serverPath)
swaggerUIHTML := `<!DOCTYPE html>
<html lang="en">
<head>
Expand All @@ -42,16 +47,16 @@ func UseSwaggerDoc(router router.IRouterBuilder, info swagger.Info) {
content="SwaggerUI"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.0.0/swagger-ui.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.11.2/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.0.0/swagger-ui-bundle.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.0.0/swagger-ui-standalone-preset.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.11.2/swagger-ui-bundle.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.11.2/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'http://localhost:8080/app/swagger.json',
url: '%s',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
Expand All @@ -63,6 +68,7 @@ func UseSwaggerDoc(router router.IRouterBuilder, info swagger.Info) {
</script>
</body>
</html>`
swaggerUIHTML = fmt.Sprintf(swaggerUIHTML, swaggerJsonUri)
ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
_, _ = ctx.Output.Write([]byte(swaggerUIHTML))
ctx.Output.SetStatus(200)
Expand All @@ -79,12 +85,12 @@ func GetSwaggerRouteInfomation(openapi *swagger.OpenApi, router router.IRouterBu
}

func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.OpenApi, env *abstractions.HostEnvironment) {
//serverPath := env.MetaData["server.path"]
serverPath := env.MetaData["server.path"]
mvcTemplate := env.MetaData["mvc.template"]
// mvc
mvcTemplate = strings.ReplaceAll(mvcTemplate, "{controller}", "%s")
mvcTemplate = strings.ReplaceAll(mvcTemplate, "{action}", "%s")
mvcTemplate = fmt.Sprintf("/%s/", mvcTemplate)
mvcTemplate = fmt.Sprintf("/%s/%s", serverPath, mvcTemplate)

suf := len(controller.ControllerName) - 10
controllerName := controller.ControllerName[0:suf]
Expand Down Expand Up @@ -146,6 +152,7 @@ func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.Ope
}
if act.IsAttributeRoute {
actPath = act.Route.Template
actPath = fmt.Sprintf("/%s%s", serverPath, actPath)
// used regexp ,replace :id to {id}
reg := regexp.MustCompile(`:[a-zA-Z0-9]+`)
actPath = reg.ReplaceAllString(actPath, "{$0}")
Expand All @@ -159,7 +166,7 @@ func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.Ope

if responseType != nil && responseType.Kind() == reflect.Struct {
// struct , ApiResult , ApiDocResult[?]
println(responseType.Name())
// println(responseType.Name())
// new struct type to object
responseObject := reflect.New(responseType).Elem().Interface()

Expand Down

0 comments on commit e456b9c

Please sign in to comment.