93 lines
1.8 KiB
Go
93 lines
1.8 KiB
Go
package utils
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
"sort"
|
||
|
||
"github.com/gofiber/fiber/v2"
|
||
"github.com/olekukonko/tablewriter"
|
||
)
|
||
|
||
// RouteInfo 路由信息
|
||
type RouteInfo struct {
|
||
Method string
|
||
Path string
|
||
Name string
|
||
}
|
||
|
||
// PrintRoutes 打印所有路由(使用 tablewriter 美化输出)
|
||
func PrintRoutes(app *fiber.App, serviceName string) {
|
||
stack := app.Stack()
|
||
|
||
// 收集所有路由
|
||
var routes []RouteInfo
|
||
for _, routeGroup := range stack {
|
||
for _, route := range routeGroup {
|
||
method := route.Method
|
||
path := route.Path
|
||
if path == "" {
|
||
path = "/"
|
||
}
|
||
|
||
// 过滤掉 Fiber 自动生成的默认路由
|
||
// 1. 过滤掉 HEAD 方法(通常是自动生成的)
|
||
if method == "HEAD" {
|
||
continue
|
||
}
|
||
|
||
// 2. 完全过滤掉根路径 `/` 的所有路由
|
||
// 这些是 Fiber 自动注册的默认路由,通常没有实际意义
|
||
if path == "/" {
|
||
continue
|
||
}
|
||
|
||
routes = append(routes, RouteInfo{
|
||
Method: method,
|
||
Path: path,
|
||
Name: route.Name,
|
||
})
|
||
}
|
||
}
|
||
|
||
// 按路径和方法排序
|
||
sort.Slice(routes, func(i, j int) bool {
|
||
if routes[i].Path != routes[j].Path {
|
||
return routes[i].Path < routes[j].Path
|
||
}
|
||
return routes[i].Method < routes[j].Method
|
||
})
|
||
|
||
// 打印标题
|
||
fmt.Printf("\n📋 %s 路由列表\n", serviceName)
|
||
|
||
if len(routes) == 0 {
|
||
fmt.Println(" 暂无路由")
|
||
return
|
||
}
|
||
|
||
// 创建表格(使用新版本 API)
|
||
table := tablewriter.NewWriter(os.Stdout)
|
||
|
||
// 设置表头
|
||
table.Header("METHOD", "PATH", "NAME")
|
||
|
||
// 添加数据行
|
||
for _, route := range routes {
|
||
method := route.Method
|
||
path := route.Path
|
||
name := route.Name
|
||
if name == "" {
|
||
name = "-"
|
||
}
|
||
|
||
table.Append(method, path, name)
|
||
}
|
||
|
||
// 渲染表格
|
||
if err := table.Render(); err != nil {
|
||
fmt.Printf("渲染表格失败: %v\n", err)
|
||
}
|
||
fmt.Printf(" 共 %d 个路由\n\n", len(routes))
|
||
}
|