- Go 99.1%
- Makefile 0.6%
- Shell 0.3%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .github/workflows | ||
| backup | ||
| cookie | ||
| docs | ||
| environment | ||
| log | ||
| metrics | ||
| middleware | ||
| minify | ||
| mockidp | ||
| oidcauth | ||
| pubsub | ||
| scripts | ||
| session | ||
| sqlitestore | ||
| utils | ||
| web | ||
| .gitignore | ||
| .golangci.yaml | ||
| .goreleaser.yaml | ||
| AGENTS.md | ||
| CLAUDE.md | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| Makefile | ||
| README.md | ||
| renovate.json | ||
| VERSION | ||
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 viagorilla/securecookie. A singletonSecureCookieis initialized once viasync.Once. CallInitSecureCookie(hashKey, blockKey)at startup with stable keys; omitting it auto-generates random keys (which are useless across restarts).session—Cookiestruct representing a session (ID, created/expiry times, authenticated flag), used bymiddlewareto validate auth.middleware— Standardnet/httpmiddleware: cookie-based auth (GetAuthMiddlewareForCookie), API key auth (GetAuthMiddlewareForSingleAPIKey,GetAuthMiddlewareWithFunction), structured request logging, and panic recovery. HTMX requests in the auth middleware getHX-Refreshinstead of a redirect.pubsub—UniversalPubSubwraps either an in-memoryLocalPubSubor aRedisPubSub, selected byNewUniversalPubSub(opts)based on whetheropts.Redisis set. Channel names are prefixed withopts.Prefix+:when non-empty.metrics— Prometheus-compatible metrics backed byVictoriaMetrics/metrics: a/metricshandler 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) plusGetAcceptType.CheckErrorlogs viaslogand writeshttp.Error. Ready-made handlers live inweb/ping,web/health,web/ready,web/favicon, andweb/errorroutes.environment— Parses.env,.override.env, and any extra files withgodotenv. 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 onlog/slog:InitLoggerwith text (FormatText, tint-colored) or JSON (FormatJSON) output, andLevelFromStringfor parsing level names from strings. Importing only this package does not link the JS minifier.minify— JS minification helpers (MinifyJS,GetMinifier) backed bytdewolff/minify.utils— Miscellaneous helpers:WrapErrors,RandString, generics (Filter), IP extraction, version info. Deprecated entries (kept for one release):InitLogger/LoggerConfig(uselog),MinifyJS/GetMinifier(useminify),RunCmd/RunCmdInPath,Contains, andPointerTo.oidcauth— OIDC sign-in with server-side sessions and bearer-token protection for MCP endpoints, generic over the application's identity type (Config.Authorizemaps verified claims to it). Appendoidcauth.Migrationto the application's store migrations for the session tables.sqlitestore— SQLite store scaffold: opening with WAL and foreign keys, orderedPRAGMA user_versionmigrations supplied by the application, and single-connection read/write transaction helpers.backup— Periodic consistent SQLite backups viaVACUUM INTO, with configurable file prefix and retention.mockidp— Reusable loopback-only mock OIDC provider for tests:Startfor Go tests,Runfor 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.