chok

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 44 Imported by: 0

README

中文 | English

MIT Go Reference CI

chok

An opinionated Go application toolkit, assembled with plain Go code.


[!NOTE] This is chok (github.com/zynthara/chok, no major-version suffix), released from v0.2.0 on: while it is at v0, a minor release (v0.3.0, ...) may change the API, and the CHANGELOG says how. v2 is sealed on the v2 branch (security fixes only; go get github.com/zynthara/chok/v2@v2.0.0-beta.6 keeps working). Moving from v2? Read the migration guide.


chok gives a Go service one strict typed configuration, typed HTTP handlers that publish their own OpenAPI document, and a gorm-backed store that fences every query to the signed-in user — an authenticated CRUD resource takes four chok imports. Identity, jobs, telemetry, cache, realtime and mail are batteries: values you construct and hand to app.Use. There is no kernel, no registry and no generated file; main.go is the whole assembly:

package main

import (
	"context"

	"github.com/zynthara/chok"
	"github.com/zynthara/chok/db"
	"github.com/zynthara/chok/identity"
	"github.com/zynthara/chok/store"
)

type Config struct {
	chok.Base                    // the app, http and log sections
	DB   db.Config       `yaml:"db"`
	Auth identity.Config `yaml:"auth"`
}

// Note belongs to whoever creates it: the store stamps the owner and
// fences every query to the signed-in user.
type Note struct {
	db.OwnedModel
	Text string `json:"text" store:"query,update" gorm:"size:500;not null"`
}

type newNote struct {
	Text string `json:"text" validate:"required,max=500"`
}

func main() {
	cfg := chok.MustLoad[Config]("notes") // chok.yaml, then NOTES_* variables
	app := chok.New(cfg.Base)
	d := db.MustOpen(cfg.DB, db.Tables(db.Table(&Note{})))
	auth := identity.MustNew(cfg.Auth, d) // /auth/register, /auth/login, ...
	app.Use(d, auth)

	notes := store.New[Note](d)
	api := app.Group("/api", auth.Authn())
	chok.POST(api, "/notes", func(ctx context.Context, req *newNote) (*Note, error) {
		n := &Note{Text: req.Text}
		return n, notes.Create(ctx, n)
	}, chok.Created())
	chok.List(api, "/notes", notes) // ?page=&size=&order=text:desc&text=
	app.Execute()
}
# chok.yaml — a misspelled key fails startup with a suggestion
db:
  driver: sqlite
  sqlite:
    path: notes.db
auth:
  token_ttl: 2h # signing_key comes from NOTES_AUTH_SIGNING_KEY

That serves JSON with request IDs and an access log, /healthz, /readyz and /livez, the OpenAPI 3.1 document at /openapi.json with its UI at /docs, registration and login with rate limiting, 401 / 404 / 409 / 400 error envelopes, and a graceful stop on Ctrl-C. SQLite, MySQL and Postgres are equally supported; the tables are created on start, or by versioned SQL migrations.

30-second hello

go run github.com/zynthara/chok/cmd/chok@latest init hello
cd hello && go mod tidy && go run .

In a second terminal:

curl -s localhost:8080/healthz
# {"status":"up","components":[{"component":"db","status":"up","duration_ms":0}]}
curl -s -X POST localhost:8080/api/v1/notes -H 'Content-Type: application/json' -d '{"title":"hello"}'
# {"id":"note_…","version":1,"created_at":"…","updated_at":"…","title":"hello","body":""}
curl -s localhost:8080/api/v1/notes
# {"items":[…],"total":1,"page":1,"size":20,"has_more":false}

chok init writes a 76-line main.go (one resource, four routes), chok.yaml, a Makefile, migrations/ and a go.mod that requires chok and names the command in a tool directive, so go tool chok runs the version the project uses. Open http://localhost:8080/docs for the API.

Five-minute blog

examples/blog is a JWT-guarded blog in under a hundred lines: register, log in, write posts only you can see, update them under optimistic locking, delete them, read /metrics.

git clone https://github.com/zynthara/chok && cd chok/examples/blog
export BLOG_AUTH_SIGNING_KEY=$(openssl rand -hex 32)
go run .
curl -s -X POST localhost:8080/auth/register -H 'Content-Type: application/json' \
  -d '{"email":"alice@example.com","password":"password123","name":"Alice"}'
TOKEN=$(curl -s -X POST localhost:8080/auth/login -H 'Content-Type: application/json' \
  -d '{"email":"alice@example.com","password":"password123"}' |
  python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])')
curl -s -X POST localhost:8080/api/v1/posts -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"title":"Hello chok","content":"my first post"}'
# {"id":"pst_…","version":1,…,"title":"Hello chok","content":"my first post","status":"draft"}
curl -s "localhost:8080/api/v1/posts?status=draft" -H "Authorization: Bearer $TOKEN"

Its README walks all nine steps — another user's 404, the 409 of a stale update, the delete, the OpenAPI document and the metrics — and its acceptance test walks the same path in CI. For a guided build-up from an empty directory, read the quickstart.

Realtime

The realtime battery pushes events to browsers as they happen — an updated order, a chat message, a finished background job — over a WebSocket or server-sent events, from the same topics. The page trades its token for a one-time ticket, so no long-lived token travels in a URL; Authorize decides who follows what; a reconnecting page resumes where it left off; with Redis, every replica shares the events.

package main

import (
	"context"

	"github.com/zynthara/chok"
	"github.com/zynthara/chok/realtime"
)

type Config struct {
	chok.Base
	Realtime realtime.Config `yaml:"realtime"`
}

type story struct {
	Title string `json:"title" validate:"required,max=200"`
}

func main() {
	cfg := chok.MustLoad[Config]("news")
	app := chok.New(cfg.Base)
	// Anonymous tickets (no realtime.Authn), and anyone may follow "news".
	hub := realtime.MustNew(cfg.Realtime, realtime.Authorize(func(_ context.Context, topic string) error {
		if topic == "news" {
			return nil
		}
		return chok.ErrForbidden.Msgf("no topic %s", topic)
	}))
	app.Use(hub) // POST /realtime/ticket, GET /realtime/ws, GET /realtime/sse

	chok.POST(app.Router(), "/stories", func(ctx context.Context, s *story) (chok.None, error) {
		return chok.None{}, hub.Publish(ctx, "news", "story.posted", s)
	})
	app.Execute()
}
// In the page: a one-time ticket, then the stream.
const {ticket} = await (await fetch("/realtime/ticket", {method: "POST"})).json();
const news = new EventSource(`/realtime/sse?topics=news&ticket=${ticket}`);
news.addEventListener("story.posted", (e) => console.log(JSON.parse(e.data).data.title));

Reconnecting and resuming, the WebSocket protocol, several replicas and live background jobs: docs/realtime.md. examples/chatter is a chat with a bot and a jobs panel built on it.

Mail and passwordless sign-in

The mail battery sends transactional mail with the standard library alone — through an SMTP relay, into .eml files during development, or into the log — from html/template and text/template files. Given a way to mail, identity signs people in with a code instead of a password: POST /auth/passwordless/start {"email"} answers 202 and mails a code (and, with magic_link_url set, a one-click link); POST /auth/passwordless/verify with the code (or the link's token) signs in, creating the account on first use. In cookie mode the session is an HttpOnly cookie the page's scripts never see, guarded by http.csrf, which is on by default.

package main

import (
	"os"

	"github.com/zynthara/chok"
	"github.com/zynthara/chok/db"
	"github.com/zynthara/chok/identity"
	"github.com/zynthara/chok/mail"
)

type Config struct {
	chok.Base
	DB   db.Config       `yaml:"db"`
	Auth identity.Config `yaml:"auth"`
	Mail mail.Config     `yaml:"mail"`
}

func main() {
	cfg := chok.MustLoad[Config]("shop")
	app := chok.New(cfg.Base)
	d := db.MustOpen(cfg.DB)
	m := mail.MustNew(cfg.Mail, mail.Templates(os.DirFS("templates")))
	// A mail is the template named after its kind:
	// templates/login-code.html, templates/password-reset.html.
	auth := identity.MustNew(cfg.Auth, d, identity.Sender(m.SendTemplate))
	app.Use(d, auth) // + POST /auth/passwordless/start, /auth/passwordless/verify, /auth/logout
	app.Execute()
}
# chok.yaml; the signing key comes from SHOP_AUTH_SIGNING_KEY
db:
  driver: sqlite
  sqlite:
    path: shop.db
auth:
  passwordless:
    enabled: true
  cookie:
    enabled: true
mail:
  from: Shop <no-reply@shop.example>
  smtp:
    host: smtp.example.com   # the password comes from SHOP_MAIL_SMTP_PASSWORD
    username: apikey

Templates, attachments, the three transports, retries through a jobs worker, the page's side of the sign-in and the cookie: docs/mail.md. examples/chatter signs in this way.

Packages

Package What it is
chok Configuration loading, the App and its lifecycle, typed handlers and routing, binding and validation, error envelopes, default middleware, OpenAPI, health probes, slog, a single-page app served beside the API (SPA)
db SQLite, MySQL and Postgres handles, transactions, model bases, RIDs, soft-unique indexes, auto / versioned / off migrations on one ledger
store Generic Store[T]: CRUD, owner scoping that fails closed, patches with optimistic locking, cursors, aggregates
store/where The query DSL: Eq, In, Like, Order, Page, Cursor, FromQuery, …
identity Accounts, JWTs, login rate limiting, OAuth, passwordless sign-in by mailed code, cookie sessions, the audit log, the first admin from auth.admins, Authn()
identity/rbac casbin permissions over identity's roles, admin passing every check: Require, policies, tenant domains, a Redis watcher
identity/google, github, apple, facebook The OAuth providers
jobs Cron-scheduled periodic jobs and transactional-outbox workers: at least once, typed payloads, retries with backoff, dead letters
telemetry Prometheus metrics, OpenTelemetry traces, slog to OpenTelemetry logs, SQL instrumentation
cache An in-memory and a Redis layer behind one Config, with a circuit breaker
realtime Events pushed to browsers over WebSocket and server-sent events: one-time tickets, authorized topics, resuming after a reconnect, a Redis backplane
mail Transactional mail through an SMTP relay, .eml files or the log: templates, attachments, inline images; identity's sign-in codes
choktest Test helpers: a throwaway database per test on the lane's dialect, an in-process App client

Every exported symbol, one line each: docs/api.md.

Configuration

One struct, loaded by chok.Load[T]: defaults, then chok.yaml, then environment variables (http.addr is <NAME>_HTTP_ADDR), then flags. Unknown keys fail startup with a suggestion; secrets are masked; --check-config validates the configuration and prints it without starting anything; only log.level reloads, on SIGHUP. Every key, with its type, default and rules: docs/config.md.

Command line

go install github.com/zynthara/chok/cmd/chok@latest   # or go tool chok in a project
Command What it does
chok init <name> A project that serves on go run .
chok migrate create <name> The next versioned migration's empty SQL files, one per dialect
chok migrate up / status / mark-applied <version> Apply, list or record migrations on the chok_migrations ledger, reading the app's own db configuration
chok openapi export <url> [--out file] Save a running app's OpenAPI document as JSON or YAML
chok version The chok version, revision and toolchain the command was built from

Design in three sentences

Configuration is strict: one typed struct, unknown keys fail startup, and only the log level reloads. Errors describe themselves: an error that implements chok.Coder becomes the HTTP envelope, with no mapper registry. Assembly is code: dependencies are values you pass to constructors, and app.Use only registers lifecycle.

More in docs/design.md (Chinese).

Documentation

Topic Where
Quickstart: from an empty directory to an authenticated resource docs/quickstart.md
Realtime: events in the browser, five minutes docs/realtime.md
Mail, passwordless sign-in and cookie sessions docs/mail.md
Configuration reference (generated) docs/config.md
API map (generated) docs/api.md
Design (Chinese) docs/design.md
Migrating from v2 (Chinese) docs/migration-from-v2.md
Changes by release CHANGELOG.md
GoDoc https://pkg.go.dev/github.com/zynthara/chok
Guidance for coding agents CLAUDE.md, AGENTS.md

Contributing

make verify runs every gate CI runs, in order: tidy, gofmt, vet, golangci-lint, go fix, the test suite on SQLite, Postgres and MySQL, the API budget and a smoke test of examples/blog. The database lanes read CHOK_TEST_PG_DSN and CHOK_TEST_MYSQL_DSN; CLAUDE.md has the conventions. Security reports: SECURITY.md.

License

Released under the MIT License. The cron parser in jobs/internal/cron is adapted from robfig/cron (MIT); see NOTICE.

Documentation

Overview

Package chok is an opinionated toolkit for Go applications that are assembled with plain code: one strict typed configuration, an App with a predictable lifecycle, typed HTTP handlers with a runtime OpenAPI document, and error values that describe their own HTTP response.

The smallest application:

func main() {
	chok.New(chok.MustLoad[chok.Base]("hello")).Execute()
}

It serves /healthz, /livez and /readyz on :8080, reads chok.yaml (or hello.yaml, or configs/hello.yaml) when present, takes every key from HELLO_* environment variables, logs JSON to stdout and stops gracefully on SIGINT or SIGTERM.

Configuration

An application declares its whole configuration as one struct that embeds Base and adds a section per battery:

type Config struct {
	chok.Base
	DB db.Config `yaml:"db"`
}

Load fills it from defaults, the file, the environment and flags, and fails on anything it does not recognize. Only log.level changes while running, on SIGHUP.

Components

Batteries are values: construct them, then register them with App.Use, which recognizes Starter, Closer, Healther, Mounter, Namer and Instrumenter. There is no registry to look anything up in.

Errors

A handler returns an *Error or any error implementing Coder; the App renders it as {"code","reason","message","request_id","metadata"}. Any other error is a 500 whose cause is logged and never sent.

Example

The smallest application: defaults, chok.yaml and HELLO_* variables, health probes, graceful stop.

package main

import (
	"github.com/zynthara/chok"
)

func main() {
	app := chok.New(chok.MustLoad[chok.Base]("hello"))
	_ = app // app.Execute() blocks until SIGINT or SIGTERM
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest   = NewError(http.StatusBadRequest, "BadRequest", "bad request")
	ErrValidation   = NewError(http.StatusBadRequest, "Validation", "validation failed")
	ErrUnauthorized = NewError(http.StatusUnauthorized, "Unauthorized", "unauthorized")
	ErrForbidden    = NewError(http.StatusForbidden, "Forbidden", "forbidden")
	ErrNotFound     = NewError(http.StatusNotFound, "NotFound", "not found")
	ErrConflict     = NewError(http.StatusConflict, "Conflict", "conflict")
	ErrRateLimited  = NewError(http.StatusTooManyRequests, "RateLimited", "rate limited")
	ErrInternal     = NewError(http.StatusInternalServerError, "InternalError", "internal server error")
)

The errors every application meets. Derive variants with With, Msgf and Wrap; errors.Is matches a variant against its sentinel.

Functions

func AllowCrossSitePost added in v0.2.0

func AllowCrossSitePost(r Router, pattern string)

AllowCrossSitePost lets another site's page POST to pattern below r past http.csrf. It is for a third party's form that brings the user's browser back to the application — a payment gateway's return, 3-D Secure, a SAML POST binding, an OAuth provider's form_post callback — and for nothing else: such a route must check the request another way, by the third party's signature or a state parameter the application issued, and must not act on the session cookie alone. Never use it for the application's own forms. pattern is relative to r, as for POST; the route's other methods and every other route stay checked. Allowing a pattern again is harmless, and a Router that is not an App's is ignored.

chok.AllowCrossSitePost(app.Router(), "/pay/return")

func ClientIP added in v0.2.0

func ClientIP(ctx context.Context) string

ClientIP returns the client address, read from forwarding headers only when the direct peer is one of http.trusted_proxies.

func DELETE added in v0.2.0

func DELETE[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)

DELETE registers fn for DELETE pattern on r; see GET for binding.

func GET added in v0.2.0

func GET[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)

GET registers fn for GET pattern on r.

Request fields bind by tag: path:"id", query:"q", header:"X-Api-Key", and json:"title" from an application/json body (unknown members and duplicate keys are rejected, names match case-sensitively). Query, header and path values overwrite whatever the body put in their fields. A request type with a Default() method gets it called after binding; then the validate tags run and a failure is a 400 whose metadata.fields names each field by its source name.

func List added in v0.2.0

func List[T any](r Router, pattern string, l Lister[T], opts ...RouteOption)

List registers GET pattern on r to serve pages from l: page, size, order=field:asc|desc and every field of l.QueryFields() as an equality filter come from the query string.

func Load added in v0.2.0

func Load[T any](name string, opts ...LoadOption) (T, error)

Load builds a T from, lowest to highest: `default` tags, the YAML file, environment variables and flags. name derives the environment prefix (upper case, - and . become _) and the file candidates.

The file is the first of: --config <file>, {PREFIX}_CONFIG, ConfigFile, ./chok.yaml, ./{name}.yaml, ./configs/{name}.yaml; without one only defaults and the environment apply. Every key can be set through the environment: http.addr is {PREFIX}_HTTP_ADDR, lists are comma-separated.

Load is strict. An unknown key fails with a suggestion ("unknown key http.adr (did you mean addr?)"), a value of the wrong type names its path, validate tags and Validate methods run on the result, and every problem is reported in one error. An environment variable with the prefix that matches no key is a warning: Load keeps it in the Base that T is or embeds, and New logs it through the App's logger (a T without a Base, or a failed Load, logs it through slog.Default at once).

Struct tags: yaml:"key" names the key; default:"value" is its default; secret:"true" masks it wherever the configuration is printed.

With --check-config on the command line, Load prints the effective configuration with secrets masked and exits 0, or prints the problems and exits 2, without returning.

Example

Config embeds Base and adds the application's own section.

package main

import (
	"fmt"

	"github.com/zynthara/chok"
)

func main() {
	type Config struct {
		chok.Base
		Greeting struct {
			Text string `yaml:"text" default:"hello"`
		} `yaml:"greeting"`
	}
	cfg, err := chok.Load[Config]("example", chok.Args(nil))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(cfg.Greeting.Text, cfg.HTTP.Addr)
}
Output:
hello :8080

func LoggerFrom added in v0.2.0

func LoggerFrom(ctx context.Context) *slog.Logger

LoggerFrom returns the request's logger, which carries its request_id; outside a request it returns slog.Default().

func MustLoad added in v0.2.0

func MustLoad[T any](name string, opts ...LoadOption) T

MustLoad is Load that prints the problems to stderr and exits 2 on error.

func PATCH added in v0.2.0

func PATCH[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)

PATCH registers fn for PATCH pattern on r; see GET for binding.

func POST added in v0.2.0

func POST[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)

POST registers fn for POST pattern on r; see GET for binding.

func PUT added in v0.2.0

func PUT[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)

PUT registers fn for PUT pattern on r; see GET for binding.

func RequestID added in v0.2.0

func RequestID(ctx context.Context) string

RequestID returns the request's ID: the X-Request-Id it arrived with (sanitized) or a generated one. The response echoes it.

func SPA added in v0.2.0

func SPA(r Router, prefix string, fsys fs.FS)

SPA serves the single-page application in fsys under prefix: a file as it is, and index.html for a page path that names no file, so the application's own router takes the path over. Files under assets/, the hashed output of bundlers such as Vite, are cached for a year as immutable; everything else, index.html first, is no-cache: checked on every use against its ETag, a hash of the content, so an unchanged file costs a 304. A missing path whose last segment has a dot is a 404, and so is any missing path asked for without text/html in Accept: an API client's typo gets the error envelope, not a page.

SPA registers GET (and so HEAD) for prefix and every path below it; a prefix of "/" makes it the fallback of the whole site. More specific routes, the API and the built-in endpoints, still win. A route for every method (method "") below prefix conflicts with SPA's pattern and the mux panics: give API routes their methods. The routes are not in the OpenAPI document. An fsys without index.html at its root panics.

//go:embed dist
var dist embed.FS

web, _ := fs.Sub(dist, "dist")
chok.SPA(app.Router(), "/", web)
Example

SPA serves a built front end next to the API: the API's routes win, and every other page path gets index.html for the front end's router.

package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"testing/fstest"

	"github.com/zynthara/chok"
)

func main() {
	// In an application: //go:embed dist, then fs.Sub(dist, "dist").
	web := fstest.MapFS{"index.html": {Data: []byte("<!doctype html><div id=app></div>")}}
	app := chok.New(chok.MustLoad[chok.Base]("example", chok.Args(nil)), chok.Logger(slog.New(slog.DiscardHandler)))
	chok.GET(app.Group("/api"), "/ping", func(context.Context, *chok.None) (string, error) { return "pong", nil })
	chok.SPA(app.Router(), "/", web)

	req := httptest.NewRequest(http.MethodGet, "/orders/42", nil)
	req.Header.Set("Accept", "text/html")
	rec := httptest.NewRecorder()
	app.Handler().ServeHTTP(rec, req)
	fmt.Println(rec.Code, rec.Body.String())
}
Output:
200 <!doctype html><div id=app></div>

func WithPrincipal added in v0.2.0

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal returns a context that carries p.

func WriteError added in v0.2.0

func WriteError(w http.ResponseWriter, r *http.Request, err error)

WriteError renders err as the error envelope, the way a handler's returned error is rendered: the App's ErrorHook first, then *Error, Coder, validation errors and expired deadlines, anything else a 500; request_id in the body and, when the metadata carries retry_after, a Retry-After header. It is for middleware, which has no error to return: a handler returns its error instead. Inside an App's handler chain it uses that App's ErrorHook; elsewhere it renders without one.

Example

Middleware has no error to return; WriteError renders one as the envelope a handler's error would get.

package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/zynthara/chok"
)

func main() {
	requireKey := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("X-Api-Key") == "" {
				chok.WriteError(w, r, chok.ErrUnauthorized.Msgf("X-Api-Key is required"))
				return
			}
			next.ServeHTTP(w, r)
		})
	}
	app := chok.New(chok.MustLoad[chok.Base]("example", chok.Args(nil)), chok.Logger(slog.New(slog.DiscardHandler)))
	chok.GET(app.Group("/api", requireKey), "/ping", func(context.Context, *chok.None) (string, error) { return "pong", nil })

	rec := httptest.NewRecorder()
	app.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/ping", nil))
	fmt.Println(rec.Code)
}
Output:
401

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is one application: its configuration, the components registered with Use, and the HTTP handler its routes build. An App runs once.

func New

func New(base Base, opts ...Option) *App

New builds an App from its configuration. It never applies defaults: base normally comes from Load or MustLoad. Unless Logger is given, New builds the root logger from base.Log and installs it as slog.Default.

func (*App) Addr added in v0.2.0

func (a *App) Addr() string

Addr returns the address the HTTP server listens on, "" before it does.

func (*App) Close added in v0.2.0

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

Close releases registered components if Run has not begun, in reverse Use order, then closes owned log files. A component's Close still running one second after ctx is done is abandoned and reported, and the next one is closed. This supports deferred cleanup during construction. After Run begins, Close waits for Run to finish; cancel Run's context to stop it. A closed App cannot be run or extended. Components constructed before Use remain the caller's responsibility.

func (*App) Execute

func (a *App) Execute()

Execute runs the App under OS signals and exits 1 if it fails: SIGINT and SIGTERM stop it gracefully; another SIGINT or SIGTERM while it stops, or SIGQUIT at any time, stops it fast (the drain ends, what is left of the stop budget is capped at 5s); SIGHUP re-reads the configuration file and applies log.level, logging that any other change needs a restart.

func (*App) Group added in v0.2.0

func (a *App) Group(prefix string, mw ...Middleware) Router

Group returns a router for routes below prefix that also run mw.

func (*App) Handler added in v0.2.0

func (a *App) Handler() http.Handler

Handler returns the App's complete handler — the default middleware, the application middleware and every route — for tests and for embedding in another server. Register components and routes first: the middleware stack is fixed by the first call.

func (*App) Logger

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

Logger returns the root logger.

func (*App) Router added in v0.2.0

func (a *App) Router() Router

Router returns the root router.

func (*App) Run

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

Run starts the App and blocks until ctx is done or a component fails.

Start phase: every Starter's Start runs in its own goroutine, in Use order; then every Healther must report healthy within app.start_timeout (a Start that fails first aborts the start). Only then does the HTTP server listen and /readyz turn 200.

Stop phase, under one app.shutdown_timeout budget: /readyz and the health endpoint turn 503, http.drain_delay passes — only when one of them has been requested since the start, so a stop nobody's probes watch does not wait — the HTTP server shuts down within http.shutdown_timeout, the Starters' context is canceled and Run waits for them, then every Closer is closed in reverse Use order. Once the budget is spent, each Close still running, or called after that, gets one second more; one that has not returned by then is abandoned and reported, and the next Closer is closed.

Run returns nil when ctx is canceled, ctx.Err() when its deadline expires, and the failure otherwise. It can be called once.

func (*App) Use added in v0.2.0

func (a *App) Use(components ...any)

Use registers components. Each is handled by the interfaces it implements: Starter, Closer, Healther, Mounter, Namer and Instrumenter. Use mounts in registration order; Start calls run concurrently and do not establish readiness dependencies. Close runs in reverse. A value that implements none of them is ignored with a warning. A registered value with a BindLogger(*slog.Logger) method is handed the App's root logger as it is registered: that is how telemetry's logs.otel bridge attaches to the logger New built.

Call Use before Handler and Run. The first Handler call, which Run makes too, fixes the middleware stack, so Use panics for an Instrumenter registered after it, which the stack would leave out; any Use panics once Run has begun.

Example

Components are values; Use registers their lifecycle.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/zynthara/chok"
)

type worker struct{}

func (worker) Start(ctx context.Context) error { <-ctx.Done(); return nil }
func (worker) Health(context.Context) error    { return nil }

func main() {
	base := chok.MustLoad[chok.Base]("example", chok.Args(nil))
	app := chok.New(base)
	app.Use(worker{})

	rec := httptest.NewRecorder()
	app.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
	fmt.Println(rec.Code)
}
Output:
200

type AppConfig added in v0.2.0

type AppConfig struct {
	// ShutdownTimeout bounds the stop phase: drain, HTTP shutdown,
	// stopping the Starters and closing every component. A Close still
	// running when it is spent gets one second more, then is abandoned.
	ShutdownTimeout time.Duration `yaml:"shutdown_timeout" default:"30s"`
	// StartTimeout bounds the start phase: every Healther must report
	// healthy within it before the HTTP server listens.
	StartTimeout time.Duration `yaml:"start_timeout" default:"30s"`
	// Debug mounts /debug/pprof/* and /debug/pprof/goroutineleak.
	Debug bool `yaml:"debug"`
}

AppConfig is the app section.

type Base added in v0.2.0

type Base struct {
	App  AppConfig  `yaml:"app"`
	HTTP HTTPConfig `yaml:"http"`
	Log  LogConfig  `yaml:"log"`
	// contains filtered or unexported fields
}

Base is the standard configuration every application embeds: the app, http and log sections. Embedded without a yaml tag, its sections sit at the top level of chok.yaml next to the application's own.

type Config struct {
	chok.Base
	DB db.Config `yaml:"db"`
}

Base on its own is a valid configuration type too: chok.New(chok.MustLoad[chok.Base]("hello")).

type CORSConfig added in v0.2.0

type CORSConfig struct {
	// AllowOrigins lists the allowed origins; "*" allows any.
	AllowOrigins     []string      `yaml:"allow_origins"`
	AllowMethods     []string      `yaml:"allow_methods" default:"GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS"`
	AllowHeaders     []string      `yaml:"allow_headers" default:"Origin,Content-Type,Accept,Authorization,X-Request-Id"`
	ExposeHeaders    []string      `yaml:"expose_headers" default:"X-Request-Id"`
	AllowCredentials bool          `yaml:"allow_credentials"`
	MaxAge           time.Duration `yaml:"max_age" default:"12h"`
}

CORSConfig is http.cors. CORS is active when AllowOrigins is set.

type Closer added in v0.2.0

type Closer interface {
	Close(ctx context.Context) error
}

Closer is a component that releases resources when the App stops. Close should return once ctx is done: the App waits for it while the stop budget lasts and one second more, then abandons it.

type Coder added in v0.2.0

type Coder interface{ APIError() *Error }

Coder is implemented by errors that know their HTTP response. Errors from store, identity and jobs implement it, so a handler returns them unchanged.

Example

An error that implements Coder chooses its own response.

package main

import (
	"errors"
	"fmt"

	"github.com/zynthara/chok"
)

type outOfStock struct{ sku string }

func (e outOfStock) Error() string { return "out of stock: " + e.sku }

func (e outOfStock) APIError() *chok.Error {
	return chok.ErrConflict.Msgf("%s is out of stock", e.sku).With("sku", e.sku)
}

func main() {
	var err error = outOfStock{sku: "A-1"}
	var c chok.Coder
	if errors.As(err, &c) {
		e := c.APIError()
		fmt.Println(e.Code, e.Reason, e.Message, e.Metadata["sku"])
	}
}
Output:
409 Conflict A-1 is out of stock A-1

type Error added in v0.2.0

type Error struct {
	Code     int            `json:"code"`
	Reason   string         `json:"reason"`
	Message  string         `json:"message"`
	Metadata map[string]any `json:"metadata,omitzero"`
	// contains filtered or unexported fields
}

Error is the body of every failed response:

{"code":404,"reason":"NotFound","message":"not found","request_id":"…","metadata":{…}}

Return one from a handler, or return any error that implements Coder.

func NewError added in v0.2.0

func NewError(code int, reason, message string) *Error

NewError returns an Error with the HTTP status code, a machine-readable reason and a message for people.

func (*Error) Error added in v0.2.0

func (e *Error) Error() string

func (*Error) Is added in v0.2.0

func (e *Error) Is(target error) bool

Is reports whether target is an *Error with the same code and reason, so errors.Is(err, chok.ErrConflict) holds for any conflict.

func (*Error) Msgf added in v0.2.0

func (e *Error) Msgf(format string, args ...any) *Error

Msgf returns a copy with another message.

func (*Error) Unwrap added in v0.2.0

func (e *Error) Unwrap() error

Unwrap returns the cause given to Wrap.

func (*Error) With added in v0.2.0

func (e *Error) With(key string, v any) *Error

With returns a copy that also carries key in its metadata.

func (*Error) Wrap added in v0.2.0

func (e *Error) Wrap(cause error) *Error

Wrap returns a copy whose cause is err. The cause is logged, never sent to the client.

type ErrorHook added in v0.2.0

type ErrorHook func(ctx context.Context, err error) *Error

ErrorHook turns an error into a response before the built-in rules; it returns nil to leave the error to them.

type FileConfig added in v0.2.0

type FileConfig struct {
	Path       string `yaml:"path"`
	MaxSizeMB  int    `yaml:"max_size_mb" default:"100" validate:"gte=0"`
	MaxBackups int    `yaml:"max_backups" default:"7" validate:"gte=0"`
	MaxAgeDays int    `yaml:"max_age_days" default:"30" validate:"gte=0"`
	Compress   bool   `yaml:"compress" default:"true"`
}

FileConfig is one rotating log file.

type HTTPConfig added in v0.2.0

type HTTPConfig struct {
	// Enabled starts the HTTP server; false runs a worker process whose
	// Handler still serves in-process requests.
	Enabled           bool          `yaml:"enabled" default:"true"`
	Addr              string        `yaml:"addr" default:":8080"`
	ReadTimeout       time.Duration `yaml:"read_timeout" default:"30s"`
	ReadHeaderTimeout time.Duration `yaml:"read_header_timeout" default:"10s"`
	WriteTimeout      time.Duration `yaml:"write_timeout" default:"30s"`
	IdleTimeout       time.Duration `yaml:"idle_timeout" default:"120s"`
	// RequestTimeout cancels a request's context after it; 0 means none.
	RequestTimeout time.Duration `yaml:"request_timeout"`
	// ShutdownTimeout bounds http.Server.Shutdown.
	ShutdownTimeout time.Duration `yaml:"shutdown_timeout" default:"10s"`
	// DrainDelay is how long /readyz and the health endpoint report 503
	// before the server stops accepting, so load balancers move traffic
	// away first. A stop waits it only when one of them has been
	// requested since the start: with no probe watching, Ctrl-C stops at
	// once.
	DrainDelay time.Duration `yaml:"drain_delay" default:"5s"`
	// TrustedProxies lists the proxy addresses or CIDRs whose
	// X-Forwarded-For and X-Real-Ip headers are believed; it is empty by
	// default. Behind a reverse proxy the list leaves out, those headers
	// are ignored and every client has the proxy's address, so a limit
	// kept per address, such as identity's login throttle, counts the
	// whole proxy as one client. The App logs a warning the first time it
	// ignores one.
	TrustedProxies []string `yaml:"trusted_proxies"`
	// MaxBodyBytes caps a request body; a route can change it with MaxBody.
	MaxBodyBytes int64 `yaml:"max_body_bytes" default:"4194304" validate:"gte=0"`
	// H2C serves HTTP/2 without TLS (behind a proxy that speaks it).
	H2C  bool       `yaml:"h2c"`
	CORS CORSConfig `yaml:"cors"`
	// CSRF rejects the unsafe requests a browser sends from another site
	// (http.CrossOriginProtection); clients that send neither
	// Sec-Fetch-Site nor Origin — curl, apps, services — pass. Turning
	// it off while routes accept a session cookie logs a warning.
	CSRF    bool          `yaml:"csrf" default:"true"`
	OpenAPI OpenAPIConfig `yaml:"openapi"`
	Health  HealthConfig  `yaml:"health"`
}

HTTPConfig is the http section.

func (*HTTPConfig) Validate added in v0.2.0

func (c *HTTPConfig) Validate() error

Validate checks the proxy list and the CORS combination browsers refuse.

type HandlerFunc added in v0.2.0

type HandlerFunc[T any, R any] func(ctx context.Context, req *T) (R, error)

HandlerFunc is a typed handler: chok binds and validates *T from the request and renders R, or the error, as the response.

type HealthConfig added in v0.2.0

type HealthConfig struct {
	Enabled bool   `yaml:"enabled" default:"true"`
	Path    string `yaml:"path" default:"/healthz"`
	// ProbeTimeout bounds each component's Health call.
	ProbeTimeout time.Duration `yaml:"probe_timeout" default:"3s"`
}

HealthConfig is http.health.

type Healther added in v0.2.0

type Healther interface {
	Health(ctx context.Context) error
}

Healther is a component that reports its health on /healthz.

type Instrumenter added in v0.2.0

type Instrumenter interface{ Middleware() Middleware }

Instrumenter is a component that contributes middleware to the default stack, between ClientIP and AccessLog — telemetry plugs in this way.

type Lister added in v0.2.0

type Lister[T any] interface {
	ListFromQuery(ctx context.Context, q url.Values) (*Page[T], error)
	QueryFields() []string
}

Lister serves a List route: a page from the query string, and the fields the query may filter on, which the OpenAPI document lists.

type LoadOption added in v0.2.0

type LoadOption func(*loadConfig)

LoadOption adjusts Load.

func Args added in v0.2.0

func Args(args []string) LoadOption

Args replaces the command line Load reads (os.Args[1:] by default). Load looks only for --config <file> and --check-config there and ignores everything else; Args(nil) makes it read nothing, as tests do.

func ConfigFile added in v0.2.0

func ConfigFile(path string) LoadOption

ConfigFile names the configuration file; a missing file is an error. --config and {PREFIX}_CONFIG still take precedence over it.

func EnvPrefix added in v0.2.0

func EnvPrefix(prefix string) LoadOption

EnvPrefix replaces the environment prefix derived from the app name.

func Flags added in v0.2.0

func Flags(fs *pflag.FlagSet) LoadOption

Flags adds a parsed flag set as the highest-priority source: a changed flag named after a key path (--http.addr) sets that key.

type LogConfig added in v0.2.0

type LogConfig struct {
	// Level is the one setting SIGHUP applies while running.
	Level  string `yaml:"level" default:"info" validate:"oneof=debug info warn warning error"`
	Format string `yaml:"format" default:"json" validate:"oneof=json text"`
	// Output lists sinks: stdout, stderr or a file path.
	Output []string     `yaml:"output" default:"stdout"`
	Files  []FileConfig `yaml:"files"`
	// Access writes one line per request (method, path, route, status,
	// bytes, duration, request_id, client_ip).
	Access      bool         `yaml:"access" default:"true"`
	AccessFiles []FileConfig `yaml:"access_files"`
}

LogConfig is the log section.

func (*LogConfig) Validate added in v0.2.0

func (c *LogConfig) Validate() error

Validate rejects a blank output entry and a log with no sink at all.

type Middleware added in v0.2.0

type Middleware = func(http.Handler) http.Handler

Middleware wraps an http.Handler.

type Mounter added in v0.2.0

type Mounter interface{ Mount(r Router) }

Mounter is a component that registers its own routes. Use calls Mount immediately, so a battery's routes precede the ones the application declares after Use.

type Namer added in v0.2.0

type Namer interface{ Name() string }

Namer names a component in the health report; the default is its type name.

type None added in v0.2.0

type None struct{}

None is a request type that binds nothing, or a response type with no body: a handler returning None answers 204 unless Status says otherwise.

type OpenAPIConfig added in v0.2.0

type OpenAPIConfig struct {
	Enabled  bool   `yaml:"enabled" default:"true"`
	Title    string `yaml:"title"`
	Version  string `yaml:"version"`
	Path     string `yaml:"path" default:"/openapi.json"`
	DocsPath string `yaml:"docs_path" default:"/docs"`
}

OpenAPIConfig is http.openapi.

type Option

type Option func(*App)

Option configures New.

func Logger added in v0.2.0

func Logger(l *slog.Logger) Option

Logger injects the root logger; without it New builds one from base.Log. An injected logger is never closed by the App, SIGHUP cannot change its level, and telemetry's logs.otel bridge does not see it.

func OnError added in v0.2.0

func OnError(h ErrorHook) Option

OnError installs the App's ErrorHook; a second OnError replaces the first.

func Version added in v0.2.0

func Version(v string) Option

Version is shown on /healthz and in the start log line.

func Wrap added in v0.2.0

func Wrap(mw ...Middleware) Option

Wrap adds application middleware, run after the default stack and before route groups.

type Page added in v0.2.0

type Page[T any] struct {
	Items   []T    `json:"items"`
	Total   int64  `json:"total"`
	Page    int    `json:"page"`
	Size    int    `json:"size"`
	HasMore bool   `json:"has_more"`
	Cursor  string `json:"cursor,omitzero"`
}

Page is one page of a list.

type Principal added in v0.2.0

type Principal struct {
	UserID string
	Email  string
	Roles  []string
	Extra  map[string]string
}

Principal is the authenticated caller. identity's Authn middleware stores it in the request context; store's owner scope and application code read it with PrincipalFrom. It lives in the root package so the batteries that produce and consume it need not import each other.

func PrincipalFrom added in v0.2.0

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom returns the principal stored in ctx, if any.

func (Principal) HasRole added in v0.2.0

func (p Principal) HasRole(role string) bool

HasRole reports whether the principal holds role.

type RouteOption added in v0.2.0

type RouteOption func(*routeConfig)

RouteOption configures one route.

func Created added in v0.2.0

func Created() RouteOption

Created is Status(201).

func Deprecated added in v0.2.0

func Deprecated() RouteOption

Deprecated marks the route deprecated in the OpenAPI document.

func MaxBody added in v0.2.0

func MaxBody(n int64) RouteOption

MaxBody caps this route's request body in bytes, instead of http.max_body_bytes.

func Status added in v0.2.0

func Status(code int) RouteOption

Status sets the success status code.

func Summary added in v0.2.0

func Summary(s string) RouteOption

Summary is the route's one-line description in the OpenAPI document; without it chok derives one such as "Create post" or "List posts".

func Tags added in v0.2.0

func Tags(tags ...string) RouteOption

Tags groups the route in the OpenAPI document; the default is its resource segment.

func Use added in v0.2.0

func Use(mw ...Middleware) RouteOption

Use adds middleware to this route only.

type Router added in v0.2.0

type Router interface {
	// Handle registers h for method ("" for any) and pattern below the
	// router's prefix, wrapped by the router's and the given middleware.
	Handle(method, pattern string, h http.Handler, mw ...Middleware)
	// Group returns a router for prefix whose routes also run mw.
	Group(prefix string, mw ...Middleware) Router
}

Router registers routes. Patterns follow net/http.ServeMux: "/posts/{id}", "/files/{path...}", "/{$}".

type Starter added in v0.2.0

type Starter interface {
	Start(ctx context.Context) error
}

Starter is a component with long-running work. Start blocks until ctx is canceled, then returns nil; an error ends the App.

Directories

Path Synopsis
Package cache is chok's cache battery: byte values under string keys, in a memory layer in the process, a Redis layer shared by the replicas, or both, with a circuit breaker in front of Redis, under one Config.
Package cache is chok's cache battery: byte values under string keys, in a memory layer in the process, a Redis layer shared by the replicas, or both, with a circuit breaker in front of Redis, under one Config.
Package choktest is what an application's tests need from chok: a throwaway database of the lane's dialect, a store on it, an App served in process, and a JSON client for that App.
Package choktest is what an application's tests need from chok: a throwaway database of the lane's dialect, a store on it, an App served in process, and a JSON client for that App.
cmd
chok command
Command chok is the chok command line.
Command chok is the chok command line.
Package db opens the application's database and manages its schema.
Package db opens the application's database and manages its schema.
examples
blog command
Command blog is the chok quickstart: a JWT-guarded blog API where every post belongs to the user who wrote it.
Command blog is the chok quickstart: a JWT-guarded blog API where every post belongs to the user who wrote it.
chatter command
Command chatter is chok's realtime example: chat rooms that update without a reload, a bot that answers through a background worker, and a live panel of the background jobs.
Command chatter is chok's realtime example: chat rooms that update without a reload, a bot that answers through a background worker, and a live panel of the background jobs.
hello command
Command hello is the smallest chok application with a route: strict configuration from chok.yaml and HELLO_* variables, health probes, an OpenAPI document at /openapi.json, graceful stop.
Command hello is the smallest chok application with a route: strict configuration from chok.yaml and HELLO_* variables, health probes, an OpenAPI document at /openapi.json, graceful stop.
Package identity is the identity battery: accounts with a password or an OAuth provider, the access tokens that prove them, the middleware that checks those tokens, the administration of users and an audit log.
Package identity is the identity battery: accounts with a password or an OAuth provider, the access tokens that prove them, the middleware that checks those tokens, the administration of users and an audit log.
apple
Package apple is Sign in with Apple for identity: OpenID Connect with a nonce, the callback posted as a form, and a client secret the provider signs itself.
Package apple is Sign in with Apple for identity: OpenID Connect with a nonce, the callback posted as a form, and a client secret the provider signs itself.
facebook
Package facebook is Facebook Login for identity: OAuth 2.0 with PKCE, the user read from the Graph API.
Package facebook is Facebook Login for identity: OAuth 2.0 with PKCE, the user read from the Graph API.
github
Package github is Sign in with GitHub for identity: OAuth 2.0 with PKCE, the user read from the REST API.
Package github is Sign in with GitHub for identity: OAuth 2.0 with PKCE, the user read from the REST API.
google
Package google is Sign in with Google for identity: OpenID Connect, with a nonce and PKCE.
Package google is Sign in with Google for identity: OpenID Connect, with a nonce and PKCE.
internal/authz
Package authz connects identity/rbac to identity without widening identity's API: rbac installs its decision on an Identity, which asks it before the audit log's admin API answers.
Package authz connects identity/rbac to identity without widening identity's API: rbac installs its decision on an Identity, which asks it before the audit log's admin API answers.
internal/idptest
Package idptest is an OpenID Connect provider in process, for the provider packages' tests: discovery, the signing keys, an authorize stub and a token endpoint that answers the ID token a test staged for a code, signed with RS256.
Package idptest is an OpenID Connect provider in process, for the provider packages' tests: discovery, the signing keys, an authorize stub and a token endpoint that answers the ID token a test staged for a code, signed with RS256.
internal/oauth
Package oauth holds what identity and its provider packages share: the shape of a sign-in as identity drives it, and the helpers every provider uses.
Package oauth holds what identity and its provider packages share: the shape of a sign-in as identity drives it, and the helpers every provider uses.
internal/oidc
Package oidc is the OpenID Connect a provider needs and no more: the issuer's discovery document, and the verification of its ID tokens against the keys the issuer publishes.
Package oidc is the OpenID Connect a provider needs and no more: the issuer's discovery document, and the verification of its ID tokens against the keys the issuer publishes.
rbac
Package rbac is role-based access control for identity's users, on casbin: what each role may do, stored in the application's database and decided per request by Require.
Package rbac is role-based access control for identity's users, on casbin: what each role may do, stored in the application's database and decided per request by Require.
internal
apptest
Package apptest lets choktest and the batteries' tests reach what a test needs without a public API: chok fills in the hooks when it initializes, and choktest sets the knobs.
Package apptest lets choktest and the batteries' tests reach what a test needs without a public API: chok fills in the hooks when it initializes, and choktest sets the knobs.
clientip
Package clientip resolves the real client address behind reverse proxies — the stdlib replacement for gin's ClientIP/SetTrustedProxies pair (security-sensitive: this value keys the identity login rate limiter).
Package clientip resolves the real client address behind reverse proxies — the stdlib replacement for gin's ClientIP/SetTrustedProxies pair (security-sensitive: this value keys the identity login rate limiter).
conf
Package conf loads the typed configuration behind chok.Load.
Package conf loads the typed configuration behind chok.Load.
dbtest
Package dbtest gives each test a throwaway database of the dialect CHOK_TEST_DRIVER names: sqlite (the default; a file in t.TempDir, so the production pool layout is exercised), postgres (a fresh schema in the database of CHOK_TEST_PG_DSN) or mysql (a fresh chok_test_<rand> database on the server of CHOK_TEST_MYSQL_DSN).
Package dbtest gives each test a throwaway database of the dialect CHOK_TEST_DRIVER names: sqlite (the default; a file in t.TempDir, so the production pool layout is exercised), postgres (a fresh schema in the database of CHOK_TEST_PG_DSN) or mysql (a fresh chok_test_<rand> database on the server of CHOK_TEST_MYSQL_DSN).
dbx
Package dbx carries what db knows about a model's tables to store and the batteries without widening db's public API: the indexes db.Table declares, SoftUnique and Unique, which store uses to name the field of a duplicate-key error and to resolve an upsert's conflict target, the plain tables a battery declares for its own schema, the statement observer telemetry attaches to a handle, and the batteries' migration files the chok command applies.
Package dbx carries what db knows about a model's tables to store and the batteries without widening db's public API: the indexes db.Table declares, SoftUnique and Unique, which store uses to name the field of a duplicate-key error and to resolve an upsert's conflict target, the plain tables a battery declares for its own schema, the statement observer telemetry attaches to a handle, and the batteries' migration files the chok command applies.
jsonx
Package jsonx holds the encoding/json/v2 options every chok body uses.
Package jsonx holds the encoding/json/v2 options every chok body uses.
lint
Package lint holds repository-wide static checks that run as ordinary tests, so go test ./...
Package lint holds repository-wide static checks that run as ordinary tests, so go test ./...
logtap
Package logtap copies the records an App's loggers write to one more slog.Handler, the OpenTelemetry Logs bridge of telemetry, without a public API: the root package wraps the handlers it builds with Wrap, and App.Use binds telemetry's bridge to that App when logs.otel is on.
Package logtap copies the records an App's loggers write to one more slog.Handler, the OpenTelemetry Logs bridge of telemetry, without a public API: the root package wraps the handlers it builds with Wrap, and App.Use binds telemetry's bridge to that App when logs.otel is on.
openapi
Package openapi builds the OpenAPI 3.1 document of a chok App from its route table by reflecting over each route's request and response types.
Package openapi builds the OpenAPI 3.1 document of a chok App from its route table by reflecting over each route's request and response types.
redislog
Package redislog routes go-redis's own log lines (a dial that failed, a connection it dropped) to slog.
Package redislog routes go-redis's own log lines (a dial that failed, a connection it dropped) to slog.
reqinfo
Package reqinfo carries the per-request facts that middleware outside the router needs once the handler has run — the matched route pattern, for access logs and telemetry — without widening chok's public API.
Package reqinfo carries the per-request facts that middleware outside the router needs once the handler has run — the matched route pattern, for access logs and telemetry — without widening chok's public API.
serving
Package serving tells the batteries' Starters whether the App serves HTTP.
Package serving tells the batteries' Starters whether the App serves HTTP.
tools/apidoc command
Command apidoc writes docs/api.md, the map of chok's public API: for each public package, every line `go doc -short` prints for it — the lines hack/apibudget.sh counts against hack/budget.txt — with the first sentence of its comment.
Command apidoc writes docs/api.md, the map of chok's public API: for each public package, every line `go doc -short` prints for it — the lines hack/apibudget.sh counts against hack/budget.txt — with the first sentence of its comment.
tools/configkeys command
Command configkeys counts the configuration keys an application built on chok can set — Base plus every battery's Config — against the config_keys limit in hack/budget.txt (plan §6).
Command configkeys counts the configuration keys an application built on chok can set — Base plus every battery's Config — against the config_keys limit in hack/budget.txt (plan §6).
tools/doccheck
Package doccheck holds the test that compiles the Go programs of the documentation: every go block of docs/quickstart.md, README.md, README_zh.md, docs/realtime.md and docs/mail.md is a complete program, built against this checkout, and the chok.yaml shown next to it loads strictly into the program's configuration.
Package doccheck holds the test that compiles the Go programs of the documentation: every go block of docs/quickstart.md, README.md, README_zh.md, docs/realtime.md and docs/mail.md is a complete program, built against this checkout, and the chok.yaml shown next to it loads strictly into the program's configuration.
tracectx
Package tracectx lets a package read the trace id a context carries without importing OpenTelemetry: package telemetry sets TraceID when it initializes, so in a binary that links telemetry identity's audit events record the request's trace.
Package tracectx lets a package read the trace id a context carries without importing OpenTelemetry: package telemetry sets TraceID when it initializes, so in a binary that links telemetry identity's audit events record the request's trace.
Package jobs is chok's battery for background work: periodic jobs on cron schedules, and workers that deliver, at least once, the messages the application enqueues in its own transactions.
Package jobs is chok's battery for background work: periodic jobs on cron schedules, and workers that deliver, at least once, the messages the application enqueues in its own transactions.
internal/cron
Package cron turns cron specs into schedules.
Package cron turns cron specs into schedules.
Package mail is the mail battery: transactional mail — a sign-in code, a password reset, an order confirmation — sent with one value and the standard library only.
Package mail is the mail battery: transactional mail — a sign-in code, a password reset, an order confirmation — sent with one value and the standard library only.
Package realtime is chok's battery for pushing events to browsers as they happen: a Hub of topics that clients subscribe to over a WebSocket or a server-sent event stream, opened with one-time tickets, resumed after a reconnect from a short replay buffer, and shared by the replicas of a deployment through Redis.
Package realtime is chok's battery for pushing events to browsers as they happen: a Hub of topics that clients subscribe to over a WebSocket or a server-sent event stream, opened with one-time tickets, resumed after a reconnect from a short replay buffer, and shared by the replicas of a deployment through Redis.
Package store is the typed data access of a model: CRUD with optimistic locking and soft delete, filtered and paged lists, aggregates, and an owner scope that fences every query to the caller's rows.
Package store is the typed data access of a model: CRUD with optimistic locking and soft delete, filtered and paged lists, aggregates, and an owner scope that fences every query to the caller's rows.
internal/q
Package q holds what store and store/where share without exporting it: resolving a public field name to a column, safely.
Package q holds what store and store/where share without exporting it: resolving a public field name to a column, safely.
where
Package where is the query vocabulary of store: filters, ordering, pagination and the query modifiers, each an Option that a store applies to its query.
Package where is the query vocabulary of store: filters, ordering, pagination and the query modifiers, each an Option that a store applies to its query.
Package telemetry is chok's observability battery: Prometheus metrics, OpenTelemetry traces and, optionally, the App's logs copied to OpenTelemetry Logs, under one Config.
Package telemetry is chok's observability battery: Prometheus metrics, OpenTelemetry traces and, optionally, the App's logs copied to OpenTelemetry Logs, under one Config.

Jump to

Keyboard shortcuts

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