Documentation
¶
Overview ¶
Package chok is the v2 application shell: explicit typed assembly over the kernel control plane. The whole wiring of an app is
chok.New("blog",
chok.Use(log.Module(), web.Module(), db.Module(...)),
chok.Routes(registerRoutes),
).Execute()
No reflection scanning, no auto-registration: what you Use is what links, yaml stays the runtime switch (SPEC §3.1).
Index ¶
- func Get[T any](k Kernel, kind string, instance ...string) (T, bool)
- type App
- type Component
- type Kernel
- type Middleware
- type Option
- func Override(c Component) Option
- func Routes(f func(r Router, k Kernel) error) Option
- func Use(modules ...Component) Option
- func WithCloseTimeout(d time.Duration) Option
- func WithComponentReloadTimeout(d time.Duration) Option
- func WithConfigFile(path string) Option
- func WithDrainDelay(d time.Duration) Option
- func WithEnvPrefix(prefix string) Option
- func WithErrorMapper(m apierr.ErrorMapper) Option
- func WithFlags(fs *pflag.FlagSet) Option
- func WithInitTimeout(d time.Duration) Option
- func WithLogger(l log.Logger) Option
- func WithReloadFunc(f func(context.Context) error) Option
- func WithReloadTimeout(d time.Duration) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithVersion(v version.Info) Option
- type Router
- type RunOption
- type SectionHandle
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the single-use application container.
func New ¶
New constructs an App. Assembly problems (duplicate keys, Override on a missing key, config validation) surface at Run — fail-fast at startup, never silently.
func (*App) ErrorMappers ¶
func (a *App) ErrorMappers() *apierr.MapperRegistry
ErrorMappers exposes the per-App error mapper registry (consumed by the web middleware stack from M2 on).
func (*App) Execute ¶
func (a *App) Execute()
Execute runs the app with OS signal handling and exits non-zero on error. main() convenience; tests use Run.
func (*App) Kernel ¶
Kernel returns the running kernel (nil before Run) — mainly for tests and advanced integrations; components receive it in Init.
func (*App) Logger ¶
Logger returns the root logger. Before Run it returns the injected logger or an inert one — startup/shutdown logging only; request-path code uses the context logger.
type Component ¶
Component is what Use assembles; built-in modules construct theirs via their Module() functions.
type Kernel ¶
Kernel is the component-lookup handle passed to Routes and consumed by the battery accessors (db.From, log.From, ...).
type Middleware ¶
type Middleware = kernel.Middleware
Middleware is the framework-wide middleware shape: a plain http.Handler decorator.
type Option ¶
type Option func(*App)
Option configures an App at construction time.
func Override ¶
Override replaces a previously Use'd module with the same (kind, instance) key. A key that matches nothing fails startup — silent-miss typos are the failure mode this guards.
func Routes ¶
Routes registers the business route callback, invoked during the mount phase between MountOrder ≤ 0 and > 0 mounters.
func Use ¶
Use assembles modules. The one registration surface: duplicate (kind, instance) keys fail startup — intentional replacement is spelled chok.Override (SPEC §3.1).
func WithCloseTimeout ¶
WithCloseTimeout sets the default per-component Close budget (default 15s).
func WithComponentReloadTimeout ¶
WithComponentReloadTimeout sets the default per-component Reload budget (default 10s).
func WithConfigFile ¶
WithConfigFile pins an explicit config path (a missing file is then an error). Without it: {PREFIX}_CONFIG → ./{name}.yaml → ./configs/{name}.yaml, all optional.
func WithDrainDelay ¶
WithDrainDelay pauses between readiness flipping to 503 (draining phase begins) and Serve contexts being cancelled — load balancers deregister the pod before in-flight work is cut.
func WithEnvPrefix ¶
WithEnvPrefix overrides the env prefix (default: upper-cased app name with -/. mapped to _).
func WithErrorMapper ¶
func WithErrorMapper(m apierr.ErrorMapper) Option
WithErrorMapper registers a per-App error mapper (isolated from other App instances). The web middleware stack consumes the registry from M2 on.
func WithFlags ¶
WithFlags binds a parsed pflag set as the highest-priority config source (flags > env > file > defaults).
func WithInitTimeout ¶
WithInitTimeout sets the default per-component Init/Migrate budget (Descriptor.Timeouts overrides per component; default 30s).
func WithLogger ¶
WithLogger injects a prebuilt root logger. Its lifecycle belongs to the caller — the App only closes loggers it constructed itself.
func WithReloadFunc ¶
WithReloadFunc registers the synchronous post-reload callback: the last stage of the reload pipeline. It runs only when config swap and component dispatch both succeeded, and its error fails the whole reload (v1 gating contract, SPEC §9).
func WithReloadTimeout ¶
WithReloadTimeout bounds one whole reload pipeline (default 30s).
func WithShutdownTimeout ¶
WithShutdownTimeout bounds the whole stop sequence (drain + close; default 30s). SIGQUIT further caps it at 5s for fast shutdown.
func WithVersion ¶
WithVersion attaches build/version metadata.
type Router ¶
Router is the route-registration contract handed to the Routes callback (contract in kernel, implementation in web).
type RunOption ¶
type RunOption func(*runConfig)
RunOption configures a single Run call.
func WithConfigWatch ¶
func WithConfigWatch() RunOption
WithConfigWatch reloads on config file changes (fsnotify, 100ms debounce, content-hash suppression for k8s ConfigMap rotations). No-op with a warning when no config file was loaded.
func WithSignals ¶
func WithSignals() RunOption
WithSignals enables OS signal handling: SIGTERM/SIGINT graceful stop, SIGQUIT fast stop, SIGHUP reload.
type SectionHandle ¶
type SectionHandle[T any] struct { // contains filtered or unexported fields }
SectionHandle is the typed accessor for one business config section.
func Section ¶
func Section[T any](a *App, key string) *SectionHandle[T]
Section registers a typed business config section and returns its handle. Must be called before Run — the loader needs the complete type set to bind env vars, apply defaults and validate (SPEC §3.4); calling it after Run panics.
func (*SectionHandle[T]) Get ¶
func (h *SectionHandle[T]) Get() T
Get decodes the section from the current snapshot. The value is a copy — treat it as immutable, re-Get after reloads. Panics when called before Run (no snapshot exists yet).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package account provides a ready-to-use user module with registration, login, token refresh, and password management.
|
Package account provides a ready-to-use user module with registration, login, token refresh, and password management. |
|
internal/testfake
Package testfake supplies a deterministic AuthProvider implementation for in-process OAuth flow tests.
|
Package testfake supplies a deterministic AuthProvider implementation for in-process OAuth flow tests. |
|
providers/apple
Package apple provides chok's Apple Sign-In implementation of account.AuthProvider.
|
Package apple provides chok's Apple Sign-In implementation of account.AuthProvider. |
|
providers/facebook
Package facebook provides chok's Facebook OAuth 2.0 implementation of account.AuthProvider.
|
Package facebook provides chok's Facebook OAuth 2.0 implementation of account.AuthProvider. |
|
providers/github
Package github provides chok's GitHub OAuth 2.0 implementation of account.AuthProvider.
|
Package github provides chok's GitHub OAuth 2.0 implementation of account.AuthProvider. |
|
providers/google
Package google provides chok's Google OAuth 2.0 + OpenID Connect implementation of account.AuthProvider.
|
Package google provides chok's Google OAuth 2.0 + OpenID Connect implementation of account.AuthProvider. |
|
Package audit is chok's compliance-grade audit log battery.
|
Package audit is chok's compliance-grade audit log battery. |
|
Package auth provides authentication primitives: identity context, password hashing, and JWT token management (in the jwt sub-package).
|
Package auth provides authentication primitives: identity context, password hashing, and JWT token management (in the jwt sub-package). |
|
jwt
Package jwt provides an instance-based JWT manager using HS256.
|
Package jwt provides an instance-based JWT manager using HS256. |
|
Package authz defines the authorization interface.
|
Package authz defines the authorization interface. |
|
casbin
Package casbin doc.go is intentionally empty — the package-level godoc lives at the top of options.go where Builder, Service, and the Options type are introduced.
|
Package casbin doc.go is intentionally empty — the package-level godoc lives at the top of options.go where Builder, Service, and the Options type are introduced. |
|
Package cache provides a pluggable caching layer with memory, file, and Redis backends.
|
Package cache provides a pluggable caching layer with memory, file, and Redis backends. |
|
Package choktest provides test utilities for applications built on chok.
|
Package choktest provides test utilities for applications built on chok. |
|
cmd
|
|
|
chok
command
|
|
|
Package conf is the chok v2 configuration engine: a viper-backed loader (file + env + flag, v1-compatible precedence) that produces immutable snapshots published via RCU.
|
Package conf is the chok v2 configuration engine: a viper-backed loader (file + env + flag, v1-compatible precedence) that produces immutable snapshots published via RCU. |
|
dbtest
Package dbtest is the shared test-support opener behind the M3 SQLite+Postgres dual-run (SPEC §5.3 / §12.6 budget: the database matrix covers the store/db packages only).
|
Package dbtest is the shared test-support opener behind the M3 SQLite+Postgres dual-run (SPEC §5.3 / §12.6 budget: the database matrix covers the store/db packages only). |
|
internal/testlane
Package testlane provisions the per-test database lane behind the SQLite+Postgres dual-run without importing the db package — the dependency-free half of dbtest, shared by db's own internal tests (which cannot import dbtest: dbtest imports db, and an internal test closing that loop is an import cycle).
|
Package testlane provisions the per-test database lane behind the SQLite+Postgres dual-run without importing the db package — the dependency-free half of dbtest, shared by db's own internal tests (which cannot import dbtest: dbtest imports db, and an internal test closing that loop is an import cycle). |
|
Package debug is the chok v2 introspection module: /componentz renders the assembled component topology straight from Descriptor data (single source of truth, SPEC axiom 5) plus a bounded history of lifecycle events from the bus.
|
Package debug is the chok v2 introspection module: /componentz renders the assembled component topology straight from Descriptor data (single source of truth, SPEC axiom 5) plus a bounded history of lifecycle events from the bus. |
|
examples
|
|
|
blog
command
Command blog is the chok v2 quickstart: a JWT-guarded blog API with owner-scoped posts in about a hundred lines of application code.
|
Command blog is the chok v2 quickstart: a JWT-guarded blog API with owner-scoped posts in about a hundred lines of application code. |
|
Package handler is chok's typed request layer: generic HandleRequest / HandleAction / HandleList constructors that bind path + query + JSON sources into one request struct, validate it, call the business function and render the uniform success / apierr envelope.
|
Package handler is chok's typed request layer: generic HandleRequest / HandleAction / HandleList constructors that bind path + query + JSON sources into one request struct, validate it, call the business function and render the uniform success / apierr envelope. |
|
Package health is the chok v2 health module: /healthz (full diagnostic report), /livez (process liveness) and /readyz (traffic-worthiness incl.
|
Package health is the chok v2 health module: /healthz (full diagnostic report), /livez (process liveness) and /readyz (traffic-worthiness incl. |
|
internal
|
|
|
blessed
Package blessed is the single inventory of chok's built-in modules and account providers — the one table the CLI generators (chok sync, chok docs gen, the JSON-Schema emitter) consume.
|
Package blessed is the single inventory of chok's built-in modules and account providers — the one table the CLI generators (chok sync, chok docs gen, the JSON-Schema emitter) consume. |
|
clientip
Package clientip resolves the real client address behind reverse proxies — the stdlib replacement for gin's ClientIP/SetTrustedProxies pair (SPEC §4.2 item 4, security-sensitive: this value keys the account login rate limiter).
|
Package clientip resolves the real client address behind reverse proxies — the stdlib replacement for gin's ClientIP/SetTrustedProxies pair (SPEC §4.2 item 4, security-sensitive: this value keys the account login rate limiter). |
|
docgen
Package docgen renders the generated documentation surfaces — components table, configuration reference, JSON Schema — from the blessed inventory plus reflection over each module's Options type (axiom 5: docs are outputs, Descriptor and Options are the truth).
|
Package docgen renders the generated documentation surfaces — components table, configuration reference, JSON Schema — from the blessed inventory plus reflection over each module's Options type (axiom 5: docs are outputs, Descriptor and Options are the truth). |
|
fixture/m1
command
Command m1 is the M1 milestone fixture app (SPEC §10 coexistence strategy): the smallest assembly that exercises the v2 kernel with the four migrated modules.
|
Command m1 is the M1 milestone fixture app (SPEC §10 coexistence strategy): the smallest assembly that exercises the v2 kernel with the four migrated modules. |
|
fixture/m2
command
Command m2 is the M2 milestone fixture app (SPEC §10 coexistence strategy): the smallest assembly that exercises the v2 web stack over real HTTP.
|
Command m2 is the M2 milestone fixture app (SPEC §10 coexistence strategy): the smallest assembly that exercises the v2 web stack over real HTTP. |
|
fixture/m3
command
Command m3 is the M3 milestone fixture app (SPEC §10 coexistence strategy): the M2 web assembly plus the v2 data layer — db.Module in versioned migration mode, a store-backed API with every safety rail on, and WithBus events consumed off the kernel bus.
|
Command m3 is the M3 milestone fixture app (SPEC §10 coexistence strategy): the M2 web assembly plus the v2 data layer — db.Module in versioned migration mode, a store-backed API with every safety rail on, and WithBus events consumed off the kernel bus. |
|
fixture/m4
command
Command m4 is the M4 milestone fixture app (SPEC §10 coexistence strategy): the full-battery assembly — every migrated module in one process, wired the way a real deployment would be.
|
Command m4 is the M4 milestone fixture app (SPEC §10 coexistence strategy): the full-battery assembly — every migrated module in one process, wired the way a real deployment would be. |
|
promutil
Package promutil contains the small Prometheus registration helpers shared by framework modules.
|
Package promutil contains the small Prometheus registration helpers shared by framework modules. |
|
testschema
Package testschema contains repository-internal assertions that compare a component's schema declaration with the tables created by its real kernel migration lifecycle.
|
Package testschema contains repository-internal assertions that compare a component's schema declaration with the tables created by its real kernel migration lifecycle. |
|
testseq
Package testseq provides migration-sequence test infrastructure shared by chok's built-in batteries.
|
Package testseq provides migration-sequence test infrastructure shared by chok's built-in batteries. |
|
txctx
Package txctx carries the context plumbing of the RunInTx transaction model: the active *gorm.DB transaction plus its owning *db.DB identity.
|
Package txctx carries the context plumbing of the RunInTx transaction model: the active *gorm.DB transaction plus its owning *db.DB identity. |
|
Package kernel is the chok v2 component model: a declarative Descriptor, a small set of behaviour interfaces discovered by type assertion, and a single-actor control plane (Registry) that owns every lifecycle transition.
|
Package kernel is the chok v2 component model: a declarative Descriptor, a small set of behaviour interfaces discovered by type assertion, and a single-actor control plane (Registry) that owns every lifecycle transition. |
|
event
Package event is the chok v2 business event bus: typed pub/sub with per-subscriber bounded queues.
|
Package event is the chok v2 business event bus: typed pub/sub with per-subscriber bounded queues. |
|
Package metrics is the chok v2 Prometheus module: it owns the process metrics registry (Go runtime + process collectors included) and exposes it over /metrics.
|
Package metrics is the chok v2 Prometheus module: it owns the process metrics registry (Go runtime + process collectors included) and exposes it over /metrics. |
|
Package middleware is chok's http.Handler decorator set — the v2 (stdlib) rewrite of the gin middleware stack.
|
Package middleware is chok's http.Handler decorator set — the v2 (stdlib) rewrite of the gin middleware stack. |
|
Package redis is the chok v2 redis battery: a shared *redis.Client as a kernel component plus the library-level constructor and TLS helper for kernel-less use.
|
Package redis is the chok v2 redis battery: a shared *redis.Client as a kernel component plus the library-level constructor and TLS helper for kernel-less use. |
|
Package rid generates resource identifiers.
|
Package rid generates resource identifiers. |
|
Package scheduler wraps robfig/cron/v3 for running periodic background jobs with panic-safe execution, per-job overlap policies, and observable statistics.
|
Package scheduler wraps robfig/cron/v3 for running periodic background jobs with panic-safe execution, per-job overlap policies, and observable statistics. |
|
Package store provides a generic CRUD store backed by GORM.
|
Package store provides a generic CRUD store backed by GORM. |
|
where
Package where provides query building options for store operations.
|
Package where provides query building options for store operations. |
|
Package swagger provides automatic OpenAPI 3.0 spec generation from chok's typed handler system.
|
Package swagger provides automatic OpenAPI 3.0 spec generation from chok's typed handler system. |
|
Package tracing is the chok v2 OpenTelemetry module: it owns the SDK TracerProvider lifecycle (build at Init when enabled, install as the otel global, drain at Close).
|
Package tracing is the chok v2 OpenTelemetry module: it owns the SDK TracerProvider lifecycle (build at Init when enabled, install as the otel global, drain at Close). |
|
Package version exposes build / VCS / runtime metadata.
|
Package version exposes build / VCS / runtime metadata. |
|
Package web is the chok v2 HTTP layer: a stdlib http.Server plus a ServeMux-backed implementation of the kernel Router/RouterProvider contracts (SPEC §4).
|
Package web is the chok v2 HTTP layer: a stdlib http.Server plus a ServeMux-backed implementation of the kernel Router/RouterProvider contracts (SPEC §4). |