Documentation
¶
Overview ¶
Package xyz wires one registry to every frontend. Main reads the process arguments, decides the running mode by itself, and exits with the code the dispatch produced. The whole program can be a single define-chain:
func main() {
xyz.Define("user.add", addUser).
Summary("创建用户").
CLI(xyz.CliHints{...}).
MCP(xyz.MCPHints{...}).
Also(xyz.Define("math.sum", sum).Summary("求和")).
Run()
}
Run (and Main / MainConfig) dispatch the process-wide default registry and call os.Exit internally, so deferred cleanups written in main cannot run after them. When you need defer-based cleanup, a custom exit code, several registries, or want to embed the dispatcher, use Run / RunConfig with an explicit registry, which return the exit code instead:
func main() {
reg := registry.New()
// ... spec.Define(...).Register(reg) ...
defer cleanup()
os.Exit(xyz.Run(reg, os.Args[1:]))
}
A registry with no registered commands is a silent no-op: the dispatcher exits 0 without printing anything.
Mode detection:
<app> [命令] ... -> CLI frontend (subcommands, flags, positionals, -h / -v) <app> mcp stdio|sse|http -> MCP frontend (official SDK; --versions pins protocol versions) <app> serve [--addr ...] -> HTTP frontend (REST + /openapi.json + /mcp) <app> (no args) | help -> overview listing modes and commands
The mode keywords default to "serve", "mcp" and "help" and are reserved top-level names; both the keywords and the reserved-name checks follow the Modes configuration in RunConfig, so they can be renamed. Dispatch lives in main.go, configuration types in config.go, built-in parameter parsing in builtins.go, overview rendering in overview.go and the fluent builder in builder.go.
Index ¶
- Constants
- Variables
- func Interactive() bool
- func Language() string
- func LanguageFromCtx(ctx context.Context) string
- func Main(cmds ...Definable)
- func MainConfig(cfg Config)
- func NoColor() bool
- func Run(reg *registry.Registry, args []string) int
- func RunConfig(reg *registry.Registry, args []string, cfg Config) int
- func TryRun(reg *registry.Registry, args []string) (int, bool)
- func TryRunConfig(reg *registry.Registry, args []string, cfg Config) (int, bool)
- type Builder
- func (b *Builder[T, R]) Also(cmds ...Definable) *Builder[T, R]
- func (b *Builder[T, R]) CLI(h CliHints) *Builder[T, R]
- func (b *Builder[T, R]) Configure(cfg Config) *Builder[T, R]
- func (b *Builder[T, R]) Description(s string) *Builder[T, R]
- func (b *Builder[T, R]) HTTP(h HTTPHints) *Builder[T, R]
- func (b *Builder[T, R]) MCP(h MCPHints) *Builder[T, R]
- func (b *Builder[T, R]) Register(r spec.Registrar) (*spec.Entry, error)
- func (b *Builder[T, R]) Run()
- func (b *Builder[T, R]) RunArgs(args []string) int
- func (b *Builder[T, R]) RunArgsConfig(args []string, cfg Config) int
- func (b *Builder[T, R]) RunConfig(cfg Config)
- func (b *Builder[T, R]) Summary(s string) *Builder[T, R]
- type Capabilities
- type CliFieldHint
- type CliHints
- type Config
- type Definable
- type EnvContext
- type HTTPFieldHint
- type HTTPHints
- type Handler
- type MCPFieldHint
- type MCPHints
- type ModeWords
Constants ¶
const SDKVersion = "0.4.5"
SDKVersion 是 xyz-go 库自身的版本(与 git tag 一致)。它在每次发布时 手工同步(见 RELEASING.md),用于 HTTP 的 X-XYZ-Version 响应头与 MCP 的 _meta.xyz.sdk_version / serverInfo,让调用方知道是哪个 xyz 构建在服务。 这与「使用 xyz 的应用程序自己的版本」是两回事——后者见 Version。
Variables ¶
var Version = "dev"
Version 是*应用程序*(用 xyz 构建的那个程序)的版本,由根派发器的 -v/--version、HTTP 的 X-App-Version 响应头与 MCP 的 serverInfo.version / _meta.xyz.app_version 报告。两种设置方式:
- 代码里写死或运行时赋值:xyz.Version = "myapp 2.1.3" (或 xyz.Config{Version: "myapp 2.1.3"},后者优先级更高);
- 构建期注入:-ldflags "-X github.com/ejfkdev/xyz-go.Version=v1.2.3"。
默认 "dev"。注意它位于 xyz-go 包内、但承载的是*应用*的版本——这是为了让 应用能用单条 ldflags 注入而无需自己再声明变量。cli 前端为直接嵌入场景 另保留一个 cli.Version。
Functions ¶
func Interactive ¶ added in v0.4.4
func Interactive() bool
Interactive 报告进程默认输出(os.Stdout)是否为交互式终端(TTY)。 嵌入且使用自定义 writer 时,逐次执行的权威值见 cli.ExecContext.Interactive (二者同源于 termx.Interactive)。
func Language ¶ added in v0.4.4
func Language() string
Language 返回解析后的 UI 语言字符串("en" | "zh-CN")。派发后是 --xyz.lang > Config.Lang > LANG/LC_ALL > en 的结果;未派发的纯嵌入场景 返回 langx 的当前值(默认 en,可用 langx.Set 预设)。
func LanguageFromCtx ¶ added in v0.4.4
LanguageFromCtx 返回 ctx 携带的逐请求语言字符串("en" | "zh-CN")。HTTP 前端把从 Accept-Language 解析的语言放进请求 ctx(缺省回退进程默认语言), handler 由此拿到本次请求该有的语言并本地化自己的输出;ctx 未携带时回退到 进程语言(等价 Language())。
func Main ¶
func Main(cmds ...Definable)
Main registers any fully-built command definitions passed to it (from xyz.Define), dispatches the process-wide default registry on the process arguments, and exits with the resulting exit code. Zero arguments means "definitions already registered via RegisterDefault, just dispatch". Use Run/RunConfig instead when you need the code yourself (embedding, testing, deferred cleanups) or want an explicit registry.
func MainConfig ¶
func MainConfig(cfg Config)
MainConfig is Main with a custom configuration (e.g. renamed mode words).
func NoColor ¶ added in v0.4.4
func NoColor() bool
NoColor 报告环境是否要求去色(NO_COLOR 非空或 TERM=dumb)。为将来的彩色 渲染器(样式轴)预留;宿主现在即可查询以自行决定上色。
func Run ¶
Run is Main with explicit arguments and default configuration, returning the exit code without exiting the process.
func RunConfig ¶
RunConfig is Run with a custom configuration (renamed mode words, channel capabilities).
Types ¶
type Builder ¶
type Builder[T, R any] struct { // contains filtered or unexported fields }
Builder is the fluent main entry: one Define chain configures the whole program. Define opens it, Summary/Description/CLI/HTTP/MCP configure the current command, Also appends fully-built commands, and the terminal Run registers everything into the default registry, dispatches the process arguments, and exits with the resulting exit code.
xyz.Define("user.add", addUser).
Summary("创建用户").
CLI(xyz.CliHints{...}).
MCP(xyz.MCPHints{...}).
Also(
xyz.Define("math.sum", sum).Summary("求和"),
xyz.Define("time.now", now).Summary("当前 UTC 时间"),
).
Run()
Go has no generic methods, so the chain needs only this one convention: the first command is configured inline, every further command is a complete Define(...) chain handed to Also.
func (*Builder[T, R]) Also ¶
Also registers the current command and every command passed in, all into the same default registry, then keeps the chain going. Call it again to append more. Registration failures stop the chain: they surface at Run.
func (*Builder[T, R]) Configure ¶
Configure sets the dispatcher configuration used by Run / RunArgs (mode words, channel capabilities). Call it anywhere on the chain; RunConfig and RunArgsConfig take an explicit Config for that call instead.
func (*Builder[T, R]) Description ¶
Description sets the longer explanation of the command.
func (*Builder[T, R]) Register ¶
Register implements Definable: it registers the underlying command into r.
func (*Builder[T, R]) Run ¶
func (b *Builder[T, R]) Run()
Run registers the command (if not yet registered), dispatches the default registry on the process arguments, and exits with the resulting exit code. Everything after it is unreachable by design.
func (*Builder[T, R]) RunArgs ¶
RunArgs is the testable/embeddable form of Run: it registers, dispatches and returns the exit code without exiting the process. It uses the chain's Configured settings (zero value = every default).
func (*Builder[T, R]) RunArgsConfig ¶
RunArgsConfig is RunArgs with a custom configuration.
type Capabilities ¶
type Capabilities struct {
NoCLI bool // 不在命令注册表上生成子命令(mcp/serve/help/-v 仍可用)
NoMCP bool // mcp 模式不可用(stdio/sse/http 都拒绝)
NoHTTP bool // serve 模式不可用
}
Capabilities switches the channels on and off at runtime (independently of build tags). The zero value keeps every channel enabled. Disabling a channel only removes its own runtime path: the mode words (serve, mcp, help) and -v/--version keep working, and the disabled mode answers with a clear error. Disabled config methods still compile — they merely stop being consumed.
type CliFieldHint ¶
type CliFieldHint = spec.CliFieldHint
spec 公开类型在根包的原样别名:链式(单例)写法下用户只需要 import "github.com/ejfkdev/xyz-go"。
type Config ¶
type Config struct {
Modes ModeWords
Capabilities Capabilities
// Addr 是 serve 与 mcp(http/sse) 模式的默认监听地址(各模式自己的
// --addr flag 优先)。
Addr string
// BearerTokens 开启 serve REST 与 MCP http/sse 传输的 Bearer 凭据校验,
// 每个元素是一个可接受的 token;空表示不校验。命令行写法:
// --xyz.bearer=tok1,tok2(stdio 传输为本地进程,不受影响)。
BearerTokens []string
// LogLevel 是库自身诊断的日志级别(logx 输出到 stderr)。
// 零值(LevelUnset)保持默认 Info。命令行:--xyz.log-level=debug|info|warn|error。
LogLevel logx.Level
// Timeout 是 serve 模式的读/写/空闲超时;0 表示只保留 10s 的请求头超时。
Timeout time.Duration
// CertFile/KeyFile 同时给定则 serve 以 TLS 监听(--xyz.tls-cert/--xyz.tls-key)。
CertFile string
KeyFile string
// CORSOrigins 非空则开启 CORS:逐个 Origin 放行("*" 表示任意来源),
// OPTIONS 预检在鉴权之前应答。命令行:--xyz.cors=origin1,origin2。
CORSOrigins []string
// Lang 覆盖界面语言:""=自动(--xyz.lang flag > 本字段 > LANG/LC_ALL
// 环境检测 > 英文默认)。取值 "en" | "zh-CN"。
Lang string
// Translations 是用户的多语言内容覆盖表:语言 → (消息键 → 文本)。
// 键名见 langx 目录(xyz-spec §15.8 的规范键表);只覆盖内置键亦可。
Translations map[string]map[string]string
// ChannelDefaults 是 serve/mcp 启动时注入的一批通道级默认参数
// (字段线上名 → 字符串值):请求/调用未显式提供时自动补上,优先级
// 高于全局 default tag、低于显式入参与接口默认。命令行:
// --default k=v(可重复/逗号分隔对),代码侧写入本表。
ChannelDefaults map[string]string
// HelpBefore/HelpAfter 是 help 总览的自定义文本块:前者原样插在总览
// 开头(程序名/描述/版本/仓库地址等自己拼),后者插在结尾(命令表之后,
// 即使命令表被隐藏也打印)。空 = 不插入。
HelpBefore string
HelpAfter string
// Version 是*应用程序*(用 xyz 构建的程序)的版本,报告于 HTTP 的
// X-App-Version 响应头、MCP 的 serverInfo.version 与 _meta.xyz.app_version、
// 以及 CLI 的 -v/--version。空则回退到包级 xyz.Version(可用
// -ldflags "-X github.com/ejfkdev/xyz-go.Version=v1.2.3" 注入)。
// 这与 xyz 库自身的版本(xyz.SDKVersion,报告于 X-XYZ-Version)是两回事。
Version string
// Name 是应用程序名,报告于 HTTP 的 X-App-Name 响应头与 MCP 的
// serverInfo.name / _meta.xyz.app_name。空则回退到二进制basename。
Name string
// Format 是 CLI 的全局默认输出格式:auto|text|json|jsonl|markdown。
// auto(默认,空值等价)= 按 stdout 是否交互式终端解析为 FormatInteractive
// / FormatPiped。命令行 --xyz.format=<值> 写入本字段并标记为「来自命令行」
//(优先级高于逐命令的 CliHints.Format);裸 --format/--json 更高于本字段。
Format string
// FormatInteractive / FormatPiped 是 Format=auto 时两种上下文各自的具体
// 格式。空则用内置默认:交互式 text(对齐表格/键值,人类最清晰)、
// 非交互式 jsonl(每行一条紧凑 JSON,被程序调用时最易解析)。仅代码配置,
// 不设命令行旗标(命令行用 --xyz.format 直接钉死具体格式即可)。
FormatInteractive string
FormatPiped string
// ResponseHeaders 是附加到每个 HTTP 响应的自定义静态头(键值原样写入,
// 不做规范化);MCP 侧作为每次调用结果 _meta.xyz.headers 透出。
// 命令行:--xyz.header k=v(可重复,或逗号分隔多对)。
ResponseHeaders map[string]string
// NoServerHeaders 置 true 关闭自动服务器上下文头:HTTP 的
// X-App-Name/X-App-Version/X-XYZ-Version/X-XYZ-Command/X-XYZ-Duration-Ms
// 与 MCP 结果 _meta 里的 xyz 上下文都不再写。ResponseHeaders 自定义头
// 不受影响(它们是显式配置)。
NoServerHeaders bool
// contains filtered or unexported fields
}
Config adjusts the dispatcher. The zero value keeps every default.
type Definable ¶
Definable is implemented by any fully-built command definition (spec.Command[T, R], or the Builder returned by Define), so heterogeneous commands can be collected into one chain or one Main call.
type EnvContext ¶ added in v0.4.4
type EnvContext struct {
// Language 是解析后的 UI 语言:"en" | "zh-CN"。
Language string
// Interactive 报告进程默认输出(os.Stdout)是否为交互式终端(TTY)。
Interactive bool
// NoColor 报告环境是否要求去色(NO_COLOR 非空或 TERM=dumb)——样式轴
// 的输入,与 Interactive 正交(真实终端也可能 NoColor)。
NoColor bool
}
EnvContext 是一次环境上下文的快照。字段只增不改语义,便于将来扩展 (如色彩模式、应用身份、解析后的输出格式)。
type HTTPFieldHint ¶
type HTTPFieldHint = spec.HTTPFieldHint
spec 公开类型在根包的原样别名:链式(单例)写法下用户只需要 import "github.com/ejfkdev/xyz-go"。
type MCPFieldHint ¶
type MCPFieldHint = spec.MCPFieldHint
spec 公开类型在根包的原样别名:链式(单例)写法下用户只需要 import "github.com/ejfkdev/xyz-go"。
type ModeWords ¶
type ModeWords struct {
Serve string // 默认 "serve":HTTP REST + /openapi.json + /mcp(合体)
HTTP string // 默认 "http":仅 HTTP REST + /openapi.json(单独 HTTP 接口,不挂 /mcp)
MCP string // 默认 "mcp"
Help string // 默认 "help"
}
ModeWords renames the built-in mode keywords. Fields left empty keep their defaults (serve, http, mcp, help). Each word also has an always-available, help-hidden namespaced form "xyz.<word>" that survives a collision with a user command (xyz-spec §13.1): when a user command's top-level segment equals a mode word, the bare word routes to the user's command and the built-in mode stays reachable only via "xyz.<word>".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package block defines the reserved content-block envelope (xyz-spec §12.7): a result value whose JSON is an object with the single key "content", holding items of exactly the shapes
|
Package block defines the reserved content-block envelope (xyz-spec §12.7): a result value whose JSON is an object with the single key "content", holding items of exactly the shapes |
|
Package cli is the CLI frontend: it consumes a registry's entries and turns their cli bindings (shorthands, positionals, env fallbacks, transport-specific defaults) into a command tree.
|
Package cli is the CLI frontend: it consumes a registry's entries and turns their cli bindings (shorthands, positionals, env fallbacks, transport-specific defaults) into a command tree. |
|
cmd
|
|
|
example
command
完整示例:一条 xyz.Define(...)...Run() 链 = 整个程序。
|
完整示例:一条 xyz.Define(...)...Run() 链 = 整个程序。 |
|
tour
command
教学导览:展示三通道绑定、默认值分层和 schema 生成的内部视图。
|
教学导览:展示三通道绑定、默认值分层和 schema 生成的内部视图。 |
|
Package errors defines the error taxonomy shared by every frontend of the kit: one coded error drives the CLI exit code, the HTTP status code, and the MCP JSON-RPC error code alike, so transport implementations never need to interpret command-specific error strings.
|
Package errors defines the error taxonomy shared by every frontend of the kit: one coded error drives the CLI exit code, the HTTP status code, and the MCP JSON-RPC error code alike, so transport implementations never need to interpret command-specific error strings. |
|
Package httpapi is the HTTP frontend, implemented on the standard library only (net/http with method-pattern routing).
|
Package httpapi is the HTTP frontend, implemented on the standard library only (net/http with method-pattern routing). |
|
Package langx 是内置界面文本的 i18n 层:enum 语言 + 进程级目录 + 用户 覆盖。
|
Package langx 是内置界面文本的 i18n 层:enum 语言 + 进程级目录 + 用户 覆盖。 |
|
Package logx is the library's diagnostics sink: a leveled, zero-dependency logger writing to stderr.
|
Package logx is the library's diagnostics sink: a leveled, zero-dependency logger writing to stderr. |
|
Package mcp is the MCP frontend, built on the official Model Context Protocol Go SDK (github.com/modelcontextprotocol/go-sdk).
|
Package mcp is the MCP frontend, built on the official Model Context Protocol Go SDK (github.com/modelcontextprotocol/go-sdk). |
|
Package registry holds the type-erased entries built by spec.Define and hands them to the transport frontends.
|
Package registry holds the type-erased entries built by spec.Define and hands them to the transport frontends. |
|
Package spec is the single source of truth for a command: one Go struct with tags is analyzed once and produces the metadata every frontend needs (CLI flags, HTTP bindings, MCP JSON Schema) plus an Invoke closure that decodes transport-shaped input (map[string]any) into the typed argument struct, applies defaults and validation, and runs the handler.
|
Package spec is the single source of truth for a command: one Go struct with tags is analyzed once and produces the metadata every frontend needs (CLI flags, HTTP bindings, MCP JSON Schema) plus an Invoke closure that decodes transport-shaped input (map[string]any) into the typed argument struct, applies defaults and validation, and runs the handler. |
|
Package termx probes the terminal/environment context shared by the CLI format axis and the (reserved) style axis: whether an output writer is an interactive terminal, and whether colour is suppressed by the environment.
|
Package termx probes the terminal/environment context shared by the CLI format axis and the (reserved) style axis: whether an output writer is an interactive terminal, and whether colour is suppressed by the environment. |