Buffalo路由反向解析必须显式设置name参数,否则模板中xxxPath()函数报错;name决定生成的驼峰式路径函数名,如Name("post_comments")→postCommentsPath()。

routes.go 里注册路由时必须传 name 参数
Buffalo 的路径反向解析(比如 postsPath())依赖显式声明的路由别名,不是自动推导的。不设 name,模板里调用就会报 undefined function 错误。
在 config/routes.go 中,所有 app.GET、app.POST 或 app.Resource 都支持 name 选项:
app.GET("/posts", PostsResource{}.Index).Name("posts")
app.Resource("/comments", CommentsResource{}).Name("comments")
注意两点:
-
app.Resource()默认会生成多个子路由(index、show、new等),它只接受一个顶层Name("comments"),内部子路由别名会自动拼接为comments_path、comment_path、new_comment_path - 嵌套路由必须给
Scope内部的Resource单独命名,例如:app.Scope("/posts/{post_id}", func(app buffalo.App) { app.Resource("/comments", CommentsResource{}).Name("post_comments") })这样才会有postCommentsPath({post_id: 1})可用
模板里用 xxxPath() 函数生成 URL,别硬写字符串
Buffalo 自动生成的辅助函数名规则是:把路由别名里的下划线转驼峰,并加 Path 后缀。比如 Name("post_comments") → postCommentsPath(),Name("admin_users") → adminUsersPath()。
调用时传 map 构造参数,路径参数必须显式提供:
<a href="<%= postCommentsPath({post_id: post.ID}) %>">Comments</a>
<form action="<%= commentPath({id: c.Param("id"), post_id: c.Param("post_id")}) %>" method="POST"></form>
常见错误:
开箱即用的技能链路由引擎。13 条预定义链覆盖搜索、开发、审查、MLOps、法律、创意等场景,三层路由架构(触发词→SAD反馈→DAG编排),recall@10=96.97%。配置驱动(chains.yaml),零代码扩展。pip install skill-weave-chains 一键安装。
- 漏传必需的路径参数(如
{post_id: ...}),生成的 URL 缺段,导致 404 - 用错函数名,比如把
postCommentsPath写成postsCommentsPath或post_comment_path,模板编译失败 - 在非 Plush 模板(如 JSON API handler)里误调
xxxPath(),这些函数只在模板上下文注册,c.Param()或c.Request().URL才是运行时取值的正路
带查询参数的 URL 要合并进 map,不能拼字符串
Buffalo 的 xxxPath() 函数支持将 query 参数和路径参数一起传入 map,它会自动拼成 ?key=value&other=1:
<a href="<%= postsPath({page: 2, sort: "created_at"}) %>">Page 2</a>
等价于 /posts?page=2&sort=created_at。不要手动拼接:
- ❌
postsPath() + "?page=2"—— 破坏路径生成逻辑,且无法处理 URL 编码 - ❌
"/posts?page=" + strconv.Itoa(page)—— 绕过 Buffalo 路由系统,后续改路径时全部失效
如果 query 参数名含特殊字符(如 filter[status]),Plush 不支持 map key 带方括号,得改用 c.Request().URL.Query().Set() 手动构造,但这种情况极少见。
自定义函数名冲突时,优先改 name 而非重写函数
如果两个路由都设了 Name("posts"),Buffalo 启动会 panic:duplicate route name。但更隐蔽的问题是函数名冲突 —— 比如你有一个 app.GET("/api/posts", ...).Name("posts"),又有一个 app.Resource("/posts", ...).Name("posts"),生成的 postsPath() 会指向后者(Resource 优先级更高),前者实际不可反向解析。
解决方法只有改名:
- API 路由建议加前缀:
Name("api_posts")→apiPostsPath() - 管理后台路由加命名空间:
Name("admin_posts")→adminPostsPath() - 别试图在模板里覆盖或重定义
xxxPath()函数 —— 它们由 Buffalo 在启动时静态生成,运行时不可变
真正容易被忽略的是:别名只影响模板函数名,不影响中间件匹配或 handler 分发。同一个 Name("posts") 可以对应多个不同 HTTP 方法的路由,只要路径一致,它们共享同一个函数名。


















