如果需要打印Gin实例路由注册信息「路径、方法」,如何简单获取?
定义路由
MetadataV1Router := r.Group("/metadata/v1")
middleware.MetadataV1Router(MetadataV1Router, r)
定义中间件
import (
"fmt"
"github.com/gin-gonic/gin"
hrequest "gitlab-ecs.litatom.com/infra/hermes/request"
)
func MetadataV1Router(r *gin.RouterGroup, router *gin.Engine) gin.IRoutes {
{
r.GET("/apis", MetaAPIInfoMiddleware(router))
}
return r
}
type Route struct {
Method string
Path string
Handler string
HandlerFunc any
}
func MetaAPIInfoMiddleware(router *gin.Engine) gin.HandlerFunc {
return func(c *gin.Context) {
var (
req = hrequest.HGin{C: c}
routes []Route
)
for _, route := range router.Routes() {
fmt.Printf("Method: %s, Path: %s, Handler: %s\n", route.Method, route.Path, route.Handler)
}
for _, route := range router.Routes() {
routes = append(routes, Route{Method: route.Method, Path: route.Path,})
}
req.SuccessResponse(routes)
c.Next()
}
}