跳转到内容

x/rest Primer

Beta — API 在 minor 版本内保持稳定。采用前请查看发布策略扩展成熟度

当你已经通过 x/* 家族 确认问题明显属于能力家族,而不是最小 canonical 服务形态时,就打开这一页。

x/rest 是 Plumego 面向应用的可复用资源接口层,负责 CRUD route 标准化、query parsing、pagination rule 与 repository-backed resource wiring。

x/rest 是扩展表面,不属于最小稳定根路径。生产路径采用前,请检查 x/rest/module.yaml发布策略扩展成熟度。如果兼容性很重要,建议用应用本地 controller 或 interface 隔离。

  • 任务是在标准化可复用资源 API
  • 改动属于 controller 级 CRUD transport 行为
  • 工作是资源 endpoint 之间共享的 query、pagination、hook 或 transformer 行为
  • 任务真正是 application bootstrap
  • 真正的问题是 gateway 或 reverse-proxy topology
  • 工作是 business repository ownership 或 domain validation
  1. x/rest/module.yaml
  2. x/rest/spec.go
  3. x/rest/entrypoints.go
  4. 当你需要校对 canonical bootstrap shape 时,再读 reference/standard-service
这些工作适合留在 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 与业务规则
可被多个服务复用的资源接口 transportx/gateway 中的 edge proxy、gateway policy 或 reverse-transport concern
import "github.com/spcent/plumego/x/rest"
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 及批量端点。

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)
params := rest.NewQueryBuilder().
WithPageSize(25, 100).
WithAllowedSorts("name", "created_at").
WithAllowedFilters("email").
Parse(r)
// params.Page, params.PageSize, params.Sort, params.Filters, params.Search

嵌入 BaseResourceController 并只覆盖你需要的方法:

type UserController struct {
rest.BaseResourceController
svc *UserService
}
func (c *UserController) Create(w http.ResponseWriter, r *http.Request) {
// 你的逻辑
}

完整演练见 构建 REST 资源指南

如果顶层判断页已经告诉你问题属于扩展家族,那么只有当工作真正围绕可复用资源接口 transport 时,x/rest 才是正确下一跳。它不是发明新 bootstrap shape 的地方。