Documentation
¶
Index ¶
- Variables
- type App
- func (a *App) API(relativePath string, middlewares ...gin.HandlerFunc) *gin.RouterGroup
- func (a *App) AccessLogEnabled() bool
- func (a *App) AccessLogger() log.Logger
- func (a *App) AddCleanup(f func(context.Context) error)
- func (a *App) AddServer(srv Server)
- func (a *App) AuthMiddleware() gin.HandlerFunc
- func (a *App) Cacher() cache.Cache
- func (a *App) ConfigSnapshotRLock() (unlock func())
- func (a *App) DB() any
- func (a *App) ErrorMappers() *apierr.MapperRegistry
- func (a *App) Execute()
- func (a *App) Logger() log.Logger
- func (a *App) On(event component.Event, hook component.Hook)
- func (a *App) Register(c component.Component)
- func (a *App) Registry() *component.Registry
- func (a *App) Reload(ctx context.Context) error
- func (a *App) ReloadConfig() (bool, map[string]bool, error)
- func (a *App) Replace(c component.Component)
- func (a *App) Run(ctx context.Context, opts ...RunOption) error
- func (a *App) SetCacher(c cache.Cache)
- func (a *App) SetDB(gdb any)
- type Option
- func WithCacheConfig(memory *config.CacheMemoryOptions, file *config.CacheFileOptions) Option
- func WithCleanup(f func(context.Context) error) Option
- func WithCloseTimeout(d time.Duration) Option
- func WithComponentReloadTimeout(d time.Duration) Option
- func WithConfig(cfg any, 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 WithHealthTimeout(d time.Duration) Option
- func WithHookTimeout(d time.Duration) Option
- func WithInitTimeout(d time.Duration) Option
- func WithLogConfig(opts *config.SlogOptions) Option
- func WithLogger(l log.Logger) Option
- func WithReloadFunc(f func(context.Context) error) Option
- func WithReloadTimeout(d time.Duration) Option
- func WithRoutes(f func(context.Context, *App) error) Option
- func WithSetup(f func(context.Context, *App) error) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithTables(tables ...db.TableSpec) Option
- func WithVersion(v version.Info) Option
- type RunOption
- type Server
Constants ¶
This section is empty.
Variables ¶
var ErrReloadInProgress = errors.New("chok: reload already in progress")
ErrReloadInProgress is returned by Reload when another reload is already executing. Callers triggered by external events (SIGHUP, fsnotify, admin API) should treat this as benign — the in-flight reload will pick up the latest on-disk config when it re-reads.
var ErrServerUnexpectedExit = errors.New("chok: server exited unexpectedly without being stopped")
ErrServerUnexpectedExit is returned when a server's Start returns without being triggered by Stop.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the application instance.
Thread-safety: fields written during setup (before Run's registry publish) and read during request handling (cacher, gormDB, registry, logger) must be accessed under registryMu. shutdownDeadline is written during shutdown and read both from shutdown paths and from cleanup — atomic.Int64 (unix nanos) keeps reads lock-free.
func (*App) API ¶
func (a *App) API(relativePath string, middlewares ...gin.HandlerFunc) *gin.RouterGroup
API returns a gin.RouterGroup for the given path prefix, ready for registering business routes. Panics if no HTTP server is available.
Typical usage inside WithRoutes:
api := a.API("/api/v1")
handler.RegisterPostRoutes(api, store)
func (*App) AccessLogEnabled ¶
AccessLogEnabled reports whether the application should mount its own HTTP access log middleware. Defaults to true; set log.access_enabled: false to suppress (e.g. when a fronting proxy already records access logs). When logOpts is nil (no log config wired), defaults to true to match the historical behavior of the AccessLog middleware.
func (*App) AccessLogger ¶
AccessLogger returns the logger dedicated to access-log entries (HTTP request trace). Falls back to the main Logger() when log.access_files is not configured, so middleware code can call this unconditionally.
func (*App) AddCleanup ¶
AddCleanup registers a cleanup callback (LIFO order on shutdown). Cleanups run after registry.Stop — use AddCleanup for resources owned by user code outside the Component abstraction (e.g. ad-hoc goroutines). Components should release their own resources via Component.Close.
The callback's ctx carries the original Run-time values (trace_id, request_id, logger) and a deadline derived from the shutdown budget. Its cancellation is intentionally detached from the parent ctx so cleanup keeps making progress even after a shutdown signal cancels the upstream context.
The component registry is already torn down when cleanups run — App.Cacher(), App.DB(), and Registry().Get() all return nil or already-closed instances at this point. Cleanups that need access to a long-lived resource should capture it explicitly during Setup rather than re-fetch it on shutdown.
func (*App) AuthMiddleware ¶
func (a *App) AuthMiddleware() gin.HandlerFunc
AuthMiddleware returns a gin middleware that authenticates requests via the AccountComponent's JWT token parser. Returns a no-op middleware if no AccountComponent is registered or if it's disabled.
Typical usage:
api := a.API("/api/v1", a.AuthMiddleware())
func (*App) ConfigSnapshotRLock ¶
func (a *App) ConfigSnapshotRLock() (unlock func())
ConfigSnapshotRLock exposes the reader side of the config mutex so callers that absolutely must read live config fields directly (rather than via Kernel.ConfigSnapshot) can serialize with reload writes. Prefer ConfigSnapshot for new code — this is an escape hatch for legacy integrations.
func (*App) DB ¶
DB returns the application's *gorm.DB. It checks, in order:
- Explicit value set via SetDB in the setup callback.
- The DBComponent in the registry (auto-registered or explicit).
Returns nil if no database is configured. The caller must type-assert:
gdb := a.DB().(*gorm.DB)
func (*App) ErrorMappers ¶
func (a *App) ErrorMappers() *apierr.MapperRegistry
ErrorMappers returns the App's scoped error mapper registry. Returns nil when no WithErrorMapper options were configured. User code can register additional mappers at runtime (thread-safe), though registering at construction via WithErrorMapper is preferred.
func (*App) Execute ¶
func (a *App) Execute()
Execute is the only method that calls os.Exit. It runs with signals enabled.
func (*App) On ¶
On subscribes hook to the given lifecycle event. Usable before the registry exists (e.g. from inside setupFn) — the hook is queued and transferred to the registry when it's built.
Classic use: mount Router components on an HTTP engine inside an EventAfterStart hook, since by then every Component has Init'd and the Router's target resource (gin engine, gRPC server) is safe to wire up:
a.On(component.EventAfterStart, func(ctx context.Context) error {
engine := srv.Engine()
for _, name := range []string{"swagger", "account"} {
if r, ok := a.Registry().Get(name).(component.Router); ok {
if err := r.Mount(engine); err != nil { return err }
}
}
return nil
})
func (*App) Register ¶
Register adds a Component that will be managed by the App's internal component.Registry. Components are Init'd (in topological order by declared Dependencies) after the Setup callback runs and before servers start. On shutdown, they're Close'd in reverse order, ahead of AddCleanup callbacks.
Must be called before Run/Execute. Calling after the registry has been constructed panics — a misconfigured registration is a bug worth catching at the earliest point.
func (*App) Registry ¶
Registry exposes the App's internal component.Registry. Only valid after Run has built the registry (i.e. from inside a component's Init, from AddCleanup, or from the user's reload callback). Before then it returns nil.
Typical uses: fetching a Component by name during a reload callback (e.g. app.Registry().Reload(ctx) from a SIGHUP handler) or inspecting the Health report.
func (*App) Reload ¶
Reload is the unified reload entry point. It performs, in order:
- Re-read the config file + env (ReloadConfig). Validation errors abort reload — the old config keeps running.
- Dispatch Reload to every Reloadable Component registered with the internal registry. Errors are logged; peers still get their chance to absorb new config.
- Invoke the user's reloadFn (WithReloadFunc) for ad-hoc work that doesn't fit the Component model.
Reload is public so external triggers (fsnotify, admin HTTP, tests) can invoke the same sequence as SIGHUP. Safe to call at any point after Run has built the registry; earlier calls skip the registry step.
Concurrent invocations are coalesced: only one Reload runs at a time. Callers that arrive while a reload is already executing receive ErrReloadInProgress immediately rather than queueing. Queueing would let a slow reload cascade-block subsequent triggers (and ultimately the main loop), and the second caller would re-read stale config anyway since the in-flight reload already took the latest snapshot.
func (*App) ReloadConfig ¶
ReloadConfig re-reads the config file and env vars using a two-phase approach: unmarshal into a fresh copy, validate, then atomically copy the result into the live config struct. On any failure the live config is left completely untouched — no partial field writes. Returns (changed, changedSections, error) where changed indicates if the config values actually differ from the previous config, and changedSections maps top-level config keys to whether they changed.
func (*App) Replace ¶
Replace registers a Component that explicitly replaces any previously registered Component with the same Name. Unlike Register (which panics on duplicates at Registry level), Replace is the intended mechanism for overriding auto-registered or framework-provided Components with custom implementations.
Must be called before Run/Execute. Calling after the registry has been constructed panics.
func (*App) Run ¶
Run is the pure lifecycle method. It can be called in tests (no os.Exit, no signals by default). App is single-use: calling Run or Execute more than once returns an error.
func (*App) SetCacher ¶
SetCacher registers a Cache on the App. Typically called in Setup to override the auto-built cache (initCache runs before setupFn, so Cacher() is already populated; SetCacher replaces it). autoRegisterCache — which runs after Setup — picks up the final value, so the CacheComponent always reflects whatever SetCacher set.
The cache lifecycle is owned by CacheComponent.Close — no separate AddCleanup is needed.
Thread-safe: serialized via registryMu so concurrent Cacher() readers (e.g. running HTTP handlers) never observe a torn write.
type Option ¶
type Option func(*App)
Option configures an App.
func WithCacheConfig ¶
func WithCacheConfig(memory *config.CacheMemoryOptions, file *config.CacheFileOptions) Option
WithCacheConfig points to cache config options inside the typed config. After config loading, the framework auto-builds the cache from enabled layers. SetCacher() in Setup overrides the auto-built cache. Pointers are dereferenced after config loading (same timing as WithLogConfig).
func WithCleanup ¶
WithCleanup registers a cleanup callback, called LIFO when Run ends.
func WithCloseTimeout ¶
WithCloseTimeout sets the default per-component Close timeout. If a component implements CloseTimeouter, its value takes precedence. Default is 15s. Zero disables the timeout.
func WithComponentReloadTimeout ¶
WithComponentReloadTimeout sets the default per-component Reload timeout. If a component implements ReloadTimeouter, its value takes precedence. Default is 10s. Zero disables the timeout.
func WithConfig ¶
WithConfig registers a typed config pointer and optional explicit path. The pointer is populated during Run() after config loading.
func WithDrainDelay ¶
WithDrainDelay sets a pause between marking readyz as 503 and actually stopping HTTP servers. In Kubernetes deployments this gives the load balancer time to deregister the pod from endpoints before in-flight requests are drained. Zero (the default) means no delay.
The delay is bounded by the overall shutdown timeout — if the remaining budget is less than the configured drain delay, the shorter value wins.
func WithEnvPrefix ¶
func WithErrorMapper ¶
func WithErrorMapper(m apierr.ErrorMapper) Option
WithErrorMapper registers an error mapper scoped to this App instance. Unlike the global apierr.RegisterMapper, scoped mappers are isolated per App — safe for parallel tests and multi-App scenarios.
Scoped mappers are checked before global mappers when resolving errors in HTTP handlers. The mapper is injected into request context via middleware, so all handlers mounted on this App benefit automatically.
chok.New("blog",
chok.WithErrorMapper(store.MapError),
)
func WithFlags ¶
WithFlags registers a parsed pflag.FlagSet. CLI flags take highest priority: flags > env > file > default tag. pflag is already an indirect dependency via Viper.
func WithHealthTimeout ¶
WithHealthTimeout sets the per-probe Health timeout. Each Healther probe runs concurrently and is given at most this duration. A hard fan-in deadline (timeout + 1s) ensures rogue probes that ignore their context cannot block the entire /healthz endpoint. Default is 3s. Zero disables the timeout.
func WithHookTimeout ¶
WithHookTimeout sets the aggregate timeout for lifecycle hook execution. When set, EventBeforeStop and EventBeforeReload hooks are bounded by this duration — a slow hook cannot block the shutdown sequence past the Kubernetes terminationGracePeriod. Default is 10s. Zero disables the timeout.
func WithInitTimeout ¶
WithInitTimeout sets the default per-component startup-phase timeout, covering both Init and Migrate. If a component implements InitTimeouter, its value takes precedence. Default is 30s. Zero disables the timeout. For long-running schema migrations, increase this value or implement InitTimeouter on the DBComponent.
func WithLogConfig ¶
func WithLogConfig(opts *config.SlogOptions) Option
WithLogConfig points to the SlogOptions inside the typed config. The pointer is dereferenced after config loading, before Setup.
func WithLogger ¶
WithLogger injects a Logger directly (highest priority).
func WithReloadTimeout ¶
func WithRoutes ¶
WithRoutes registers a callback that runs inside an EventAfterStart hook — after every Component has Init'd and all non-swagger Router Components have been mounted. Use it to wire business routes without manual hook orchestration:
chok.WithRoutes(func(ctx context.Context, a *chok.App) error {
api := a.API("/api/v1")
handler.RegisterPostRoutes(api, postStore)
return nil
})
The framework mounts swagger AFTER this callback returns, so Populate() sees every route registered here.
func WithShutdownTimeout ¶
func WithTables ¶
WithTables declares database table specs (model + indexes) for the auto-registered DBComponent. When the config struct contains a SQLiteOptions or MySQLOptions field and no "db" Component is registered explicitly, the framework auto-registers a DBComponent that migrates these tables at startup.
chok.WithTables(
db.Table(&Post{}, db.SoftUnique("uk_slug", "slug")),
)
func WithVersion ¶
type RunOption ¶
type RunOption func(*runConfig)
RunOption configures a Run() call.
func WithConfigWatch ¶
func WithConfigWatch() RunOption
WithConfigWatch enables fsnotify-based watching of the config file. When the file is written (or replaced by an atomic-save editor), App.Reload is invoked with the same dispatch path as SIGHUP — the config re-reads, every Reloadable Component gets its Reload call, and the optional WithReloadFunc runs last.
Requires WithConfig to have registered a non-empty path; if the app was started without an explicit config file this option becomes a no-op (logged at Warn at startup).
Events are debounced by 100ms so a single save that triggers multiple Write syscalls produces exactly one Reload.
func WithSignals ¶
func WithSignals() RunOption
WithSignals enables OS signal handling (SIGTERM/SIGINT/SIGHUP/SIGQUIT).
type Server ¶
type Server interface {
Start(ctx context.Context, ready func()) error
Stop(ctx context.Context) error
}
Server is the interface all managed servers must implement.
Start(ctx, ready) blocks until Stop is called. ready() must be called exactly once after the server is ready to serve. Stop(ctx) is the sole shutdown trigger; it must be idempotent and safe to call at any point, including before Start has been called.
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. |
|
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. |
|
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 component defines the Component abstraction that unifies every subsystem in chok (logger, db, cache, scheduler, auth, ...) under a single lifecycle + configuration + health + reload contract.
|
Package component defines the Component abstraction that unifies every subsystem in chok (logger, db, cache, scheduler, auth, ...) under a single lifecycle + configuration + health + reload contract. |
|
examples
|
|
|
blog/cmd/blog
command
|
|
|
blog/internal/app
Package app wires chok Components into the blog example.
|
Package app wires chok Components into the blog example. |
|
internal
|
|
|
Package parts contains concrete Component implementations for chok's built-in subsystems (logger, redis, db, cache, scheduler, ...).
|
Package parts contains concrete Component implementations for chok's built-in subsystems (logger, redis, db, cache, scheduler, ...). |
|
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 version exposes build / VCS / runtime metadata.
|
Package version exposes build / VCS / runtime metadata. |