You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Gin路由添加类似Laravel的命名并收集路由信息

解决方案

要给Gin原生路由方法添加名称参数,同时在项目启动后就能自动收集路由信息,可以通过封装同名路由注册函数+全局注册表的方式实现,既贴近Gin原生用法,又能自动关联路由名称。

实现步骤

  1. 定义全局路由名称注册表
    用Method:Path作为唯一键,存储路由对应的名称:
import (
    "fmt"
    "net/http"
    "strings"
    "github.com/gin-gonic/gin"
)

var Routes []Route
type Route struct {
    Name       string `json:"name"`
    Sign       string `json:"sign"`
    HttpMethod string `json:"http_method"`
    HttpPath   string `json:"http_path"`
}

// 全局注册表:key为 "方法:路径",value为路由名称
var routeNameRegistry = make(map[string]string)
  1. 封装与原生同名的路由注册函数
    封装GET/POST函数,参数顺序和原生一致,仅新增name参数,注册路由的同时将名称存入注册表:
// 封装GET方法,新增name参数
func GET(r *gin.Engine, path string, name string, handlers ...gin.HandlerFunc) {
    r.GET(path, handlers...)
    key := fmt.Sprintf("%s:%s", http.MethodGet, path)
    routeNameRegistry[key] = name
}

// 封装POST方法,新增name参数
func POST(r *gin.Engine, path string, name string, handlers ...gin.HandlerFunc) {
    r.POST(path, handlers...)
    key := fmt.Sprintf("%s:%s", http.MethodPost, path)
    routeNameRegistry[key] = name
}
  1. 修改ParseRoutes方法,从注册表中获取名称
    遍历Gin内置的路由信息时,通过Method:Path键从注册表中匹配对应的路由名称:
func ParseRoutes(r *gin.Engine, group string) {
    Routes = []Route{} // 清空原有数据
    routes := r.Routes()
    for _, route := range routes {
        if strings.HasPrefix(route.Path, group) {
            sign := strings.Replace(strings.Trim(route.Path, "/"), "/", ".", -1)
            // 生成匹配注册表的key
            key := fmt.Sprintf("%s:%s", route.Method, route.Path)
            item := Route{
                Name:       routeNameRegistry[key],
                Sign:       sign,
                HttpMethod: route.Method,
                HttpPath:   route.Path,
            }
            Routes = append(Routes, item)
        }
    }
}

使用示例

func handler1(c *gin.Context) {
    // 业务逻辑
}

func handle2(c *gin.Context) {
    // 业务逻辑
}

func main() {
    r := gin.Default()
    // 用法和Gin原生几乎一致,仅多传一个路由名称参数
    GET(r, "/api/user/list", "Get User List", handler1)
    POST(r, "/api/user/create", "Create an User", handle2)
    
    // 项目启动前解析所有路由
    ParseRoutes(r, "/api")
    
    // 输出验证路由数据
    // data, _ := json.MarshalIndent(Routes, "", "    ")
    // fmt.Println(string(data))
    
    r.Run()
}

优势

  • 用法贴近Gin原生,无需改变原有编码习惯;
  • 项目启动后即可解析所有路由信息,无需等待请求触发;
  • 自动关联路由与名称,无需手动维护映射表;
  • 支持动态路由(如/api/user/:id),注册表会自动匹配带参数的路径。

内容的提问来源于stack exchange,提问作者Grocker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:40:25