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 ¶
- Variables
- func Main(cmds ...Definable)
- func MainConfig(cfg Config)
- 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 HTTPFieldHint
- type HTTPHints
- type Handler
- type MCPFieldHint
- type MCPHints
- type ModeWords
Constants ¶
This section is empty.
Variables ¶
var Version = "dev"
Version is the version reported by the -v/--version handling in Run / Main. Override it in code, or inject at build time with -ldflags "-X github.com/ejfkdev/xyz-go.Version=v1.2.3". (The cli frontend keeps its own Version for direct embedding via cli.Run.)
Functions ¶
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 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
}
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 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"。
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. |