x/rest Primer
x/rest Primer
Section titled “x/rest Primer”当你已经通过 x/* 家族 确认问题明显属于能力家族,而不是最小 canonical 服务形态时,就打开这一页。
x/rest 是 Plumego 面向应用的可复用资源接口层,负责 CRUD route 标准化、query parsing、pagination rule 与 repository-backed resource wiring。
稳定性与采用
Section titled “稳定性与采用”x/rest 是扩展表面,不属于最小稳定根路径。生产路径采用前,请检查
x/rest/module.yaml、发布策略 和
扩展成熟度。如果兼容性很重要,建议用应用本地 controller 或 interface 隔离。
什么时候从这里开始
Section titled “什么时候从这里开始”- 任务是在标准化可复用资源 API
- 改动属于 controller 级 CRUD transport 行为
- 工作是资源 endpoint 之间共享的 query、pagination、hook 或 transformer 行为
什么时候不该从这里开始
Section titled “什么时候不该从这里开始”- 任务真正是 application bootstrap
- 真正的问题是 gateway 或 reverse-proxy topology
- 工作是 business repository ownership 或 domain validation
当前仓库里先读哪些文件
Section titled “当前仓库里先读哪些文件”x/rest/module.yamlx/rest/spec.gox/rest/entrypoints.go- 当你需要校对 canonical bootstrap shape 时,再读
reference/standard-service
更具体的归属例子
Section titled “更具体的归属例子”这些工作适合留在 x/rest | 这些工作应继续留在别处 |
|---|---|
ResourceSpec、route-shape 标准化、共享分页规则与可复用 CRUD transport 行为 | app-local wiring 中的 route binding 与 transport composition |
| DB-resource controller 构造与 context-aware resource 注册 | repository 层中的持久化与 query execution |
让 controller 输出继续对齐 contract 的 response 与 error 约定 | 归属 domain 包的 domain validation 与业务规则 |
| 可被多个服务复用的资源接口 transport | x/gateway 中的 edge proxy、gateway policy 或 reverse-transport concern |
import "github.com/spcent/plumego/x/rest"注册完整 CRUD 资源
Section titled “注册完整 CRUD 资源”import ( "github.com/spcent/plumego/router" "github.com/spcent/plumego/x/rest")
r := router.NewRouter()rest.RegisterResourceRoutes(r, "/api/v1/users", controller, rest.RouteOptions{})这会在 /api/v1/users 下注册 GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD 及批量端点。
生成 DB controller
Section titled “生成 DB controller”builder := rest.NewSQLBuilder("users", "id"). WithColumns("id", "name", "email", "created_at"). WithScanFunc(scanUser). WithInsertFunc(insertArgs). WithUpdateFunc(updateArgs)
repo := rest.NewBaseRepository[User](sqlDB, builder)controller := rest.NewDBResourceController[User]("users", repo)解析查询参数
Section titled “解析查询参数”params := rest.NewQueryBuilder(). WithPageSize(25, 100). WithAllowedSorts("name", "created_at"). WithAllowedFilters("email"). Parse(r)// params.Page, params.PageSize, params.Sort, params.Filters, params.Search自定义 controller
Section titled “自定义 controller”嵌入 BaseResourceController 并只覆盖你需要的方法:
type UserController struct { rest.BaseResourceController svc *UserService}
func (c *UserController) Create(w http.ResponseWriter, r *http.Request) { // 你的逻辑}完整演练见 构建 REST 资源指南。
一个典型的阅读跳转
Section titled “一个典型的阅读跳转”如果顶层判断页已经告诉你问题属于扩展家族,那么只有当工作真正围绕可复用资源接口 transport 时,x/rest 才是正确下一跳。它不是发明新 bootstrap shape 的地方。