Skip to content

Commit

Permalink
assemble swagger api json
Browse files Browse the repository at this point in the history
  • Loading branch information
yoyofx committed Jan 29, 2024
1 parent eb83e32 commit 9ce784e
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 28 deletions.
4 changes: 2 additions & 2 deletions examples/simpleweb/contollers/dbcontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
)

type DbController struct {
mvc.ApiController
dbConfig configuration.OptionsSnapshot[models.MyConfig]
mvc.ApiController `doc:"数据库接口Controller"`
dbConfig configuration.OptionsSnapshot[models.MyConfig]
}

func NewDbController(snapshotOptions configuration.OptionsSnapshot[models.MyConfig]) *DbController {
Expand Down
2 changes: 1 addition & 1 deletion examples/simpleweb/contollers/hubcontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (

// websocket hub
type HubController struct {
mvc.ApiController
mvc.ApiController `doc:"websocket hub controller"`

hub *hubs.Hub
redisClient *redisdb.RedisDataSource
Expand Down
2 changes: 1 addition & 1 deletion examples/simpleweb/contollers/sdcontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

type SDController struct {
mvc.ApiController
mvc.ApiController `doc:"服务发现接口Controller"`
discoveryCache servicediscovery.Cache
discoveryClient servicediscovery.IServiceDiscoveryClient
discoverySelector servicediscovery.ISelector
Expand Down
2 changes: 1 addition & 1 deletion examples/simpleweb/contollers/usercontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

type UserController struct {
mvc.ApiController `route:"user"`
mvc.ApiController `route:"user" doc:"用户接口Controller"`

userAction models.IUserAction
discoveryClient servicediscovery.IServiceDiscovery
Expand Down
2 changes: 2 additions & 0 deletions pkg/swagger/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ package swagger
type OpenApi struct {
Openapi string `json:"openapi"`
Info Info `json:"info"`
Servers []Server `json:"servers"`
Tags []Tag `json:"tags"`
Paths map[string]map[string]Path `json:"paths"`
}
13 changes: 13 additions & 0 deletions pkg/swagger/swagger_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,16 @@ type License struct {
Name string `json:"name"`
Url string `json:"url"`
}

type Server struct {
Url string `json:"url"`
}

type Tag struct {
Name string `json:"name"`
Description string `json:"description"`
//ExternalDocs struct {
// Description string `json:"description"`
// Url string `json:"url"`
//}
}
32 changes: 15 additions & 17 deletions web/endpoints/swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,27 @@ import (
"strings"
)

func GetAllController(router router.IRouterBuilder) map[string]map[string]swagger.Path {
func GetSwaggerRouteInfomation(openapi *swagger.OpenApi, router router.IRouterBuilder) {
builder := router.GetMvcBuilder()
controllerList := builder.GetControllerDescriptorList()
pathMap := make(map[string]map[string]swagger.Path)
for _, controller := range controllerList {
FilterValidParams(controller, pathMap)
FilterValidParams(controller, openapi)
}
return pathMap
}

func FilterValidParams(controller mvc.ControllerDescriptor, pathMap map[string]map[string]swagger.Path) map[string]map[string]swagger.Path {
func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.OpenApi) {
suf := len(controller.ControllerName) - 10
basePath := controller.ControllerName[0:suf]
controllerName := controller.ControllerName[0:suf]
openapi.Tags = append(openapi.Tags, swagger.Tag{Name: controller.ControllerName, Description: controller.Descriptor})
for _, act := range controller.GetActionDescriptors() {
// 遍历 action, 拼接api路径 swagger.Path
actPath := "/" + basePath + "/" + act.ActionName[len(act.ActionMethod):]

actionName := strings.ReplaceAll(strings.ToLower(act.ActionName), act.ActionMethod, "")
actPath := "/" + controllerName + "/" + actionName
pathInfoMap := make(map[string]swagger.Path)
pathMap[actPath] = pathInfoMap
openapi.Paths[actPath] = pathInfoMap
pathInfo := swagger.Path{}

pathInfo.Tags = []string{controller.ControllerName}
// action params
if len(act.MethodInfo.Parameters) > 0 {
for _, param := range act.MethodInfo.Parameters {
Expand Down Expand Up @@ -72,7 +73,6 @@ func FilterValidParams(controller mvc.ControllerDescriptor, pathMap map[string]m
pathInfoMap[act.ActionMethod] = pathInfo

}
return pathMap
}

func RequestBody(param reflectx.MethodParameterInfo) swagger.RequestBody {
Expand Down Expand Up @@ -101,15 +101,13 @@ func RequestBody(param reflectx.MethodParameterInfo) swagger.RequestBody {

func UseSwaggerUI(router router.IRouterBuilder, f func() swagger.Info) {
xlog.GetXLogger("Endpoint").Debug("loaded swagger ui endpoint.")
openapi := swagger.OpenApi{}
openapi.Openapi = "3.0.3"
openapi := &swagger.OpenApi{
Openapi: "3.0.3",
Paths: make(map[string]map[string]swagger.Path)}
openapi.Info = f()
router.GET("/swagger.json", func(ctx *context.HttpContext) {
pathMap := GetAllController(router)
openapi.Paths = pathMap
//marshal, _ := json.Marshal(&openapi)
//swaggerJson := marshal
ctx.JSON(200, openapi) //.Render(200, actionresult.Data{ContentType: "application/json; charset=utf-8", Data: []byte(swaggerJson)})
GetSwaggerRouteInfomation(openapi, router)
ctx.JSON(200, openapi)
})

router.GET("/swagger", func(ctx *context.HttpContext) {
Expand Down
9 changes: 6 additions & 3 deletions web/mvc/controller_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ func (builder *ControllerBuilder) AddController(controllerCtor interface{}) {
controllerName, controllerType := reflectx.GetCtorFuncOutTypeName(controllerCtor)
controllerName = strings.ToLower(controllerName)
// Create Controller and Action descriptors
descriptor := NewControllerDescriptor(controllerName, controllerType, controllerCtor)
builder.mvcRouterHandler.ControllerDescriptors[controllerName] = descriptor
descriptor, err := NewControllerDescriptor(controllerName, controllerType, controllerCtor)
logger.Debug("add mvc controller: [%s]", controllerName)

if err != nil {
logger.Error(err.Error())
return
}
builder.mvcRouterHandler.ControllerDescriptors[controllerName] = descriptor
// add routes for action attributes
controllerAttr := controllerType.Field(0).Tag.Get("route")
if controllerAttr != "" {
Expand Down
14 changes: 11 additions & 3 deletions web/mvc/controller_descriptor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mvc

import (
"errors"
"github.com/yoyofx/yoyogo/utils"
"github.com/yoyofx/yoyogo/web/context"
"github.com/yoyofxteam/reflectx"
Expand All @@ -11,12 +12,19 @@ import (
// ControllerDescriptor
type ControllerDescriptor struct {
ControllerName string
Descriptor string
ControllerType interface{} // ctor func of controller
actionDescriptors map[string]ActionDescriptor
}

// NewControllerDescriptor create new controller descriptor
func NewControllerDescriptor(name string, controllerType reflect.Type, controllerCtor interface{}) ControllerDescriptor {
func NewControllerDescriptor(name string, controllerType reflect.Type, controllerCtor interface{}) (ControllerDescriptor, error) {

fieldApiController := controllerType.Field(0)
if fieldApiController.Name != "ApiController" {
return ControllerDescriptor{}, errors.New("controller must be embed field0 ApiController")
}
controllerDoc := fieldApiController.Tag.Get("doc")

instance := reflect.New(controllerType).Interface()
actionList := reflectx.GetObjectMethodInfoList(instance)
Expand All @@ -25,7 +33,7 @@ func NewControllerDescriptor(name string, controllerType reflect.Type, controlle

for _, action := range actionList {
actionName := strings.ToLower(action.Name)
if !utils.ContainsStr([]string{"fail", "ok", "setviewengine", "view", "getname"}, actionName) {
if !utils.ContainsStr([]string{"apiresult", "fail", "ok", "setviewengine", "view", "getname"}, actionName) {
actionDescriptors[actionName] = ActionDescriptor{
ActionName: action.Name,
ActionMethod: getHttpMethodByActionName(actionName),
Expand All @@ -34,7 +42,7 @@ func NewControllerDescriptor(name string, controllerType reflect.Type, controlle
}
}

return ControllerDescriptor{name, controllerCtor, actionDescriptors}
return ControllerDescriptor{name, controllerDoc, controllerCtor, actionDescriptors}, nil
}

// GetActionDescriptors get action descriptor list
Expand Down

0 comments on commit 9ce784e

Please sign in to comment.