Go Commons
  • Go 99.1%
  • Makefile 0.6%
  • Shell 0.3%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-26 19:22:38 +03:00
.github/workflows Update zekihan/release-workflows digest to 16e6eb4 (#47) 2026-11-22 20:43:18 +03:00
backup feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
cookie Test session, cookie, favicon and environment edge cases (#46) 2026-11-22 20:36:24 +03:00
docs Unify publishing workflows 2026-11-05 04:51:49 +03:00
environment Test session, cookie, favicon and environment edge cases (#46) 2026-11-22 20:36:24 +03:00
log OPS-525: split utils into log and minify packages, add JSON log format, deprecate unused APIs (#52) 2026-11-25 20:09:45 +03:00
metrics Capture mux route through request copies in metrics middleware (#49) 2026-11-23 15:10:18 +03:00
middleware Abort panicking handlers after response commitment (#55) 2026-11-25 20:24:08 +03:00
minify OPS-525: split utils into log and minify packages, add JSON log format, deprecate unused APIs (#52) 2026-11-25 20:09:45 +03:00
mockidp feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
oidcauth OPS-551: Bound OIDC HTTP requests by default (#60) 2026-11-26 18:41:51 +03:00
pubsub OPS-525: split utils into log and minify packages, add JSON log format, deprecate unused APIs (#52) 2026-11-25 20:09:45 +03:00
scripts Keep local settings and version bumps private 2026-10-11 15:29:49 +03:00
session Test session, cookie, favicon and environment edge cases (#46) 2026-11-22 20:36:24 +03:00
sqlitestore Enforce read-only SQLite transactions (#61) 2026-11-26 19:16:32 +03:00
utils OPS-525: split utils into log and minify packages, add JSON log format, deprecate unused APIs (#52) 2026-11-25 20:09:45 +03:00
web Set a stable Content-Type for ICO favicons (#62) 2026-11-26 19:22:38 +03:00
.gitignore Keep local settings and version bumps private 2026-10-11 15:29:49 +03:00
.golangci.yaml Preserve gofumpt call balancing 2026-11-06 04:02:46 +03:00
.goreleaser.yaml Unify publishing workflows 2026-11-05 04:51:49 +03:00
AGENTS.md feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
CLAUDE.md refactor: rename CLAUDE.md to AGENTS.md 2026-06-18 23:41:43 +03:00
go.mod feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
go.sum feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
LICENSE feat: add initial implementation 2025-07-27 08:29:30 +03:00
Makefile Pin audit tool versions (#51) 2026-11-25 20:09:54 +03:00
README.md feat: add shared OIDC auth, SQLite store, backup and mock IdP packages (#58) 2026-11-25 22:10:53 +03:00
renovate.json OPS-513: extend the shared Renovate preset (#54) 2026-11-25 20:18:35 +03:00
VERSION OPS-551: Bound OIDC HTTP requests by default (#60) 2026-11-26 18:41:51 +03:00

go-commons

Shared Go utilities for building HTTP services: secure cookies, sessions, net/http middleware, pub/sub, response helpers, environment loading, and assorted helpers. This is a pure library — there is no main package.

Install

go get github.com/zekihan/go-commons

Packages

  • cookie — Secure cookie encode/decode via gorilla/securecookie. A singleton SecureCookie is initialized once via sync.Once. Call InitSecureCookie(hashKey, blockKey) at startup with stable keys; omitting it auto-generates random keys (which are useless across restarts).
  • session — Cookie struct representing a session (ID, created/expiry times, authenticated flag), used by middleware to validate auth.
  • middleware — Standard net/http middleware: cookie-based auth (GetAuthMiddlewareForCookie), API key auth (GetAuthMiddlewareForSingleAPIKey, GetAuthMiddlewareWithFunction), structured request logging, and panic recovery. HTMX requests in the auth middleware get HX-Refresh instead of a redirect.
  • pubsub — UniversalPubSub wraps either an in-memory LocalPubSub or a RedisPubSub, selected by NewUniversalPubSub(opts) based on whether opts.Redis is set. Channel names are prefixed with opts.Prefix + : when non-empty.
  • metrics — Prometheus-compatible metrics backed by VictoriaMetrics/metrics: a /metrics handler with Go runtime and process metrics, HTTP middleware labelled by method, route pattern, and status, and app-specific counters, gauges, and histograms.
  • web — HTTP response helpers (Write, WriteString, CheckError) plus GetAcceptType. CheckError logs via slog and writes http.Error. Ready-made handlers live in web/ping, web/health, web/ready, web/favicon, and web/errorroutes.
  • environment — Parses .env, .override.env, and any extra files with godotenv. Values override the process environment and later files override earlier files. Missing files and directories are skipped; an error stops loading without undoing values from earlier files.
  • log — Structured logging helpers built on log/slog: InitLogger with text (FormatText, tint-colored) or JSON (FormatJSON) output, and LevelFromString for parsing level names from strings. Importing only this package does not link the JS minifier.
  • minify — JS minification helpers (MinifyJS, GetMinifier) backed by tdewolff/minify.
  • utils — Miscellaneous helpers: WrapErrors, RandString, generics (Filter), IP extraction, version info. Deprecated entries (kept for one release): InitLogger/LoggerConfig (use log), MinifyJS/GetMinifier (use minify), RunCmd/RunCmdInPath, Contains, and PointerTo.
  • oidcauth — OIDC sign-in with server-side sessions and bearer-token protection for MCP endpoints, generic over the application's identity type (Config.Authorize maps verified claims to it). Append oidcauth.Migration to the application's store migrations for the session tables.
  • sqlitestore — SQLite store scaffold: opening with WAL and foreign keys, ordered PRAGMA user_version migrations supplied by the application, and single-connection read/write transaction helpers.
  • backup — Periodic consistent SQLite backups via VACUUM INTO, with configurable file prefix and retention.
  • mockidp — Reusable loopback-only mock OIDC provider for tests: Start for Go tests, Run for external e2e harnesses that need the provider configuration as one JSON line from a small command.

utils.GetIP trusts X-Forwarded-For and X-Real-IP before the remote address. Ensure a trusted proxy controls these headers before using the result for access control or other security decisions.

Development

make tidy    # fmt + go mod tidy
make lint    # tidy + golangci-lint run --fix
make test    # run all tests with -race
make audit   # vet + staticcheck + govulncheck + tests

Publishing and manual recovery: Publishing.

Metrics

registry := metrics.New()

mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", handler)

// Route label is the ServeMux pattern ("/users/{id}"), never the raw path.
srv := &http.Server{Handler: registry.Middleware(mux)}

// App-specific metrics; labels must stay bounded (no IDs or raw paths).
jobs := registry.Counter("app_jobs_total", metrics.Labels{"kind": "sync"})
jobs.Inc()
registry.Gauge("app_queue_depth", nil).Set(3)

// Serve /metrics on an internal-only address, not via public ingress.
go registry.ListenAndServe(ctx, ":9090")

Mount registry.Handler() on the main mux instead if a separate listener is not wanted. For non-ServeMux routing use metrics.MiddlewareWithRoute or metrics.WithRoute to supply a bounded route name.

If middlewares between registry.Middleware and the mux copy the request (for example with Request.WithContext), the mux pattern is set only on the copy. Wrap the mux itself with metrics.CapturePattern so the route still reaches the metrics middleware; otherwise every request is labelled unknown:

srv.Handler = registry.Middleware(logRequests(metrics.CapturePattern(mux)))

In Kubernetes, annotate the pod for vmagent scraping on the metrics port and path /metrics.