-
Notifications
You must be signed in to change notification settings - Fork 0
how_to_schema.md
maoxiaoyue edited this page May 14, 2026
·
4 revisions
讓路由攜帶 metadata(輸入/輸出型別、描述、標籤),AI 無需追蹤 handler 實作即可理解 API 行為。支援 REST、gRPC、Bot、MCP、WebSocket、CLI 六種協議。
傳統路由只告訴框架「這個 URL 對應哪個 handler」,AI 必須閱讀 handler 原始碼才能理解 API。Schema-first 路由讓 metadata 直接附著在路由上:
傳統:r.POST("/api/users", createUserHandler) ← AI 需讀 handler 原始碼
Schema:r.Schema(Route{...}).Handle(handler) ← AI 直接從 metadata 理解
import "github.com/maoxiaoyue/hypgo/pkg/schema" // 定義請求/回應型別 type CreateUserRequest struct { Name string `json:"name"` Email string `json:"email"` } type UserResponse struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } // 註冊帶 schema 的路由 r := router.New() r.Schema(schema.Route{ Method: "POST", Path: "/api/users", Summary: "建立使用者", Tags: []string{"users"}, Input: CreateUserRequest{}, Output: UserResponse{}, Responses: map[int]schema.ResponseSchema{ 201: {Description: "User created"}, 400: {Description: "Invalid input"}, }, }).Handle(createUserHandler)
api := r.NewGroup("/api/v1") api.Schema(schema.Route{ Method: "GET", Path: "/products", Summary: "取得商品列表", Tags: []string{"products"}, Output: []ProductResponse{}, }).Handle(listProductsHandler) // 路由自動註冊為 GET /api/v1/products
Schema 路由與傳統路由可以並存,完全向後相容:
r.GET("/health", healthHandler) // 傳統路由 — 照常使用 r.Schema(schema.Route{...}).Handle(createHandler) // Schema 路由 — 附帶 metadata
v0.8.5+多協議支援(gRPC / Bot / MCP / WebSocket / CLI)為 v0.8.5 新增功能。v0.8.1 僅支援 REST 協議。
除了 REST,Schema 支援直接註冊其他協議的命令合約:
// gRPC schema.RegisterGRPC("UserService/CreateUser", "Create user", CreateUserReq{}, UserResp{}) // Bot(Telegram, Line, Discord, WhatsApp 等) schema.RegisterBot("/start", "Start the bot", nil, WelcomeMsg{}) schema.RegisterBotPlatform("telegram", "/game", "Start game", GameOpts{}, GameState{}) schema.RegisterBotPlatform("discord", "!play", "Play music", PlayReq{}, PlayResp{}) // MCP(Model Context Protocol) schema.RegisterMCP("search_repos", "Search repos", SearchInput{}, SearchOutput{}) // WebSocket 訊息類型 schema.RegisterWebSocket("join_room", "Join room", JoinReq{}, JoinResp{}) // CLI 子命令 schema.RegisterCLI("process", "Process data", ProcessFlags{}, ProcessResult{})
所有協議共用同一個 Schema Registry 和 Manifest,AI 讀一個 manifest 就能理解所有 API。
type Route struct { // 通用欄位(所有協議共用) Protocol string // "rest"(default), "grpc", "bot", "mcp", "websocket", "cli" Command string // 非 REST 命令標識(gRPC method、bot command、MCP tool...) Platform string // bot 專用平台:"telegram", "line", "discord", "whatsapp" Summary string // 一行描述(給 AI 和文件用) Description string // 詳細描述 Tags []string // 分類標籤 Input interface{} // 請求的 Go struct(用於驗證) Output interface{} // 回應的 Go struct(用於驗證) InputName string // 自動填入,無需手動設定 OutputName string // 自動填入,無需手動設定 // REST 專用(向後相容) Method string // HTTP 方法(GET, POST, PUT, DELETE...) Path string // 路由路徑(支援 :param 和 *catchall) Params []ParamSchema // 路徑/查詢參數描述 Headers []HeaderSchema // 必要標頭描述 Responses map[int]ResponseSchema // 各狀態碼的回應描述 } // RouteKey() 回傳 Registry 查詢 key // REST: "rest|POST /api/users" // gRPC: "grpc|UserService/CreateUser" // Bot: "bot|/start" // MCP: "mcp|search_repos" // IsREST() 判斷是否為 REST 路由
| Protocol | Command 格式 | 範例 |
|---|---|---|
rest |
Method + Path(自動) |
POST /api/users |
grpc |
Service/Method |
UserService/CreateUser |
bot |
/command 或事件名 |
/start, follow, !play
|
mcp |
tool_name |
search_repos, create_issue
|
websocket |
message_type |
join_room, send_message
|
cli |
command_name |
process, export
|
type ParamSchema struct { Name string // 參數名稱 In string // "path", "query", "header" Required bool // 是否必填 Type string // "string", "int", "bool" Desc string // 描述 }
type ResponseSchema struct { Description string // 回應描述 Type interface{} // Go struct type(用於 Contract Testing 驗證) TypeName string // 自動填入 }
所有透過 Schema() 或 Register*() 註冊的路由都會存入全域 Registry:
// 查詢 REST 路由(向後相容) route, ok := schema.Global().Get("POST", "/api/users") // 根據完整 key 查詢(任何協議) route, ok := schema.Global().GetByKey("grpc|UserService/CreateUser") route, ok := schema.Global().GetByKey("bot|/start") // 按協議篩選 grpcRoutes := schema.Global().GetByProtocol("grpc") botRoutes := schema.Global().GetByProtocol("bot") // 取得所有已註冊的 schema(所有協議) all := schema.Global().All() // 查看已註冊數量 count := schema.Global().Len() // 清空(測試用) schema.Global().Reset()
Registry 為 thread-safe,使用 sync.RWMutex 保護。
提供型別內省工具,供 Manifest 和 Contract Testing 使用:
// 取得型別名稱 schema.TypeName(UserResponse{}) // → "UserResponse" // 取得 struct 欄位資訊 fields := schema.FieldsOf(UserResponse{}) // → [{Name:"id", Type:"integer", Required:true}, ...] // 驗證 JSON 是否符合 struct(含必填欄位檢查) err := schema.ValidateJSON([]byte(`{"name":"alice"}`), CreateUserRequest{}) // 生成零值 JSON(用於自動測試) data := schema.GenerateZeroJSON(CreateUserRequest{}) // → {"name":"","email":""}
| 條件 | Required |
|---|---|
Name string \json:"name"`` |
✅ 是 |
Email string \json:"email,omitempty"`` |
❌ 否(omitempty) |
Bio *string \json:"bio"`` |
❌ 否(pointer) |
json:"-" |
跳過(不出現) |
pkg/schema/
├── schema.go Route(多協議)、SchemaRoute、ParamSchema 等型別定義
├── registry.go 全域 thread-safe Registry(支援 RouteKey 多協議查詢)
├── helpers.go RegisterGRPC/Bot/MCP/WebSocket/CLI 便捷函式
├── reflect.go TypeName、FieldsOf、ValidateJSON 反射工具
└── schema_test.go 單元測試
pkg/schema ← 僅依賴 pkg/context(HandlerFunc 型別)
← 不依賴 pkg/router(避免迴圈依賴)
SchemaRegistrar 介面由 schema 定義,Router 和 Group 實作,避免迴圈依賴。
設計文件
套件
- config — 設定
- context — 請求上下文
- router — 路由器
- server — 伺服器
- middleware — 中介層
- websocket — WebSocket
- hidb — 資料庫 ORM
- hidb/cassandra — Cassandra
- logger — 日誌
- json — JSON 處理
- grpc — gRPC
AI 協作工具鏈
- schema — Schema-first 路由
- manifest — 專案 Manifest
- contract — Contract Testing
- errors — Typed Error Catalog
- migrate — Migration Diff
- scaffold — 智慧 Scaffold
- airules — AI Rules
CLI 命令
- hyp 總覽
- hyp new
- hyp api
- hyp run
- hyp restart
- hyp generate
- hyp migrate
- hyp context
- hyp ai-rules
- hyp chkcomment
- hyp impact
- hyp docker
- hyp health
- hyp version
- hyp difflog
Design Docs
Packages
- config — Configuration
- context — Request Context
- router — Router
- server — Server
- middleware — Middleware
- websocket — WebSocket
- hidb — Database ORM
- hidb/cassandra - Cassandra 5.0
- logger — Logger
- json — JSON
- grpc — gRPC
AI Collaboration Toolchain
- schema — Schema-first Routing
- manifest — Project Manifest
- contract — Contract Testing
- errors — Typed Error Catalog
- migrate — Migration Diff
- scaffold — Smart Scaffold
- airules — AI Rules
CLI Commands