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
}
Output:
Index ¶
- Variables
- func AllowCrossSitePost(r Router, pattern string)
- func ClientIP(ctx context.Context) string
- func DELETE[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)
- func GET[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)
- func List[T any](r Router, pattern string, l Lister[T], opts ...RouteOption)
- func Load[T any](name string, opts ...LoadOption) (T, error)
- func LoggerFrom(ctx context.Context) *slog.Logger
- func MustLoad[T any](name string, opts ...LoadOption) T
- func PATCH[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)
- func POST[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)
- func PUT[T, R any](r Router, pattern string, fn HandlerFunc[T, R], opts ...RouteOption)
- func RequestID(ctx context.Context) string
- func SPA(r Router, prefix string, fsys fs.FS)
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- func WriteError(w http.ResponseWriter, r *http.Request, err error)
- type App
- func (a *App) Addr() string
- func (a *App) Close(ctx context.Context) error
- func (a *App) Execute()
- func (a *App) Group(prefix string, mw ...Middleware) Router
- func (a *App) Handler() http.Handler
- func (a *App) Logger() *slog.Logger
- func (a *App) Router() Router
- func (a *App) Run(ctx context.Context) error
- func (a *App) Use(components ...any)
- type AppConfig
- type Base
- type CORSConfig
- type Closer
- type Coder
- type Error
- type ErrorHook
- type FileConfig
- type HTTPConfig
- type HandlerFunc
- type HealthConfig
- type Healther
- type Instrumenter
- type Lister
- type LoadOption
- type LogConfig
- type Middleware
- type Mounter
- type Namer
- type None
- type OpenAPIConfig
- type Option
- type Page
- type Principal
- type RouteOption
- type Router
- type Starter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadRequest = NewError(http.StatusBadRequest, "BadRequest", "bad request") ErrValidation = NewError(http.StatusBadRequest, "Validation", "validation failed") 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
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
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
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
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
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
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 ¶
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
Addr returns the address the HTTP server listens on, "" before it does.
func (*App) Close ¶ added in v0.2.0
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
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) Run ¶
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
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
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
NewError returns an Error with the HTTP status code, a machine-readable reason and a message for people.
func (*Error) Is ¶ added in v0.2.0
Is reports whether target is an *Error with the same code and reason, so errors.Is(err, chok.ErrConflict) holds for any conflict.
type ErrorHook ¶ added in v0.2.0
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
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 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.
type Middleware ¶ added in v0.2.0
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
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
OnError installs the App's ErrorHook; a second OnError replaces the first.
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
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
PrincipalFrom returns the principal stored in ctx, if any.
type RouteOption ¶ added in v0.2.0
type RouteOption func(*routeConfig)
RouteOption configures one route.
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...}", "/{$}".
Source Files
¶
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. |