chok

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 30 Imported by: 0

README

中文 | English

MIT Go Reference CI

chok

An opinionated, configuration-driven Go web framework.


chok bundles HTTP, database, cache, JWT auth, scheduler, and observability into a single Go module. One YAML file enables or disables every subsystem; all wiring is generated from your config struct.

# chok.yaml
http:      { addr: ":8080" }
log:       { level: info, format: json, output: [stdout] }
database:  { driver: sqlite, sqlite: { path: "app.db" } }
account:   { enabled: true, signing_key: "..." }
swagger:   { enabled: true, title: "My API" }
// main.go — three lines wire the entire app
type Config struct {
    HTTP     config.HTTPOptions     `mapstructure:"http"`
    Log      config.SlogOptions     `mapstructure:"log"`
    Database config.DatabaseOptions `mapstructure:"database"`
    Account  config.AccountOptions  `mapstructure:"account"`
    Swagger  config.SwaggerOptions  `mapstructure:"swagger"`
}

var cfg Config

func main() {
    chok.New("myapp",
        chok.WithConfig(&cfg),
        chok.WithRoutes(func(_ context.Context, a *chok.App) error {
            a.API("/api/v1", a.AuthMiddleware()).GET("/me", meHandler)
            return nil
        }),
    ).Execute()
}

That's an HTTP server with JSON logging, SQLite + auto-migration, JWT-backed /auth/register|login|refresh-token|change-password|..., an OpenAPI 3.0 spec at /swagger, /healthz /livez /readyz for Kubernetes, and a Prometheus /metrics endpoint — without a single explicit Register call.

Design

Three immutable adjectives:

  • Config-driven. enabled: true|false is the primary on/off switch. Code changes are reserved for business logic, not subsystem assembly.
  • One blessed implementation per capability. HTTP is gin. ORM is gorm. Cache is Otter + Badger + Redis. Cron is robfig. JWT is golang-jwt. Tracing is OpenTelemetry. No parallel choices.
  • Internally complex, externally trivial. A Component abstraction with topological lifecycle, hot-reload dispatch, and health aggregation hides behind app.Register(c) and app.Logger().

Quick start

go install github.com/zynthara/chok/cmd/chok@latest

chok init myapp
cd myapp && go mod tidy && make run

The scaffold ships with cmd/, internal/{app,handler}, configs/, a Makefile that injects build metadata via ldflags, and a chok.yaml that enables HTTP + logging + SQLite + JWT auth + Swagger. Hit http://127.0.0.1:8080/healthz to confirm the boot.

Built-in Components

15 subsystems, each registered as a Component with Init / Close and optional Reload / Health / Router / Migrate capabilities. Most auto-register from your Config struct; the rest you opt into in WithSetup.

Component Auto-register Selected by Capability
LoggerComponent yes SlogOptions logger + access log + reload
HTTPComponent yes HTTPOptions gin server + middleware stack
DBComponent yes DatabaseOptions gorm + auto-migrate (sqlite/mysql)
RedisComponent yes RedisOptions go-redis client + health
CacheComponent yes CacheMemory/FileOptions memory + file + Redis chain
AccountComponent yes AccountOptions register / login / JWT / reset
SwaggerComponent yes SwaggerOptions OpenAPI 3.0 + Swagger UI
HealthComponent yes (whenever HTTP) /healthz /livez /readyz
MetricsComponent yes (whenever HTTP) Prometheus /metrics
DebugComponent yes DebugOptions /componentz topology dump
TracingComponent explicit code OTel tracer + OTLP exporter
SchedulerComponent explicit code robfig cron with stats
PoolComponent explicit code bounded async worker pool
JWTComponent explicit code extra JWT managers
AuthzComponent explicit code pluggable authorizer

Custom components implement the same interface and integrate with the registry's lifecycle, hot-reload, and health checks. See docs/design.md §13.

CLI

chok init <name>          # scaffold a new project
chok version [--json]     # build / VCS / runtime metadata
chok update [--ref vX.Y]  # upgrade the local CLI via go install

Version metadata resolves in order: ldflags injected by make build / goreleaser → debug.ReadBuildInfo (so go install ...@latest shows a real pseudo-version + git hash) → dev / unknown fallback.

Examples

Path What it shows
examples/blog Quickstart-grade: HTTP + SQLite + JWT + Swagger + a single Post resource with optimistic locking, soft delete, and owner scope. Boot in 5 minutes.

A full-coverage example (examples/tasker) exercising every Component and custom-component pattern is on the roadmap; see docs/roadmap.md.

Documentation

Topic Where
Architecture & API contracts docs/design.md
Design changelog (per release) docs/changelog.md
Roadmap docs/roadmap.md
GoDoc reference https://pkg.go.dev/github.com/zynthara/chok
Agent / AI assistant guidance CLAUDE.md, AGENTS.md

Contributing

Conventional commits (feat:, fix:, docs:, chore:) drive release-please's automatic versioning and CHANGELOG generation. Tag push triggers a goreleaser build for linux / darwin / windows × amd64 / arm64.

make all      # tidy + lint + test + build
make smoke    # boot examples/blog as a sanity check
make snapshot # run goreleaser locally without publishing

The hard rules and the architectural invariants the project tries to preserve are documented in CLAUDE.md.

License

Released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
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.

View Source
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 New

func New(name string, opts ...Option) *App

New creates an App (pure construction, zero side effects).

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

func (a *App) AccessLogEnabled() bool

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

func (a *App) AccessLogger() log.Logger

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

func (a *App) AddCleanup(f func(context.Context) error)

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) AddServer

func (a *App) AddServer(srv Server)

AddServer registers a Server to be managed by Run.

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) Cacher

func (a *App) Cacher() cache.Cache

Cacher returns the registered Cache, or nil if none was set.

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

func (a *App) DB() any

DB returns the application's *gorm.DB. It checks, in order:

  1. Explicit value set via SetDB in the setup callback.
  2. 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) Logger

func (a *App) Logger() log.Logger

Logger returns the current logger.

func (*App) On

func (a *App) On(event component.Event, hook component.Hook)

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

func (a *App) Register(c component.Component)

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

func (a *App) Registry() *component.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

func (a *App) Reload(ctx context.Context) error

Reload is the unified reload entry point. It performs, in order:

  1. Re-read the config file + env (ReloadConfig). Validation errors abort reload — the old config keeps running.
  2. Dispatch Reload to every Reloadable Component registered with the internal registry. Errors are logged; peers still get their chance to absorb new config.
  3. 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

func (a *App) ReloadConfig() (bool, map[string]bool, error)

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

func (a *App) Replace(c component.Component)

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

func (a *App) Run(ctx context.Context, opts ...RunOption) error

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

func (a *App) SetCacher(c cache.Cache)

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.

func (*App) SetDB

func (a *App) SetDB(gdb any)

SetDB stores a *gorm.DB on the App and registers a Close cleanup. Unlike Logger and Cache, DB is not auto-discovered — the user must explicitly create the connection in Setup (choose driver, run migrations, etc.).

Thread-safe: serialized via registryMu.

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

func WithCleanup(f func(context.Context) error) Option

WithCleanup registers a cleanup callback, called LIFO when Run ends.

func WithCloseTimeout

func WithCloseTimeout(d time.Duration) Option

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

func WithComponentReloadTimeout(d time.Duration) Option

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

func WithConfig(cfg any, path ...string) Option

WithConfig registers a typed config pointer and optional explicit path. The pointer is populated during Run() after config loading.

func WithDrainDelay

func WithDrainDelay(d time.Duration) Option

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 WithEnvPrefix(prefix string) Option

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

func WithFlags(fs *pflag.FlagSet) Option

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

func WithHealthTimeout(d time.Duration) Option

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

func WithHookTimeout(d time.Duration) Option

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

func WithInitTimeout(d time.Duration) Option

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

func WithLogger(l log.Logger) Option

WithLogger injects a Logger directly (highest priority).

func WithReloadFunc

func WithReloadFunc(f func(context.Context) error) Option

func WithReloadTimeout

func WithReloadTimeout(d time.Duration) Option

func WithRoutes

func WithRoutes(f func(context.Context, *App) error) Option

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 WithSetup

func WithSetup(f func(context.Context, *App) error) Option

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

func WithTables

func WithTables(tables ...db.TableSpec) Option

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

func WithVersion(v version.Info) Option

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.

func ServerFunc

func ServerFunc(f func(ctx context.Context, ready func()) error) Server

ServerFunc adapts a simple function into a Server. Stop cancels the internal ctx, so f exits via <-ctx.Done().

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/blessed
Package blessed bundles every chok-blessed OAuth provider via blank imports.
Package blessed bundles every chok-blessed OAuth provider via blank imports.
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 component.
Package audit is chok's compliance-grade audit log component.
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 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL