skit

module
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT

README

skit

skit ([S]ervice [KIT]) Go SDK (software development kit) for building production web services that speak REST and/or gRPC, backed by Postgres, with first-class observability (slog + OpenTelemetry traces + Prometheus metrics), reliable background workers, and a transactional outbox.

OpenTelemetry compliant. Services built with skit follow the conventions of OpenTelemetry Go:

  • traces are recorded with the OpenTelemetry Go SDK and exported over OTLP;
  • the SDK is configured with the OTEL_* environment variables of the specification (OTEL_TRACES_EXPORTER, OTEL_TRACES_SAMPLER, OTEL_EXPORTER_OTLP_*, OTEL_RESOURCE_ATTRIBUTES);
  • trace context is propagated as W3C TraceContext (traceparent, tracestate) over HTTP, gRPC and outbox/broker messages;
  • server spans come from the official instrumentation (otelhttp, otelgrpc); span names, attributes and the Resource (service.*, deployment.environment.name, telemetry.sdk.*) follow the semantic conventions;
  • every log record carries trace_id, span_id and trace_flags of its span.

Metrics are exposed in the Prometheus format.

This is NOT a framework. It is just a building block for production-ready applications in Go.

It distills patterns from several reference services into a single, importable module (github.com/assanoff/skit). A separate repo, skit-x, is the runnable showcase: a full CRUD app that imports this SDK from GitHub and exercises every package end-to-end (and is where the skit CLI is tried out).

Layout

Package Purpose
errs Error type with stable codes, REST/gRPC mapping, validation, secret sanitization
logger slog-based logger: trace_id injection, level fan-out (stdout + Sentry), additive per-level side-effect hooks (Events, e.g. alert on error), caller-skip variants, access log
otel Tracing API for SDK packages: Tracer, SetError, W3C propagation (Carrier/ExtractFromCarrier, InjectToResponse), Suppress; otel/setup installs the SDK (Resource, sampler from OTEL_TRACES_SAMPLER), otel/otlp builds the OTLP exporter from OTEL_*
dbx sqlx/pgx helpers: named queries, WithinTran, bulk insert/upsert/update, retries
dim Slim dependency-injection: lazy Provider[T], Once/OnceWithName, NewResource with init/cleanup logging
closer Graceful-shutdown registry: process-global default (Add/CloseSync) + instances (New/NewWithWait), LIFO
config 12-factor config via go-flags: one struct → CLI flags + env vars + --help, dotenv for local, subcommand dispatch
rest (+ router/mid/jsonapi) Typed HTTP handlers over stdlib ServeMux + routegroup; {error_code, data} response envelopes (Result, ResultItem, CursorResult); routing (router), typed application middleware (rest/mid: error localize/mask, panics, observability, cache, ETag) and JSON:API documents (rest/jsonapi)
middleware net/http server middleware (func(http.Handler) http.Handler): panic recovery, server span (Trace, otelhttp), access log, timeout, body-size limit (cf. httpmw for the client side)
httpserver http.Handler-on-a-listener as a worker.Runnable; the shared server core for REST, the gRPC-gateway and debugsrv; idle/header timeouts, net/http errors to your logger, stuck connections closed on shutdown
order, page Listing primitives shared by the domain and both transports: allowlisted sort (order), validated offset/cursor paging input (page)
grpcserver gRPC server as a worker.Runnable: server span per RPC (otelgrpc), recovery/logging/metrics interceptors, errs→status mapping, health, reflection, transport tuning knobs
worker Unified worker abstraction: Runnable, Group, Loop (fixed) / NewPacedLoop (adaptive: drain-when-busy, idle-backoff), Pool, Processor[T], Backoff
queue Durable named queues on Postgres (FOR UPDATE SKIP LOCKED): Schedule on the pool or Bind(tx).Schedule in a transaction through a Registry, Workers per queue, outcomes by the error of the handler (Permanent, Halt, backoff)
poller Typed cache of a periodically-refreshed value (Poller[T]), a worker.Runnable
broker Transport-agnostic Publisher/Consumer abstraction; CloudEvents v1.0 envelope; broker/rabbitmq implementation (confirm-mode publisher, worker.Runnable consumer)
outbox Transactional outbox on queue: an event is a task scheduled in the transaction of its domain write (queue.Bind), written by Envelope and published by Handler through any broker.Publisher; Config sets up the queue of events
eventbus In-process synchronous event bus (Bus) for decoupling domains without import cycles: Call (abort on first error) / Publish (run all, join errors). For atomic/durable events use outbox instead
i18n go-i18n wrapper: catalogs from fs.FS, Accept-Language matching + middleware, localizes *errs.Error by MessageID/Code with Args
auth Principal in context, credential extraction, pluggable Verifier, built-in JWT (HMAC/RSA/EC + JWKS via Keyfunc), Authenticate/Optional/RequireRole middleware
metrics Prometheus registry + HTTP middleware; extensible model — one shared registry, each package owns its collectors, Register (register-or-get) makes it conflict-free so SDK and app metrics coexist
health Liveness/readiness handlers for Kubernetes probes
buildinfo The build of the running binary (Read): version from VCS or a link-time stamp, revision, time, Go version; for the log, the Resource, Sentry and GET /version
debugsrv net/http/pprof + optional metrics/health as one http.Handler (Handler); run it standalone on a separate port (New, a worker.Runnable that is also an http.Handler), attach it to the app router at Paths, or mount pprof alone (Pprof)
migrate goose wrapper applying SQL migrations from an fs.FS via the Provider API (no goose global state)
httpmw Outbound HTTP-client middleware: RetryTransport retries 429/503 with worker.Backoff + RFC 7231 Retry-After
dbtest testcontainers Postgres for integration tests: start, migrate, connect, auto-teardown
apitest Stdlib-only HTTP test helpers: JSON requests, status/body assertions against an httptest.Server
safetick Panic recovery for worker ticks and consumer callbacks
httplog Access logger with OpenTelemetry trace correlation and ECS-HTTP formatting
httpclient Typed JSON HTTP client with OAuth2 (client-credentials) support and pluggable request middleware
retry Generic retry with pluggable Backoff (exponential + jitter) and terminal-error short-circuit; the backoff shared by httpmw/worker
cron Cron scheduler (robfig/cron) as a worker.Runnable: spec-validated jobs, per-firing panic recovery, graceful drain
lock Distributed mutual exclusion behind a common Locker: Postgres advisory locks and single-instance Redis locks
dedup Idempotency like a cache: k.Do(ctx, key, fn) runs fn once per key and hands its stored success to repeats; memory and Redis stores
chx Optional ClickHouse helper (connect + goose migrations); pulls the ClickHouse driver only when imported
grpcgateway grpc-gateway REST↔gRPC transcoding as a worker.Runnable, sharing the app's server core
grpctest In-process gRPC test harness over bufconn running the real grpcserver interceptor chain
provider/postgres Ready dim factory of a Postgres pool: pg.Open of dbx/pg, a reachability check, close on shutdown
provider/redis Ready dim factory of a go-redis client: PING on open, close on shutdown
provider/sentry Ready dim factory of the Sentry SDK: init, flush on shutdown
provider/translator Ready dim factory of an i18n.Translator from the service's message files
app Opinionated application entrypoint: wires config → deps → worker.Group and drives graceful shutdown via closer
cmd/skit Scaffolding CLI: skit new <module> (embedded starter, --full service layout, or gonew passthrough with --template), plus per-model generators via skit add …

The skit add generators scaffold per-model code: rest, rest-test, grpc, grpc-test, consumer, worker, migration, event, cron, and http-client. See quick-start.md for an end-to-end walkthrough.

Installation

Your code always imports the same path — github.com/assanoff/skit/... — regardless of how the source is supplied, because Go resolves packages by import path. So both recipes below produce identical runtime behavior; they differ only in versioning and workflow. The key rule for the local recipe: keep the module path github.com/assanoff/skit and wire it in with replace or a workspace — do not rename the import paths (that forks the SDK).

Versioned, reproducible, go.sum-verified. This is what skit new generates.

go get github.com/assanoff/skit@v0.6.0   # or @latest
import (
    "github.com/assanoff/skit/rest/router"
    "github.com/assanoff/skit/worker"
)

Update with go get github.com/assanoff/skit@latest. Pin a different version anytime by re-running go get …@vX.Y.Z.

Internal dependency (local source on disk)

Use this to develop your service and the SDK side by side, building against a local checkout. Two equivalent ways — pick one:

A. replace directive (per-module, committed to your app's go.mod):

# in your service module
go get github.com/assanoff/skit@v0.6.0          # keeps a sane version + go.sum entry
go mod edit -replace github.com/assanoff/skit=../skit
go mod tidy
// resulting go.mod
require github.com/assanoff/skit v0.6.0
replace github.com/assanoff/skit => ../skit

B. Go workspace (go.work, not committed — local to your machine):

cd /path/to/workspace        # parent dir holding both checkouts
go work init ./your-service ./skit

Either way the import paths stay github.com/assanoff/skit/... and the build uses the on-disk source. This is exactly how skit-x builds against the SDK during local development (replace github.com/assanoff/skit => ../skit).

Caveats for the local recipe:

  • It builds against whatever is on disk — not version-pinned and not go.sum-verified for the replaced module; the path must exist everywhere you build (CI, teammates).
  • replace/go.work are not transitive and not published — they apply only to your own build. Fine for an application (the main module); for a library you publish, ship the external dependency and drop the replace before tagging.
  • Recommended flow: keep the external require pinned, add replace only while iterating on the SDK, then remove it.

i18n & auth

  • i18n.Translator loads JSON catalogs from an embed.FS, resolves the request language from Accept-Language, and localizes error responses: an app middleware translates any *errs.Error by its MessageID (or Code) with Args as template data. The example localizes widget errors to en/ru.
  • auth verifies bearer tokens via a pluggable Verifier (built-in JWT covers HMAC, RSA/EC PEM, and JWKS through a custom Keyfunc) and enforces RBAC with Authenticate + RequireRole. The example protects widget writes behind a widget:write role while keeping reads public.

Scaffolding

go run ./cmd/skit new github.com/you/svc          # embedded starter
go run ./cmd/skit new github.com/you/svc --template github.com/some/tmpl  # via gonew

See quick-start.md for an end-to-end walkthrough: scaffolding a service, running it, and generating REST/gRPC modules with the skit CLI.

Messaging & transactional outbox

queue, outbox and broker give reliable, exactly-the-domain-write event publishing with a domain layer that knows nothing about SQL or the transport. Any work after a commit is a task of a queue; an event is a task whose handler publishes it to the broker.

  • The domain schedules a plain typed value through the Scheduler its store hands it inside the transaction:

    err := c.store.WithinTranTasks(ctx, func(r widget.Repo, s widget.Scheduler) error {
        if err := r.Create(ctx, w); err != nil { // domain write
            return err
        }
        return s.Schedule(ctx, widget.Created{ID: w.ID}) // domain event
    })
    

    The wiring binds that Scheduler to the transaction with queue.Bind(tx, q, reg). The task and the domain write commit in ONE transaction — an event is persisted iff its domain write commits. The domain names no queue, exchange, topic, or routing key; it imports neither queue nor dbx.

  • Routing is a wiring concern. A queue.Registry, populated once at startup, maps each value's Go type to its queue and kind; an event goes into the queue of events in an envelope (outbox.JSON), and the Mux of that queue publishes each kind to its topic with outbox.Handler. With the broker off the route is queue.Drop(): the domain write goes through, the event goes nowhere, and the domain does not branch.

    reg := queue.NewRegistry()
    reg.Register[widget.Created]("events", "widget.created", queue.WithEncoder(outbox.JSON))
    
    mux := queue.NewMux()
    mux.Register("widget.created", outbox.Handler(pub, "widgets"))
    if err := reg.Check("events", mux); err != nil { // every event has a handler
        return err
    }
    workers, err := queue.Workers(log, q, outbox.Config("events"), mux.Handle,
        queue.WithMetrics(d.Metrics))
    
  • The workers of the queue publish with at-least-once delivery: a broker that is down costs one failed publish per poll and loses nothing, only broker.Permanent sends an event to the dead letters. Metrics are the queue's: skit_queue_*{queue="events"} by kind, the event type.

  • Each transport maps Topic to its own concept and derives a key from the message (RabbitMQ: exchange, routing key = event type or rabbitmq.WithRoutingKey; Kafka: topic, no key or kafka.WithPartitionKey), so the same event can ship over any broker. broker/rabbitmq publishes CloudEvents v1.0 with publisher confirms and consumes them via a supervised worker.Runnable.

  • Tracing flows end-to-end: the envelope captures the W3C trace context the event is created in (otel.Carrier), the handler carries it onto the broker message, and the consumer restores it with otel.ExtractFromCarrier + opens a child span — so producing a widget and recording its audit row are one trace.

Two runnable scenarios with their READMEs live in examples/: examples/outbox-dbx — a store on dbx that writes an order and its event in one transaction, and the workers that publish it to RabbitMQ; examples/rabbitmq — a domain that knows only broker, with RabbitMQ in the assembly alone.

The skit-x showcase wires it end-to-end: creating a widget schedules widget.Created into the queue of events, its workers publish it to RabbitMQ, and the widgetaudit consumer records it while continuing the producer's trace (see core/widget, widgetaudit, and the e2e test there, which asserts the consumer span is a child of the producer span).

Reliable background processing

worker, queue, and dbx compose into an at-least-once batch pipeline:

  • worker.Pool — bounded-concurrency fan-out of one-shot jobs.
  • worker.Processor[T] — a Source (claim) → Handler (process) → Sink (ack/retry) loop, run on a schedule via worker.Loop.
  • queue — Postgres queues in one table: queue.Workers claims the ready tasks of one queue via FOR UPDATE SKIP LOCKED, so N replicas drain it safely, and the error of the handler decides the outcome (Permanent, Halt, retry with backoff).

The showcase wires this end-to-end: POST /widgets/import enqueues a batch, and a supervised import worker bulk-inserts it (idempotently, via dbx.BulkInsert + ON CONFLICT DO NOTHING). See skit-x/core/widgetimport.

Splitting one binary across pods

A service usually starts as one process doing everything. When the HTTP side has to scale, the background loops must not scale with it — N replicas would poll the same rows N times and any wall-clock cron would fire N times.

The SDK deliberately ships no role/profile type for this: it already gives you two orthogonal gates, and the third question is answered by the command.

Question Answered by
Is this transport or dependency configured at all? an empty key turns it off — HTTP_ADDR, GRPC_ADDR, DEBUG_ADDR, BROKER_HOST
Is this subsystem switched on? its own flag — Worker.Disabled
Does this process run that part, and where? the command, which lists its options

The scaffold (skit new --full) generates exactly that. A process is assembled like Lego from options (internal/app/server/options.go): server.New builds the dependency container and applies the options the command lists, app.Run supervises what they added. Each long-running command is that list:

// internal/cmd/worker.go
func (c *WorkerCommand) Execute(_ []string) error {
	return run(c.ServerOpts,
		server.WithServer(c.Debug.Addr, server.Debug),
		server.WithWorkers(),
	)
}
Command Options
serve WithServer(HTTP_ADDR, Install), WithServer(DEBUG_ADDR, Debug), WithWorkers(), WithConsumers()
http WithServer(HTTP_ADDR, Install), WithServer(DEBUG_ADDR, Debug)
worker WithServer(DEBUG_ADDR, Debug), WithWorkers()
consumer WithServer(DEBUG_ADDR, Debug), WithConsumers()

There is one kind of server: WithServer(addr, route sets…) — an httpserver.Server serving the route sets it is given. A "debug server" is not a type but a server with the technical sets: Health (/healthz, /readyz), Metrics, Pprof, Info (/debug/components), or Debug for all of them. Install is the business API and brings its own request middleware chain (trace, access log, HTTP metrics, timeout, body limit), so a set behaves the same on any server — probes and scrapes never reach the access log or the request timeout. Moving a set to another port is an edit of the command, not a config switch:

run(c.ServerOpts,
	server.WithServer(c.HTTP.Addr, server.Install),
	server.WithServer(":9100", server.Metrics),
	server.WithServer(c.Debug.Addr, server.Health, server.Pprof, server.Info),
)

No role type, no conditions inside the server package — what a process runs and where it listens is read off the command. Splitting a deployment is then a values-only change: the same image with a different command.

Every command keeps a server with Health: /healthz and /readyz are what keep a worker-only pod probeable and alive until SIGTERM, so one probe configuration fits every pod. GET /debug/components reports what the pod runs — the same values it logs at startup:

{"servers":[":8080",":6060"],"workers":0,"consumers":0}   ← http
{"servers":[":6060"],"workers":3,"consumers":0}           ← worker

For a cron that must fire once across the fleet, gate it with lock.Locker (skit add cron --lock postgres).

Why it is built this way, what a live split deployment showed (migration races, requests lost on rollout, the release layout) and what is still open — see research-pod-split.md.

gRPC

grpcserver runs alongside (or instead of) the REST server — both are worker.Runnables supervised by worker.Group, toggled independently by config. It ships:

  • a server span per RPC (otelgrpc, Config.TracerProvider) and the same cross-cutting interceptors as REST (panic recovery, structured access logs, Prometheus metrics) plus automatic *errs.Error → gRPC status mapping (error codes are aligned, so the mapping is a direct cast);
  • messages use the protobuf Opaque API via Protobuf Editions (edition = "2023", api_level = API_OPAQUE) — Google's official path to faster, lower-allocation, lazy-decoding generated code (replaces the third-party vtprotobuf; no extra dependency or codec);
  • transport tuning (MaxRecvMsgSize, NumStreamWorkers, keepalive);
  • gRPC health service and optional reflection.

Code is generated with buf v2 (config lives with the app in skit-x). gRPC v1.84 / protobuf v1.36.

make proto-tools   # install buf, protoc-gen-go, protoc-gen-go-grpc
make proto         # buf lint + generate in ../skit-x (proto -> gen)

Quick start

make build      # build the SDK
make test       # unit tests
make check      # everything CI checks: tidy, go fix, lint, govulncheck, tests

See skit-x for a full application wired with dim (go run ./cmd serve), plus its integration tests (make test-integration).

Directories

Path Synopsis
Package apitest provides helpers for end-to-end HTTP tests that drive a real application handler through an httptest.Server.
Package apitest provides helpers for end-to-end HTTP tests that drive a real application handler through an httptest.Server.
Package app holds the application assembly layer of the SDK.
Package app holds the application assembly layer of the SDK.
Package auditlog records a versioned audit trail of model changes and answers history and diff queries over it.
Package auditlog records a versioned audit trail of model changes and answers history and diff queries over it.
auditbus
Package auditbus records audit entries from events on the in-process eventbus, so a domain package asks for an audit write without importing auditlog: the producer publishes an Event on the bus, and the recorder that Register subscribes to it writes the entry.
Package auditbus records audit entries from events on the in-process eventbus, so a domain package asks for an audit write without importing auditlog: the producer publishes an Event on the bus, and the recorder that Register subscribes to it writes the entry.
auditpg
Package auditpg is the Postgres auditlog.Store: the versions of the models in the audit_log table, one row per version, the snapshot of the model in a JSONB column.
Package auditpg is the Postgres auditlog.Store: the versions of the models in the audit_log table, one row per version, the snapshot of the model in a JSONB column.
auditqueue
Package auditqueue is the durable auditlog.Recorder: Record schedules the audit entry as a task of a skit queue — one INSERT on the request path — and the workers of the queue write it through the audit core.
Package auditqueue is the durable auditlog.Recorder: Record schedules the audit entry as a task of a skit queue — one INSERT on the request path — and the workers of the queue write it through the audit core.
auditrest
Package auditrest is the read side of the audit log over REST: the history of a model, the diff between two of its versions and the fields each version changed, mounted on any skit router in one call.
Package auditrest is the read side of the audit log over REST: the history of a model, the diff between two of its versions and the fields each version changed, mounted on any skit router in one call.
audittest
Package audittest provides an in-memory auditlog.Store for tests and examples, so an audit Core runs without Postgres.
Package audittest provides an in-memory auditlog.Store for tests and examples, so an audit Core runs without Postgres.
Package auth provides authentication and authorization building blocks: a transport-neutral Principal carried in context, credential extraction from HTTP requests, a pluggable Verifier (token -> Principal), a built-in JWT verifier, and net/http middleware for authentication and role-based access control.
Package auth provides authentication and authorization building blocks: a transport-neutral Principal carried in context, credential extraction from HTTP requests, a pluggable Verifier (token -> Principal), a built-in JWT verifier, and net/http middleware for authentication and role-based access control.
Package broker abstracts an event broker behind transport-agnostic Publisher and Handler contracts.
Package broker abstracts an event broker behind transport-agnostic Publisher and Handler contracts.
internal/brokertrace
Package brokertrace records the send span of the broker adapters (broker/kafka, broker/rabbitmq) and reads the creation context of a message from its headers, which the consumer core (broker/internal/consume) links its span to.
Package brokertrace records the send span of the broker adapters (broker/kafka, broker/rabbitmq) and reads the creation context of a message from its headers, which the consumer core (broker/internal/consume) links its span to.
internal/consume
Package consume is the consumer core of the broker adapters (broker/kafka, broker/rabbitmq): it decodes a delivery with the envelope of the consumer, runs the handler under panic recovery and records the handling as a span and in the skit_broker_* metrics.
Package consume is the consumer core of the broker adapters (broker/kafka, broker/rabbitmq): it decodes a delivery with the envelope of the consumer, runs the handler under panic recovery and records the handling as a span and in the skit_broker_* metrics.
kafka
Package kafka is the Apache Kafka adapter for the skit broker abstraction.
Package kafka is the Apache Kafka adapter for the skit broker abstraction.
rabbitmq
Package rabbitmq implements the broker abstraction over RabbitMQ.
Package rabbitmq implements the broker abstraction over RabbitMQ.
Package buildinfo reports the build of the running binary: its version, the VCS revision and time it was built from, and the Go version.
Package buildinfo reports the build of the running binary: its version, the VCS revision and time it was built from, and the Go version.
Package chx is a thin ClickHouse client for analytics and long-term stores.
Package chx is a thin ClickHouse client for analytics and long-term stores.
Package closer manages graceful shutdown of resources.
Package closer manages graceful shutdown of resources.
cmd
skit command
Command skit scaffolds and manages skit-based services.
Command skit scaffolds and manages skit-based services.
Package config standardizes 12-factor configuration on jessevdk/go-flags: a single options struct whose fields carry `long`/`env`/`default`/`description` tags, so the same definition drives CLI flags, environment variables, and `--help`.
Package config standardizes 12-factor configuration on jessevdk/go-flags: a single options struct whose fields carry `long`/`env`/`default`/`description` tags, so the same definition drives CLI flags, environment variables, and `--help`.
Package cron runs jobs on a wall-clock schedule as a supervised worker.Runnable.
Package cron runs jobs on a wall-clock schedule as a supervised worker.Runnable.
Package dbtest is a lightweight way to run Postgres in Docker for tests: one call starts a disposable container (via testcontainers), hands back an open, migrated pool, and removes the container when the test is done.
Package dbtest is a lightweight way to run Postgres in Docker for tests: one call starts a disposable container (via testcontainers), hands back an open, migrated pool, and removes the container when the test is done.
dbx
Package dbx provides SQL helpers on top of jmoiron/sqlx and database/sql: a pool and a transaction behind one Querier, query and exec helpers, transactions that open on a pool and join on a transaction, and bulk insert.
Package dbx provides SQL helpers on top of jmoiron/sqlx and database/sql: a pool and a transaction behind one Querier, query and exec helpers, transactions that open on a pool and join on a transaction, and bulk insert.
pg
Package pg opens a Postgres pool for dbx through the pgx driver, with query tracing, pool metrics and a Classifier of Postgres error codes.
Package pg opens a Postgres pool for dbx through the pgx driver, with query tracing, pool metrics and a Classifier of Postgres error codes.
sqlite
Package sqlite opens a SQLite pool for dbx through a driver the caller registers, modernc.org/sqlite by default, with a Classifier of SQLite result codes.
Package sqlite opens a SQLite pool for dbx through a driver the caller registers, modernc.org/sqlite by default, with a Classifier of SQLite result codes.
Package debugsrv serves operational endpoints — net/http/pprof profiles plus optional metrics and health handlers — on a separate, internal-only listener or as a handler attached to an existing router.
Package debugsrv serves operational endpoints — net/http/pprof profiles plus optional metrics and health handlers — on a separate, internal-only listener or as a handler attached to an existing router.
Package dedup runs an operation once per key and hands the result of its first success to the repeats, the way a cache hands out a value:
Package dedup runs an operation once per key and hands the result of its first success to the repeats, the way a cache hands out a value:
Package dim is a slim, generics-based dependency-injection toolkit: lazy providers and managed resources built from plain functions, with structured logging of initialization and cleanup.
Package dim is a slim, generics-based dependency-injection toolkit: lazy providers and managed resources built from plain functions, with structured logging of initialization and cleanup.
Package errs provides a single, transport-agnostic error type with stable codes, their HTTP statuses (grpcserver maps them to gRPC codes), errors of invalid input fields, and automatic redaction of secrets in user-facing messages.
Package errs provides a single, transport-agnostic error type with stable codes, their HTTP statuses (grpcserver maps them to gRPC codes), errors of invalid input fields, and automatic redaction of secrets in user-facing messages.
Package eventbus is an in-process, synchronous event bus for decoupling domain packages that cannot import one another (avoiding import cycles).
Package eventbus is an in-process, synchronous event bus for decoupling domain packages that cannot import one another (avoiding import cycles).
examples
outbox-dbx command
Command outbox-dbx is the orders service of the outbox example: a write and its event commit in one Postgres transaction, and the workers of the queue of events publish the event to RabbitMQ afterwards.
Command outbox-dbx is the orders service of the outbox example: a write and its event commit in one Postgres transaction, and the workers of the queue of events publish the event to RabbitMQ afterwards.
outbox-dbx/orderapp
Package orderapp is the domain of the orders service in the outbox example.
Package orderapp is the domain of the orders service in the outbox example.
outbox-dbx/orderdb
Package orderdb is the Postgres store of the orders on dbx.
Package orderdb is the Postgres store of the orders on dbx.
rabbitmq command
Command rabbitmq is the orders service of the broker example.
Command rabbitmq is the orders service of the broker example.
rabbitmq/orderapp
Package orderapp is the domain of the orders service in the broker example.
Package orderapp is the domain of the orders service in the broker example.
Package grpcgateway builds a grpc-gateway as a plain http.Handler, so the JSON/HTTP transport runs as just another brick of the server kit — wrapped by httpserver and supervised in the same worker.Group as the gRPC and REST servers.
Package grpcgateway builds a grpc-gateway as a plain http.Handler, so the JSON/HTTP transport runs as just another brick of the server kit — wrapped by httpserver and supervised in the same worker.Group as the gRPC and REST servers.
Package grpcserver bootstraps a gRPC server with the SDK's cross-cutting concerns and exposes it as a worker.Runnable.
Package grpcserver bootstraps a gRPC server with the SDK's cross-cutting concerns and exposes it as a worker.Runnable.
Package grpctest runs an in-memory gRPC server for tests, the gRPC counterpart of apitest.
Package grpctest runs an in-memory gRPC server for tests, the gRPC counterpart of apitest.
Package health provides liveness and readiness HTTP handlers suitable for Kubernetes probes.
Package health provides liveness and readiness HTTP handlers suitable for Kubernetes probes.
Package httpclient builds configured *http.Client values for calling upstream services, and helps consume their JSON responses.
Package httpclient builds configured *http.Client values for calling upstream services, and helps consume their JSON responses.
Package httplog writes the access log of an HTTP server: one record per request, through the application's own *slog.Logger, so access lines share its output, level, trace correlation and sinks.
Package httplog writes the access log of an HTTP server: one record per request, through the application's own *slog.Logger, so access lines share its output, level, trace correlation and sinks.
Package httpmw provides outbound HTTP-client middleware: composable http.RoundTripper wrappers for resilient calls to upstream services.
Package httpmw provides outbound HTTP-client middleware: composable http.RoundTripper wrappers for resilient calls to upstream services.
Package httpserver is the standard-library-idiomatic core of the server kit: a worker.Runnable that serves any http.Handler on its own listener with graceful shutdown.
Package httpserver is the standard-library-idiomatic core of the server kit: a worker.Runnable that serves any http.Handler on its own listener with graceful shutdown.
Package i18n is a thin wrapper over nicksnyder/go-i18n that loads message catalogs from an fs.FS (typically an embed.FS), resolves the request language from an Accept-Language header, and localizes *errs.Error messages by their MessageID/Code with Args as template data.
Package i18n is a thin wrapper over nicksnyder/go-i18n that loads message catalogs from an fs.FS (typically an embed.FS), resolves the request language from an Accept-Language header, and localizes *errs.Error messages by their MessageID/Code with Args as template data.
internal
brokertest
Package brokertest starts the brokers of the skit tests in containers — RabbitMQ and a single-node Kafka — for the tests of broker/kafka, broker/rabbitmq and outbox.
Package brokertest starts the brokers of the skit tests in containers — RabbitMQ and a single-node Kafka — for the tests of broker/kafka, broker/rabbitmq and outbox.
httpw
Package httpw provides a single canonical http.ResponseWriter proxy shared by every middleware that needs to observe a response.
Package httpw provides a single canonical http.ResponseWriter proxy shared by every middleware that needs to observe a response.
pgschema
Package pgschema provisions the Postgres tables of the SDK storage packages at startup (queue, auditlog/auditpg, translation/translationpg) and derives the advisory-lock keys of the SDK (lock).
Package pgschema provisions the Postgres tables of the SDK storage packages at startup (queue, auditlog/auditpg, translation/translationpg) and derives the advisory-lock keys of the SDK (lock).
prom
Package prom holds the Prometheus helpers the SDK packages share: register or get the collector already registered (MustRegister), the bucket bounds of durations (DurationBuckets), a duration observed with the trace of its context as the exemplar (ObserveDuration), and the metrics of the runs of periodic work (Runs), which worker and cron record.
Package prom holds the Prometheus helpers the SDK packages share: register or get the collector already registered (MustRegister), the bucket bounds of durations (DurationBuckets), a duration observed with the trace of its context as the exemplar (ObserveDuration), and the metrics of the runs of periodic work (Runs), which worker and cron record.
runspan
Package runspan records a run of periodic work — a worker tick, a cron run — as the root span of its own trace, for worker and cron.
Package runspan records a run of periodic work — a worker tick, a cron run — as the root span of its own trace, for worker and cron.
Package lock provides distributed mutual exclusion for work that must run on at most one replica at a time — most often a scheduled job (see the cron package and `skit add cron --lock`).
Package lock provides distributed mutual exclusion for work that must run on at most one replica at a time — most often a scheduled job (see the cron package and `skit add cron --lock`).
Package logger builds the service's *slog.Logger: a JSON handler chain that correlates every record with the active trace, tags it with the service identity, and can fire side-effect hooks per level.
Package logger builds the service's *slog.Logger: a JSON handler chain that correlates every record with the active trace, tags it with the service identity, and can fire side-effect hooks per level.
Package metrics is the one Prometheus registry of a process: the base preset, the HTTP server metrics and the scrape handler.
Package metrics is the one Prometheus registry of a process: the base preset, the HTTP server metrics and the scrape handler.
Package middleware provides standard net/http server middleware for skit services.
Package middleware provides standard net/http server middleware for skit services.
Package migrate applies SQL schema migrations from an embedded filesystem.
Package migrate applies SQL schema migrations from an embedded filesystem.
Package order describes the ordering of a list query: a By value (an allowlisted field name + an ASC/DESC direction) and a Parse that builds one from untrusted "field,direction" request input.
Package order describes the ordering of a list query: a By value (an allowlisted field name + an ASC/DESC direction) and a Parse that builds one from untrusted "field,direction" request input.
Package otel is the OpenTelemetry API of skit: tracers for SDK packages, span errors, suppression of background traces and W3C trace context propagation.
Package otel is the OpenTelemetry API of skit: tracers for SDK packages, span errors, suppression of background traces and W3C trace context propagation.
otlp
Package otlp builds the OTLP/gRPC span exporter for otel/setup.
Package otlp builds the OTLP/gRPC span exporter for otel/setup.
setup
Package setup installs the OpenTelemetry SDK of a process: the TracerProvider, the Resource, the sampler, the propagator and the OTel diagnostics.
Package setup installs the OpenTelemetry SDK of a process: the TracerProvider, the Resource, the sampler, the propagator and the OTel diagnostics.
Package outbox publishes domain events to a message broker through a queue of events: an event is a task of the queue package, scheduled in the transaction of its domain change and published by the workers of its queue.
Package outbox publishes domain events to a message broker through a queue of events: an event is a task of the queue package, scheduled in the transaction of its domain change and published by the workers of its queue.
Package page provides a small, validated value for query paging, shared by the transport (parsing ?page=/?rows= or gRPC fields) and the store (binding :offset / :rows_per_page).
Package page provides a small, validated value for query paging, shared by the transport (parsing ?page=/?rows= or gRPC fields) and the store (binding :offset / :rows_per_page).
Package poller maintains a single "current value" that is refreshed by periodically calling a Getter.
Package poller maintains a single "current value" that is refreshed by periodically calling a Getter.
provider
postgres
Package postgres provides a ready Postgres connection pool for dim: Resource opens it with pg.Open, checks it is reachable and closes it on shutdown.
Package postgres provides a ready Postgres connection pool for dim: Resource opens it with pg.Open, checks it is reachable and closes it on shutdown.
redis
Package redis provides a ready Redis client (github.com/redis/go-redis) for dim: Resource opens it, checks it with a PING and closes it on shutdown.
Package redis provides a ready Redis client (github.com/redis/go-redis) for dim: Resource opens it, checks it with a PING and closes it on shutdown.
sentry
Package sentry initializes the Sentry SDK (github.com/getsentry/sentry-go) for dim: Resource initializes it, returns the current Hub and flushes the buffered events on shutdown.
Package sentry initializes the Sentry SDK (github.com/getsentry/sentry-go) for dim: Resource initializes it, returns the current Hub and flushes the buffered events on shutdown.
translator
Package translator provides a ready i18n.Translator for dim: Resource builds it from the message files of the service.
Package translator provides a ready i18n.Translator for dim: Resource builds it from the message files of the service.
Package queue runs durable background work with at-least-once delivery, safe for concurrent workers across goroutines and replicas.
Package queue runs durable background work with at-least-once delivery, safe for concurrent workers across goroutines and replicas.
Package rest is a tiny typed-handler layer over net/http.
Package rest is a tiny typed-handler layer over net/http.
jsonapi
Package jsonapi encodes rest responses as JSON:API documents (application/vnd.api+json) with github.com/hashicorp/jsonapi.
Package jsonapi encodes rest responses as JSON:API documents (application/vnd.api+json) with github.com/hashicorp/jsonapi.
mid
Package mid provides application-layer middleware: rest.MidFunc values that wrap a typed rest.HandlerFunc and operate on the ResponseEncoder it returns (the typed value), not on raw bytes.
Package mid provides application-layer middleware: rest.MidFunc values that wrap a typed rest.HandlerFunc and operate on the ResponseEncoder it returns (the typed value), not on raw bytes.
router
Package router wraps the standard library's net/http.ServeMux with nestable groups and two cooperating handler/middleware layers: net/http transport middleware and typed rest application middleware.
Package router wraps the standard library's net/http.ServeMux with nestable groups and two cooperating handler/middleware layers: net/http transport middleware and typed rest application middleware.
Package retry runs an operation again on failure, with exponential backoff, optional jitter, a bounded attempt budget, and an early stop on terminal errors.
Package retry runs an operation again on failure, with exponential backoff, optional jitter, a bounded attempt budget, and an early stop on terminal errors.
Package safetick provides panic recovery helpers for long-running background loops and message-consumer callbacks, so a single bad tick or message cannot crash the worker.
Package safetick provides panic recovery helpers for long-running background loops and message-consumer callbacks, so a single bad tick or message cannot crash the worker.
Package translation provides a type-safe, declarative system for translating model content stored per-record (distinct from i18n, which localizes static catalog/error strings).
Package translation provides a type-safe, declarative system for translating model content stored per-record (distinct from i18n, which localizes static catalog/error strings).
translationpg
Package translationpg is the Postgres translation.Store: each translatable column of a record is a row of the translations table, keyed by (model_name, column_name, key_id, language_id).
Package translationpg is the Postgres translation.Store: each translatable column of a record is a row of the translations table, keyed by (model_name, column_name, key_id, language_id).
translationrest
Package translationrest wires the translation package into a skit REST router as a single rest.MidFunc that translates responses automatically.
Package translationrest wires the translation package into a skit REST router as a single rest.MidFunc that translates responses automatically.
translationtest
Package translationtest provides an in-memory translation.Store for tests, so a Translator runs without Postgres.
Package translationtest provides an in-memory translation.Store for tests, so a Translator runs without Postgres.
Package validate checks a struct by its `validate:` tags (github.com/go-playground/validator) and reports the failures as an errs.FieldErrors error.
Package validate checks a struct by its `validate:` tags (github.com/go-playground/validator) and reports the failures as an errs.FieldErrors error.
Package worker runs the background work of a service: supervised components, recurring loops, bounded fan-out and claim-based batches.
Package worker runs the background work of a service: supervised components, recurring loops, bounded fan-out and claim-based batches.

Jump to

Keyboard shortcuts

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