Skip to content

Commit

Permalink
integration swagger v1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
yoyofx committed Feb 7, 2024
1 parent bf1b167 commit 9a7eaec
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 23 deletions.
56 changes: 49 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ QQ交流群: [780385870](https://qm.qq.com/cgi-bin/qm/qr?k=xP5ZSGZaLLgJIjK0P89
go get github.com/yoyofx/yoyogo
```
# 安装依赖 (由于某些原因国内下载不了依赖)
## go version < 1.13
## go version < 1.20
```bash
window 下在 cmd 中执行:
set GO111MODULE=on
Expand Down Expand Up @@ -122,6 +122,7 @@ github.com/shima-park/agollo
* [x] RouteData路由数据 (/api/:version/) 与 Binding的集成
* [x] 路由组功能
* [x] MVC默认模板功能
* [X] MVC 自定义路由
* [x] 路由过滤器 Filter

## MVC
Expand All @@ -139,7 +140,7 @@ github.com/shima-park/agollo
* [X] 配置
* [X] WebSocket
* [X] JWT
* [ ] swagger
* [X] swagger
* [X] GRpc
* [X] Prometheus

Expand Down Expand Up @@ -194,6 +195,26 @@ func registerEndpoints(rb router.IRouterBuilder) {
Endpoints.UsePrometheus(rb)
Endpoints.UsePprof(rb)
Endpoints.UseJwt(rb)

//swagger api document
endpoints.UseSwaggerDoc(rb,
swagger.Info{
Title: "YoyoGO 框架文档演示",
Version: "v1.0.0",
Description: "框架文档演示swagger文档 v1.0 [ #yoyogo](https://github.com/yoyofx/yoyogo).",
TermsOfService: "https://dev.yoyogo.run",
Contact: swagger.Contact{
Email: "[email protected]",
Name: "yoyogo",
},
License: swagger.License{
Name: "MIT",
Url: "https://opensource.org/licenses/MIT",
},
},
func(openapi *swagger.OpenApi) {
openapi.AddSecurityBearerAuth()
})

rb.GET("/error", func(ctx *context.HttpContext) {
panic("http get error")
Expand Down Expand Up @@ -250,11 +271,12 @@ func NewUserController(userAction models.IUserAction) *UserController {
return &UserController{userAction: userAction}
}

// 请求对象的参数化绑定
type RegiserRequest struct {
mvc.RequestBody
UserName string `param:"username"`
Password string `param:"password"`
// 请求对象的参数化绑定 , 使用 doc属性标注 支持swagger文档
type RegisterRequest struct {
mvc.RequestBody `route:"/api/users/register" doc:"用户注册"`
UserName string `uri:"userName" doc:"用户名"`
Password string `uri:"password" doc:"密码"`
TestNumber uint64 `uri:"num" doc:"数字"`
}

// Register函数自动绑定参数
Expand All @@ -268,6 +290,26 @@ func (this *UserController) GetInfo() mvc.ApiResult {
return this.OK(this.userAction.Login("zhang"))
}

// DocumentResponse custom document response , use doc tag for swagger
type DocumentResponse struct {
Message string `json:"message" doc:"消息"`
List []DocumentDto `json:"list" doc:"文档列表"`
Success bool `json:"success" doc:"是否成功"`
}

// Swagger API 文档支持
func (controller UserController) GetDocumentList(request *struct {
mvc.RequestGET `route:"/v1/user/doc/list" doc:"获取全部文档列表"`
}) DocumentResponse {

return DocumentResponse{Message: "GetDocumentList", List: []DocumentDto{
{Id: 1, Name: "test1", Time: time.Now()}, {Id: 2, Name: "test2", Time: time.Now()},
{Id: 3, Name: "test3", Time: time.Now()}, {Id: 4, Name: "test4", Time: time.Now()},
{Id: 5, Name: "test5", Time: time.Now()}, {Id: 6, Name: "test6", Time: time.Now()},
}, Success: true}
}


// Web程序的开始与停止事件
func fireApplicationLifeEvent(life *abstractions.ApplicationLife) {
printDataEvent := func(event abstractions.ApplicationEvent) {
Expand Down
4 changes: 2 additions & 2 deletions README_En.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ func main() {
* [X] configtion
* [X] WebSocket
* [X] JWT
* [ ] swagger
* [ ] GRpc
* [X] swagger
* [X] GRpc
* [X] Prometheus


Expand Down
8 changes: 3 additions & 5 deletions examples/simpleweb/contollers/usercontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ func (controller UserController) GetDocumentById(request *struct {
Message("GetDocumentById").Build()
}

// custom document response
// DocumentResponse custom document response
type DocumentResponse struct {
Message string `json:"message" doc:"消息"`
List []DocumentDto `json:"list" doc:"文档列表"`
Expand All @@ -193,11 +193,9 @@ func (controller UserController) GetDocumentList(request *struct {
mvc.RequestGET `route:"/v1/user/doc/list" doc:"获取全部文档列表"`
}) DocumentResponse {

list := []DocumentDto{
return DocumentResponse{Message: "GetDocumentList", List: []DocumentDto{
{Id: 1, Name: "test1", Time: time.Now()}, {Id: 2, Name: "test2", Time: time.Now()},
{Id: 3, Name: "test3", Time: time.Now()}, {Id: 4, Name: "test4", Time: time.Now()},
{Id: 5, Name: "test5", Time: time.Now()}, {Id: 6, Name: "test6", Time: time.Now()},
}

return DocumentResponse{Message: "GetDocumentList", List: list, Success: true}
}, Success: true}
}
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package yoyogo

const (
//Application Version, such as v1.x.x pre-release
Version = "v1.8.8.release"
Version = "v1.8.7.release"
//Application logo
//Logo = "IF8gICAgIF8gICAgICAgICAgICAgICAgICAgIF9fXyAgICAgICAgICAKKCApICAgKCApICAgICAgICAgICAgICAgICAgKCAgX2BcICAgICAgICAKYFxgXF8vJy8nXyAgICBfICAgXyAgICBfICAgfCAoIChfKSAgIF8gICAKICBgXCAvJy8nX2BcICggKSAoICkgLydfYFwgfCB8X19fICAvJ19gXCAKICAgfCB8KCAoXykgKXwgKF8pIHwoIChfKSApfCAoXywgKSggKF8pICkKICAgKF8pYFxfX18vJ2BcX18sIHxgXF9fXy8nKF9fX18vJ2BcX19fLycKICAgICAgICAgICAgICggKV98IHwgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgIGBcX19fLycgICAgICAgICAgICBMaWdodCBhbmQgZmFzdC4gIA=="
Logo = `
Expand Down
51 changes: 43 additions & 8 deletions web/endpoints/swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ func UseSwaggerDoc(router router.IRouterBuilder, info swagger.Info, configFunc f
_ = ctx.RequiredServices.GetService(&env)
baseUrl := fmt.Sprintf("http://localhost:%s", env.Port)
openapi := swagger.NewOpenApi(baseUrl, info)

configFunc(openapi)
//openapi.AddSecurityBearerAuth()
GetSwaggerRouteInfomation(openapi, router, env)
GetSwaggerRouteInformation(openapi, router, env)
ctx.JSON(200, openapi)
})

Expand Down Expand Up @@ -76,15 +76,51 @@ func UseSwaggerDoc(router router.IRouterBuilder, info swagger.Info, configFunc f
})
}

func GetSwaggerRouteInfomation(openapi *swagger.OpenApi, router router.IRouterBuilder, env *abstractions.HostEnvironment) {
func GetSwaggerRouteInformation(openapi *swagger.OpenApi, router router.IRouterBuilder, env *abstractions.HostEnvironment) {
// mvc routes
builder := router.GetMvcBuilder()
controllerList := builder.GetControllerDescriptorList()
for _, controller := range controllerList {
FilterValidParams(controller, openapi, env)
getMvcRouters(controller, openapi, env)
}

// default routes
getEndpointRouters(openapi, router, env)
}

func getEndpointRouters(openapi *swagger.OpenApi, router router.IRouterBuilder, env *abstractions.HostEnvironment) {
// default normal route ,such as rb.POST("/info/:id", PostInfo)
routerInfoList := router.GetRouteInfo()
openapi.Tags = append(openapi.Tags, swagger.Tag{Name: "default", Description: fmt.Sprintf("Endpoints of the default route. (%v)", len(routerInfoList))})
for idx, _ := range routerInfoList {
// uri parameters
pathInfo := swagger.Path{
Tags: []string{"default"},
Responses: map[string]swagger.ResponsesItem{},
Parameters: []swagger.Parameters{}}

actPath := fmt.Sprintf("/%s%s", env.MetaData["server.path"], routerInfoList[idx].Path)
// used regexp ,replace :id to {id}
if strings.Contains(actPath, ":") {
reg := regexp.MustCompile(`:([a-zA-Z0-9]+)`)
matches := reg.FindAllString(actPath, -1)
var params []swagger.Parameters
if len(matches) > 0 {
for _, match := range matches {
paramName := strings.Replace(match, ":", "", -1)
params = append(params, swagger.Parameters{In: "path", Name: paramName})
}
pathInfo.Parameters = params
}
actPath = reg.ReplaceAllString(actPath, "{$1}")
}

pathInfo.Responses["200"] = swagger.ResponsesItem{Description: "OK"}
openapi.Paths[actPath] = map[string]swagger.Path{strings.ToLower(routerInfoList[idx].Method): pathInfo}
}
}

func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.OpenApi, env *abstractions.HostEnvironment) {
func getMvcRouters(controller mvc.ControllerDescriptor, openapi *swagger.OpenApi, env *abstractions.HostEnvironment) {
serverPath := env.MetaData["server.path"]
mvcTemplate := env.MetaData["mvc.template"]
// mvc
Expand Down Expand Up @@ -154,9 +190,8 @@ func FilterValidParams(controller mvc.ControllerDescriptor, openapi *swagger.Ope
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}")
actPath = strings.ReplaceAll(actPath, ":", "")
reg := regexp.MustCompile(`:([a-zA-Z0-9]+)`)
actPath = reg.ReplaceAllString(actPath, "{$1}")
pathInfo.Summary = pathInfo.Summary + " ( Route Attribute ) "
} else {
pathInfo.Summary = pathInfo.Summary + " ( MVC ) "
Expand Down

0 comments on commit 9a7eaec

Please sign in to comment.