go-libs

module
v0.6.0 Latest Latest
Warning

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

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

README

go-libs · latest published v0.6.0

Production Go microservices frequently reimplement identical operational plumbing—circuit breakers, rate limiters, singleflight caching, worker pools, structured error hierarchies, and graceful shutdown—leading to inconsistent behavior and dependency sprawl across services. go-libs provides a unified suite of 41 packages and HTTP/Gin middleware with verified statement coverage under a single module BOM. Each package is independently importable with zero business domain logic, delivering hardened operational primitives without framework lock-in.

Go Reference Docs Portal llms.txt CI Coverage OpenSSF Scorecard

Shared, zero-business-logic Go libraries and middleware for cloud-native microservices.

📖 Engineering Documentation & Architecture Blueprint
Complete subsystem guides, module selection flowcharts, architectural rationales, and execution topologies:

Each package is independently importable, fully tested with verified statement coverage across critical paths, and has no dependency on any external business domain layer. All packages live under one go.mod to guarantee version lock-step across every service that imports them.

Multi-Package "BOM" Architecture

This repository uses a Single Module Monorepo pattern. There is only one go.mod file at the root of go-libs.

Why is this the best "BOM" (Bill of Materials) way? By having a single github.com/abeta-dev/go-libs@v0.6.0 import, you guarantee that all internal packages (db, recovery, ratelimit, cache, workerpool, metrics, retry, telemetry) are perfectly synced to the same tested release threshold across all your microservices. It prevents version drifting between interconnected middleware packages natively.

Minimal-Footprint Imports

Despite living in a single module, each package resolves independently in Go's dependency graph. Importing lightweight leaf packages (such as shutdown, retry, sliceutil, env, or apperror) pulls zero heavy third-party frameworks (gin, pgx, or opentelemetry) into your go.sum or compiled binary.

You can verify this claim in 30 seconds from a clean scratch directory:

# 1. Create an isolated scratch module
mkdir -p /tmp/verify-leaf && cd /tmp/verify-leaf
go mod init verify-leaf

# 2. Write a minimal app importing only shutdown
cat << 'EOF' > main.go
package main

import (
	"fmt"
	"time"
	"github.com/abeta-dev/go-libs/shutdown"
)

func main() {
	sm := shutdown.New(5 * time.Second)
	fmt.Println("Graceful shutdown manager ready:", sm != nil)
}
EOF

# 3. Resolve dependencies
go get github.com/abeta-dev/go-libs@v0.6.0
go mod tidy

# 4. Prove no heavy frameworks exist in go.sum (exits 0 with zero output if clean)
grep -E 'gin-gonic|jackc/pgx|opentelemetry' go.sum || echo "VERIFIED: Zero heavy dependencies in go.sum"

🛡️ Continuous CI Regression Guard: Every pull request runs scripts/check_leaf_imports.sh in an isolated sandbox across 35 minimal-footprint leaf packages (and verifies 29 Depth-0 pure internal leaves) to ensure no heavy framework can ever quietly leak into lightweight primitives.


Installation

go get github.com/abeta-dev/go-libs@v0.6.0

Requirements:

  • Go 1.26.0 or higher

Quick Start: Headline Packages

1. retry — Context-Aware Backoff & Jitter

Declarative execution with exponential jitter backoff, deadline awareness, and non-retryable error short-circuiting:

import (
	"context"
	"time"

	"github.com/abeta-dev/go-libs/retry"
)

cfg := retry.Config{
	Attempts:    3,
	InitialWait: 100 * time.Millisecond,
	MaxWait:     2 * time.Second,
	Strategy:    retry.ExponentialJitter,
}

err := retry.Do(ctx, cfg, func(ctx context.Context) error {
	return fetchRemoteData(ctx)
})
2. circuitbreaker — Fail-Fast 3-State Machine

Protects downstream dependencies using consecutive failures or failure ratio thresholds with immediate short-circuiting when open:

import (
	"context"
	"time"

	"github.com/abeta-dev/go-libs/circuitbreaker"
)

// Trips open after 3 consecutive failures; re-tests after 500ms
cb := circuitbreaker.NewConsecutiveBreaker(3, 500*time.Millisecond)

err := cb.Execute(ctx, func() error {
	return queryExternalService(ctx)
})
3. ratelimit — Token Bucket & Sliding Window

In-memory multi-tenant rate limiting and standard HTTP middleware with RFC-compliant RateLimit-* headers:

import (
	"net/http"
	"time"

	"github.com/abeta-dev/go-libs/ratelimit"
)

// Standalone in-memory rate limiter (100 req / minute)
limiter := ratelimit.NewTokenBucket(100, time.Minute)
if !limiter.Allow("tenant-client-ip") {
	// 429 Too Many Requests
}

// Or as standard HTTP middleware with RFC headers
handler := ratelimit.New(100, time.Minute)(nextHandler)
4. cache — Singleflight Stampede-Protected In-Memory Cache

Generic typed cache with singleflight request coalescing (GetOrFetch), TTL expiration, and pluggable eviction policies:

import (
	"context"
	"time"

	"github.com/abeta-dev/go-libs/cache"
)

c := cache.NewTypedCache[UserProfile](
	10_000,
	cache.WithEvictionPolicy(cache.PolicySampledLRU),
)

// Singleflight prevents concurrent thundering herd queries for identical keys
profile, err := c.GetOrFetch(ctx, "user:123", 5*time.Minute, func(ctx context.Context) (UserProfile, error) {
	return loadUserFromDB(ctx, 123)
})
5. workerpool — Bounded Panic-Safe Concurrency

Fixed-size worker pools with task buffering, metric collection, and graceful drain-and-stop:

import (
	"github.com/abeta-dev/go-libs/workerpool"
)

// 4 concurrent workers, queue buffer of 100 tasks
wp := workerpool.New(4, 100)
defer wp.Stop() // drains remaining queue before shutting down

_ = wp.Submit(func() {
	processJob(job)
})
6. env — Zero-Dependency Typed Environment Parsing

Safe environment parsing with sensible fallbacks and zero external reflection dependencies:

import (
	"time"

	"github.com/abeta-dev/go-libs/env"
)

port := env.Int("PORT", 8080)
dbTimeout := env.Duration("DB_TIMEOUT", 5*time.Second)
isProduction := env.Bool("PRODUCTION", true)
appName := env.String("APP_NAME", "order-service")
7. apperror — Structured Domain Error Hierarchy

Canonical typed error codes mapping cleanly to HTTP status codes with errors.Is support:

import (
	"github.com/abeta-dev/go-libs/apperror"
)

func FindUser(id string) (*User, error) {
	return nil, apperror.NotFound("user not found")
}

// Check error codes with standard errors.Is semantics
if apperror.Is(err, apperror.CodeNotFound) {
	status := err.(*apperror.Error).GetStatus() // 404
}

Why go-libs vs. Alternatives?

Go developers frequently face a choice between assembling dozens of single-purpose third-party packages (each with differing API idioms, logging adapters, and maintenance cadences) or maintaining bespoke operational code in every repository. go-libs provides a deliberate middle ground: a unified BOM of standard operational primitives with zero business domain logic and zero framework lock-in.

Capability Common Alternative Why Choose go-libs? Trade-offs & When to Use Alternative
Circuit Breaker sony/gobreaker Native support for both consecutive-failure and failure-ratio algorithms, built-in metrics adapters, context-aware execution, and zero external dependencies. sony/gobreaker is a mature industry standard; choose it if you need its specific cyclic generation model or custom count windows without adopting our metrics interface.
Retry & Backoff cenkalti/backoff Clean, declarative retry.Do and retry.DoWithResult[T] APIs with native exponential jitter, deadline cancellation, and automatic classified non-retryable error short-circuiting. cenkalti/backoff offers dedicated ticker implementations and complex custom retry state machines; choose it if you need streaming retry tickers rather than function invocation.
Rate Limiter uber-go/ratelimit Multi-tenant keyed limiters (TokenBucket, SlidingWindow), CIDR proxy header resolution, and RFC-compliant RateLimit-* HTTP headers. uber-go/ratelimit uses an atomic leaky bucket designed for ultra-high-throughput request pacing; choose it if you need microsecond-level smooth pacing for outbound traffic rather than inbound multi-tenant HTTP throttling.
In-Memory Cache dgraph-io/ristretto / allegro/bigcache Generic type safety ([T]), built-in singleflight request coalescing (GetOrFetch prevents thundering herds), pluggable eviction policies (SampledLRU, LRU, LFU, FIFO), and zero CGo/unsafe code. ristretto and bigcache are optimized for high concurrency with millions of entries using off-heap buffers or complex TinyLFU pipelines; choose them if you are caching tens of gigabytes of data where GC pause reduction is paramount.

Reference Blueprint Microservice & Cloud-DevOps Suite

A complete, runnable reference implementation composing ginmw, cache, workerpool, health, logger, metrics, circuitbreaker, retry, and shutdown into a unified production service is available in examples/microservice/:

# Run the reference microservice
go run ./examples/microservice

# Run its end-to-end integration tests
go test -v -race ./examples/microservice

# Build the distroless minimal Docker container (<18MB, non-root UID 65532)
docker build -t microservice:1.0.0 -f examples/microservice/Dockerfile .

# Deploy via production Kubernetes Helm Chart (with HPA, PDB, ServiceMonitor)
helm upgrade --install microservice ./deploy/helm/microservice

Package Inventory

1. Framework-Agnostic Core Infrastructure & Resilience
Package Import suffix Key exports & Description
metrics /metrics Counter, Gauge, Histogram interfaces and zero-allocation no-ops for pluggable Prometheus/OpenTelemetry instrumentation
retry /retry Do, DoWithResult[T], Config with Constant, Linear, Exponential, ExponentialJitter backoff strategies
circuitbreaker /circuitbreaker NewConsecutiveBreaker(maxFailures, timeout, opts...), NewRatioBreaker(...) — outbound 3-state machine
clock /clock Clock, RealClock, FakeClock — deterministic mockable time abstraction for sleep-free tests
workerpool /workerpool New(workers, queueSize, opts...), Submit(task) error, SubmitContext(ctx, task) error, WithMetrics, WithPanicHandler
cache /cache NewTypedCache[T](opts...), GetOrFetchWithStatus, DeletePrefix, SetWithTags, InvalidateTag, FetchStatus — generic singleflight stampede-protected cache
shutdown /shutdown New(timeout), .Register(name, fn), .Execute(ctx), .Wait() — concurrent graceful teardown manager
async /async Go, GoCtx, Parallel, ParallelLimit — panic-safe goroutines and bounded concurrency orchestration
fsm /fsm NewMachine, ValidateTransition, CanTransition — declarative in-memory finite state machine with O(1) transitions

2. Functional Generics, Errors & Foundation
Package Import suffix Key exports & Description
sliceutil /sliceutil Reduce, GroupBy, Chunk, Unique, Flatten, First — generic slice algorithms beyond standard slices
maputil /maputil Merge, Filter — generic type-safe map operations beyond standard maps
apperror /apperror CodeNotFound, CodeUnauthorized, CodeConflict, New, Wrap, Is — canonical structured domain errors
env /env String, Int, Bool, Duration, MustString, MustInt — zero-dependency typed OS environment parsers
logger /logger Default(), FromContext(ctx), WithContext(ctx, l), WithField, WithFields — context-aware structured slog
stringutil /stringutil OrDefault, MaskEmail, MaskPhone, TrimAndLower, Truncate, RandomStringFromReader — safe string operations
timeutil /timeutil NowIn(loc), FormatIn, StartOfDay, EndOfDay, AddBusinessDays — parametric time helpers
cryptoutil /cryptoutil GenerateTempPassword(n), HashPassword(pwd), ComparePassword(hash, pwd) — secure credential helpers backed by crypto/rand (CSPRNG) and golang.org/x/crypto/bcrypt (OWASP cost factor 12)
uuidutil /uuidutil New, NewString, NewV7, NewV7String, Parse, ParsePtr, MustParse, IsValid, IsNil — centralized RFC 4122 / RFC 9562 UUID v4 & v7 operations

3. Framework-Agnostic HTTP Middleware & Transport

Compatible with standard library http.Handler, Chi, Echo, or any Go HTTP framework.

Package Import suffix Key exports & Description
httpclient /httpclient New(opts...), NewRoundTripper, WithRetry, WithCircuitBreaker, WithRateLimiter — resilient composed HTTP transport client
ratelimit /ratelimit New(cap, window, opts...), NewGlobal(), NewAuth(), RFC RateLimit-* headers, WithMetrics
securityheaders /securityheaders New(opts...), WithDisableHSTS(), WithCacheControl(...) — OWASP defensive security headers (CSP, HSTS, X-Frame, SDUI cache control)
bodylimit /bodylimit New(maxBytes), MB(n), KB(n), String(bytes) — HTTP request body size limiter preventing payload inflation attacks
compress /compress Middleware(cfg...), Negotiate(acceptEncoding), PrecompressedFileServer, PrecompressedFS — SSE-safe RFC 9110 Brotli (br) & Gzip (gzip) compression plus .br/.gz static/SPA file server with CSRF <meta> injection
etag /etag Middleware(opts...), Compute, Match, WriteVersionedJSON, WithAppVersion, WithIgnoreJSONKeys — RFC 9110 ETag / 304 Not Modified with volatile JSON key stripping and X-Client-App-Version auto-bust
loopbackguard /loopbackguard ValidateLoopbackAddr, New(opts...), Guard.Middleware, GenerateCSRFToken — loopback DNS-rebinding Host allowlist, Sec-Fetch-Site / Origin Same-Origin guard, and constant-time per-boot CSRF protection
sse /sse NewStream, Handler, Event, WithHeartbeat, WithRetry — first-class Server-Sent Events (text/event-stream) streaming with keepalives, Last-Event-ID, and context cancellation
httpmw /httpmw Chain, Use, Logger, Recovery, REDMetrics, MetricsEndpoint, RequireTenant, ETag, LoopbackGuard, SSE — zero-Gin, zero-pgx, zero-OTel stdlib net/http middleware suite
requestid /requestid Middleware, FromContext(ctx), Header constant — W3C correlation ID propagation
recovery /recovery Middleware(opts...) — JSON panic recovery with structured slog output
httputil /httputil OK, Created, NoContent, Error, ErrorFromDomain, ValidationError — standardized responses
pagination /pagination Parse(r), NewResponse, NewTypedResponse[T], PaginateSlice[T] — query parsing, response formatting, and generic slice pagination
health /health New(checks...), LivenessHandler, ReadinessHandler, .Handler — parallel HTTP probe service
idempotency /idempotency NewMemoryStore(), NewPGStore(db.DBTX, opts...), Store — two-phase request deduplication with in-memory or PostgreSQL storage
validation /validation FormatErrors(err) — human-readable validator/v10 struct validation error formatting

4. Data Access & Security Primitives
Package Import suffix Key exports & Description
db /db Connect(ctx, url, opts), WithTx(ctx, pool, fn), WithQuerier(ctx, q), GetQuerier(ctx, pool), DBTX interface — pgx connection pool & transaction wrapper
sqlite /sqlite Open(ctx, path, opts...), Wrap, WithImmediateTx, Migrate, Backup, Checkpoint — driver-agnostic embedded SQLite WAL helper (busy_timeout, BEGIN IMMEDIATE, user_version, atomic VACUUM INTO)
rbac /rbac NewEngine(), Engine.Match(pattern, action) — role-based access control engine
rbaccontext /rbaccontext WithPermissions(ctx, perms), Can(ctx, perm), CanAny(ctx, perms...) — permission helpers
telemetry /telemetry NewTracerProvider(opts...), InitProvider(tp), StartSpan(ctx, tracer, span) — OpenTelemetry distributed tracing
jwks /jwks GetECPublicKey, NewResolver — thread-safe cached ECDSA P-256 JWKS public key resolver with stale fallback

[!NOTE] Domain & Application Accelerators: High-level business and application-layer capabilities (Multi-channel Notifications, PDF Generation with GST Invoice Templates, Transactional Outbox Engine with PostgreSQL DDL, Partitioned Audit Logging, Brotli/Gzip Streaming CSV Data Export, Zero-Leak Object Storage with Presigned URLs, and Lease-Fenced Periodic Job Scheduling) are maintained in the companion accelerator repository: github.com/abeta-dev/go-app-kit.


5. Gin-Specific Middleware Pipeline (ginmw)

All Gin-specific middleware wrappers live in ginmw for uniform imports.

Package Import suffix Key exports & Description
ginmw /ginmw AuthMiddleware, GenerateToken, GetClaims, Compress, RateLimit, Recovery, RequestID, SecurityHeaders, Idempotency, Logger, RequireTenant, RespondSuccess, RespondError, REDMetrics — unified Gin web framework middleware suite
Function Purpose
ginmw.AuthMiddleware() Validates Bearer JWT; injects *Claims into context
ginmw.GenerateToken(claims, timeInMins) Mints signed HS256 access token with custom TTL (claims *Claims, timeInMins int64)
ginmw.GetClaims(c) Extracts *Claims from gin context
ginmw.RBAC(provider) Loads live DB permissions per request into context
ginmw.RequirePermission(perm) Aborts 403 if context lacks exact permission
ginmw.RequireAnyPermission(perms...) Aborts 403 if context lacks all listed permissions
ginmw.AdminOnly() Restricts route to platform-admin roles
ginmw.CORS(allowedOrigins) CORS with wildcard-suffix support (*.example.com)
ginmw.GlobalRateLimit() IP token-bucket: 200 req/min (flood protection)
ginmw.AuthRateLimit() IP token-bucket: 10 req/min (brute-force protection)
ginmw.LimitBodyDefault() 2 MB max body for all API routes
ginmw.LimitBodyAuth() 4 KB max body for auth endpoints
ginmw.Compress(cfg...) SSE-safe RFC 9110 Brotli (br) & Gzip (gzip) response compression and request decompression
ginmw.PrecompressedFileServer(dir, opts...) Precompressed .br / .gz static & SPA file server with optional CSRF <meta> injection (PrecompressedFS for fs.FS)
ginmw.ETag(opts...) Version-gated ETag / 304 Not Modified middleware (WriteVersionedJSON for direct handlers)
ginmw.SecurityHeaders(name) OWASP defensive headers (SecurityHeadersWithOptions supports WithDisableHSTS / WithCacheControl)
ginmw.LoopbackGuard(g) Local-first DNS-rebinding, Same-Origin, and per-boot CSRF guard (NewLoopbackGuard)
ginmw.SSE(fn, opts...) First-class Server-Sent Events (text/event-stream) Gin handler adapter
ginmw.RequestID() Injects/propagates X-Request-ID
ginmw.Logger() Structured access log (method, path, status, latency)
ginmw.Telemetry(service) OpenTelemetry W3C trace context extraction and span lifecycle
ginmw.Idempotency(store) Two-phase HTTP request deduplication and response caching
ginmw.RequireTenant(opts...) Enforces tenant presence from context, claims, or headers with optional role bypass
ginmw.RespondSuccess(c, data) Unified JSend-compatible 200 JSON response envelope
ginmw.RespondError(c, status, code, msg) Unified JSend-compatible structured error response envelope
ginmw.REDMetrics() Thread-safe lock-free Rate, Errors, Duration metrics middleware
ginmw.MetricsEndpoint() Prometheus text/JSON /metrics exposition handler

📊 Verified Statement Coverage Status

Coverage across all 41 packages in go-libs is measured using Go's official statement-level coverage tool (go test -short -coverprofile=coverage.out ./...):

Overall Repository Statement Coverage: 100.0% (Zero data races across -race) Core Middleware Gate (ginmw): 100.0% Quality Standard: Strict per-package floor >= 85.0% enforced by ./scripts/check_coverage.sh

Package Purpose Statement Coverage
apperror Canonical structured application error codes and helpers 100.0%
async Panic-safe goroutines and bounded concurrency orchestration 100.0%
bodylimit HTTP middleware to cap request body sizes 100.0%
cache Generic singleflight stampede-protected multi-policy cache with prefix/tag invalidation and FetchStatus 100.0%
circuitbreaker Outbound resilience 3-state machine (Consecutive & Failure Ratio algorithms) 100.0%
clock Deterministic mockable time abstraction with RealClock and advanceable FakeClock 100.0%
compress SSE-safe Brotli (br) & Gzip (gzip) HTTP compression and precompressed .br/.gz SPA file server 100.0%
cryptoutil Secure password hashing (golang.org/x/crypto/bcrypt) and CSPRNG password generation (crypto/rand) 100.0%
db Database Pool & Querier 100.0%
env Zero-dependency typed environment variable parsers 100.0%
etag RFC 9110 ETag / 304 Not Modified and version-gated JSON middleware with client auto-bust 100.0%
fsm Declarative in-memory finite state machine with O(1) state transitions 100.0%
ginmw Unified Gin HTTP middleware chain & helper 100.0%
health Parallel dependency health check and Kubernetes probe handler 100.0%
httpclient Resilient composed HTTP client (RateLimit -> CircuitBreaker -> Retry -> Timeout -> Transport) 100.0%
httpmw Zero-Gin, zero-pgx, zero-OTel stdlib net/http middleware suite 100.0%
httputil Standardized JSON response and error handlers 100.0%
idempotency Two-phase HTTP request deduplication 100.0%
jwks Thread-safe cached ECDSA P-256 JWKS public key resolver 100.0%
logger Request-context aware structured logging with slog, sampling, and sensitive data redaction 100.0%
loopbackguard Local-first loopback address, DNS-rebinding Host, Same-Origin, and constant-time CSRF guard 100.0%
maputil Generic type-safe map operations 100.0%
metrics Framework-agnostic Counter, Gauge, Histogram interfaces N/A (Pure Interfaces)
pagination Offset-based request query parser and generic slice pagination 100.0%
ratelimit IP rate limiters (TokenBucket, SlidingWindow) with CIDR proxy parsing 100.0%
rbac Role-Based Access Control logic engine 100.0%
rbaccontext Context-based permission lookup helpers 100.0%
recovery Panic-to-JSON-500 middleware with structured logging 100.0%
requestid Correlation ID generator and context propagator 100.0%
retry Context-aware backoff and retry execution algorithms 100.0%
securityheaders OWASP secure header injector middleware (WithDisableHSTS, WithCacheControl) 100.0%
shutdown Graceful concurrent teardown manager 100.0%
sliceutil Generic slice algorithms (Reduce, GroupBy, Chunk, Unique, Flatten, First) 100.0%
sqlite Driver-agnostic embedded SQLite WAL helper (BEGIN IMMEDIATE, user_version, VACUUM INTO) 100.0%
sse First-class Server-Sent Events (text/event-stream) streaming helper with heartbeats & Last-Event-ID 100.0%
stringutil Sensitive info masking and text helpers 100.0%
telemetry OpenTelemetry distributed tracing wrapper 100.0%
timeutil Parametric time arithmetic, RFC parsing, business days, and timezone utilities 100.0%
uuidutil Centralized RFC 4122 UUID operations and validation 100.0%
validation Declarative validation error formatter 100.0%
workerpool Bounded panic-safe concurrent worker pool with metrics & options 100.0%
Total Statement Coverage Cumulative across all packages 100.0%

Note: The standalone reference microservice (examples/microservice) achieves 87.4% integration statement coverage.


🔭 Local Observability Sandbox (Prometheus + Grafana)

Boot the entire microservice along with a live Prometheus scraper and pre-provisioned Grafana Golden Signals dashboard in one command:

docker compose -f deploy/docker-compose.observability.yml up --build
  • Microservice API: http://localhost:8080 (/metrics, /health, /api/v1/items)
  • Prometheus Scraper: http://localhost:9090
  • Grafana Dashboard: http://localhost:3000 (auto-authenticated, view pre-configured Microservice Golden Signals & Resilience dashboard)

Looking for full enterprise cluster-wide observability?
Check out our companion platform repository: cloud-native-observability featuring the complete LGTM stack (Loki, Grafana, Tempo, Prometheus) + OpenTelemetry with ArgoCD GitOps and Google SRE SLO alerting!


🤖 AI Agent Skills & Multi-Model Context Routing

go-libs includes vendor-neutral Agent Skills (SKILL.md) and a root AGENTS.md router for any LLM coding agent (Antigravity, Gemini CLI, Claude Code, OpenAI Codex, Cursor, Windsurf):

Skill Path Covered Packages
go-libs (Umbrella) skills/go-libs/SKILL.md Full 41-package catalog router, architectural invariants, and truth gates
go-libs-resilience skills/go-libs-resilience/SKILL.md retry, circuitbreaker, ratelimit, workerpool, cache, async, shutdown, fsm, clock, metrics
go-libs-http-gin skills/go-libs-http-gin/SKILL.md ginmw, httpmw, compress, etag, loopbackguard, sse, httpclient, httputil, pagination, idempotency, health, requestid, recovery, securityheaders, bodylimit, validation
go-libs-data-security skills/go-libs-data-security/SKILL.md db, sqlite, rbac, rbaccontext, jwks, cryptoutil, telemetry, logger
go-libs-foundation skills/go-libs-foundation/SKILL.md apperror, env, sliceutil, maputil, stringutil, timeutil, uuidutil

Machine-readable LLM context is also published at llms.txt (and served live at https://abeta-dev.github.io/go-libs/llms.txt).


🌐 Abeta Go Ecosystem

go-libs serves as the foundational operational layer across the 4-repository Abeta Go Ecosystem:

Repository Architectural Role Live Documentation Portal API Reference (pkg.go.dev)
github.com/abeta-dev/go-libs (v0.6.0) Foundational zero-business-logic Go primitives: HTTP/Gin & stdlib httpmw middleware, SSE, ETag, loopback CSRF guard, resilience, concurrency, PostgreSQL & embedded SQLite WAL, RBAC, and OpenTelemetry abeta-dev.github.io/go-libs pkg.go.dev/github.com/abeta-dev/go-libs
github.com/abeta-dev/go-fintech-india (v0.5.0) Zero-dependency Indian FinTech & statutory compliance engine (17 domain files: exact int64 paise Money math, deterministic CalculateGST intra/inter-state CGST+SGST/IGST tax-split, statutory CalculateTDS section calculator with Section 206AA enforcement, GSTIN Mod-36, PAN, Aadhaar Verhoeff D5, <100ns offline IFSC/MICR, NPCI UPI URIs, Razorpay/Cashfree/PhonePe webhooks, Indian FY/Advance Tax, MCA Schedule III aging) abeta-dev.github.io/go-fintech-india pkg.go.dev/github.com/abeta-dev/go-fintech-india
github.com/abeta-dev/go-app-kit (v0.7.0) 7 enterprise application workflow engines (outbox, pdf, notifications, audit, export with Brotli/Gzip streaming CSV, zero-leak object storage with presigned URLs, and lease-fenced periodic job scheduler) abeta-dev.github.io/go-app-kit pkg.go.dev/github.com/abeta-dev/go-app-kit
github.com/abeta-dev/cloud-native-observability (v0.4.0) Production LGTM observability stack (Loki, Grafana, Tempo, Prometheus, OTel), Terraform IaC, ArgoCD GitOps, and Google SRE SLO alerting abeta-dev.github.io/cloud-native-observability github.com/abeta-dev/cloud-native-observability

Contributing & Development

# Run all core quality checks (linting, tests with -race, coverage gates)
make all

# Run linters across all packages
make lint

# Run all unit tests with data race detection (fast, scale tests excluded)
make test-race

# Run comprehensive statement coverage gates (global >=90%, pkg >=85%, ginmw 100%)
make coverage

# Run benchmarks and regression analysis against baseline
make bench

# Run fuzz testing suite (10s per target)
make fuzz

# Run dedicated scale and 1000-connection load tests
make test-scale

# Run 10-iteration stress testing under race detector
make stress

Please see CONTRIBUTING.md for contribution guidelines, SECURITY.md for security reporting, and CODE_OF_CONDUCT.md for our code of conduct.

📦 Repository Provenance & Release Record

go-libs is available from the Go module proxy at the latest verified published version, v0.6.0. The current origin/main checkout is a separate baseline history; see Release Baseline before selecting a release or publishing a reconciliation. For the complete version-by-version delivery record and historical commit errata, see CHANGELOG.md. Full semantic versioning contracts and package stability tiers are detailed in docs/VERSIONING.md.


License

MIT License. Copyright (c) 2026 Abeta.

Directories

Path Synopsis
Package apperror defines canonical application-level error codes and a structured Error type for use across microservices.
Package apperror defines canonical application-level error codes and a structured Error type for use across microservices.
Package async provides panic-safe concurrency primitives, asynchronous goroutine runners, and bounded parallel task executors with context cancellation.
Package async provides panic-safe concurrency primitives, asynchronous goroutine runners, and bounded parallel task executors with context cancellation.
Package bodylimit provides an HTTP middleware that enforces a maximum request body size.
Package bodylimit provides an HTTP middleware that enforces a maximum request body size.
Package cache provides a thread-safe, singleflight-protected in-memory cache with TTL.
Package cache provides a thread-safe, singleflight-protected in-memory cache with TTL.
Package circuitbreaker provides an outbound failure state machine for microservice resilience.
Package circuitbreaker provides an outbound failure state machine for microservice resilience.
Package clock provides an abstract interface for time-based operations, enabling deterministic, sleep-free testing of time-dependent components.
Package clock provides an abstract interface for time-based operations, enabling deterministic, sleep-free testing of time-dependent components.
Package compress provides production-hardened HTTP response compression (Brotli "br" and Gzip "gzip") with RFC 9110 Accept-Encoding q-value negotiation, pooled writers, threshold buffering, and bounded request body decompression with zip-bomb protection.
Package compress provides production-hardened HTTP response compression (Brotli "br" and Gzip "gzip") with RFC 9110 Accept-Encoding q-value negotiation, pooled writers, threshold buffering, and bounded request body decompression with zip-bomb protection.
Package cryptoutil provides domain-agnostic cryptographic helpers.
Package cryptoutil provides domain-agnostic cryptographic helpers.
Package db manages PostgreSQL pgxpool connections and transaction contexts.
Package db manages PostgreSQL pgxpool connections and transaction contexts.
Package env provides zero-dependency typed environment variable retrieval with sensible fallbacks and strict Must* panic assertions for application bootstrap.
Package env provides zero-dependency typed environment variable retrieval with sensible fallbacks and strict Must* panic assertions for application bootstrap.
Package etag provides RFC 9110 ETag / If-None-Match (304 Not Modified) and version-gated HTTP middleware with volatile JSON key stripping and client app version auto-bust support.
Package etag provides RFC 9110 ETag / If-None-Match (304 Not Modified) and version-gated HTTP middleware with volatile JSON key stripping and client app version auto-bust support.
Package fsm provides a lightweight, declarative, in-memory Finite State Machine for validating state transitions across domain lifecycles.
Package fsm provides a lightweight, declarative, in-memory Finite State Machine for validating state transitions across domain lifecycles.
Package ginmw provides HTTP body size limiting middleware.
Package ginmw provides HTTP body size limiting middleware.
Package health provides zero-dependency HTTP health check handlers decoupling Kubernetes liveness (/healthz, /livez) from dependency readiness (/readyz).
Package health provides zero-dependency HTTP health check handlers decoupling Kubernetes liveness (/healthz, /livez) from dependency readiness (/readyz).
Package httpclient provides an enterprise-grade, composed resilient HTTP client and http.RoundTripper middleware stack for Go microservices.
Package httpclient provides an enterprise-grade, composed resilient HTTP client and http.RoundTripper middleware stack for Go microservices.
Package httpmw provides a unified, lightweight standard-library net/http middleware suite with full parity to ginmw (RequestID, LimitBody, Compress, PrecompressedFileServer, ETag, SecurityHeaders, LoopbackGuard, CORS, Recovery, Logger, REDMetrics, MetricsEndpoint, RateLimit, RBAC permissions, RequireTenant, and SSE) while pulling zero Gin, pgx, or OpenTelemetry dependencies — ideal for stdlib net/http BFFs and desktop binaries.
Package httpmw provides a unified, lightweight standard-library net/http middleware suite with full parity to ginmw (RequestID, LimitBody, Compress, PrecompressedFileServer, ETag, SecurityHeaders, LoopbackGuard, CORS, Recovery, Logger, REDMetrics, MetricsEndpoint, RateLimit, RBAC permissions, RequireTenant, and SSE) while pulling zero Gin, pgx, or OpenTelemetry dependencies — ideal for stdlib net/http BFFs and desktop binaries.
Package httputil provides standardized JSON API response helpers (OK, Created, NoContent, Error) and automatic translation from domain error types into client-safe HTTP error envelopes.
Package httputil provides standardized JSON API response helpers (OK, Created, NoContent, Error) and automatic translation from domain error types into client-safe HTTP error envelopes.
Package idempotency provides two-phase atomic idempotency locking and response caching for HTTP mutating operations via the Idempotency-Key header, preventing duplicate side effects.
Package idempotency provides two-phase atomic idempotency locking and response caching for HTTP mutating operations via the Idempotency-Key header, preventing duplicate side effects.
Package jwks provides an in-memory cached JSON Web Key Set (JWKS) resolver for cryptographic public keys, with automatic TTL refresh and resilient fallback.
Package jwks provides an in-memory cached JSON Web Key Set (JWKS) resolver for cryptographic public keys, with automatic TTL refresh and resilient fallback.
Package logger provides context-aware structured JSON logging wrappers around the standard library log/slog package, propagating request IDs across service operations.
Package logger provides context-aware structured JSON logging wrappers around the standard library log/slog package, propagating request IDs across service operations.
Package loopbackguard provides local-first loopback address validation, DNS-rebinding Host allowlisting, Sec-Fetch-Site / Origin Same-Origin checks, and constant-time per-boot ephemeral CSRF token verification for localhost BFFs and desktop Go services.
Package loopbackguard provides local-first loopback address validation, DNS-rebinding Host allowlisting, Sec-Fetch-Site / Origin Same-Origin checks, and constant-time per-boot ephemeral CSRF token verification for localhost BFFs and desktop Go services.
Package maputil provides generic, zero-dependency helper functions for Go maps including Merge and Filter transformations.
Package maputil provides generic, zero-dependency helper functions for Go maps including Merge and Filter transformations.
Package metrics defines framework-agnostic instrumentation interfaces (Counter, Gauge, Histogram) with zero-allocation no-op implementations, enabling pluggable metrics exporters without coupling core packages to specific monitoring backends.
Package metrics defines framework-agnostic instrumentation interfaces (Counter, Gauge, Histogram) with zero-allocation no-op implementations, enabling pluggable metrics exporters without coupling core packages to specific monitoring backends.
Package pagination provides reusable helpers for offset-based pagination, clamping limit/page inputs to safe thresholds and computing SQL offsets and page totals.
Package pagination provides reusable helpers for offset-based pagination, clamping limit/page inputs to safe thresholds and computing SQL offsets and page totals.
Package ratelimit provides in-memory IP-based rate limiting using TokenBucket and SlidingWindow algorithms, featuring background eviction to prevent memory leaks.
Package ratelimit provides in-memory IP-based rate limiting using TokenBucket and SlidingWindow algorithms, featuring background eviction to prevent memory leaks.
Package rbac provides a domain-agnostic Role-Based Access Control (RBAC) engine supporting multi-segment wildcard pattern matching (e.g.
Package rbac provides a domain-agnostic Role-Based Access Control (RBAC) engine supporting multi-segment wildcard pattern matching (e.g.
Package rbaccontext attaches and verifies RBAC permissions within standard context.Context, enabling fine-grained handler permission checks (Can, CanAny, CanAll).
Package rbaccontext attaches and verifies RBAC permissions within standard context.Context, enabling fine-grained handler permission checks (Can, CanAny, CanAll).
Package recovery provides panic-trapping HTTP middleware with structured stack trace logging to slog and standardized client-safe JSON error responses via httputil.
Package recovery provides panic-trapping HTTP middleware with structured stack trace logging to slog and standardized client-safe JSON error responses via httputil.
Package requestid provides HTTP middleware that injects or propagates canonical X-Request-ID correlation identifiers across request contexts and response headers.
Package requestid provides HTTP middleware that injects or propagates canonical X-Request-ID correlation identifiers across request contexts and response headers.
Package retry provides context-aware retry execution with configurable backoff strategies (Constant, Linear, Exponential, ExponentialJitter) and error predicates.
Package retry provides context-aware retry execution with configurable backoff strategies (Constant, Linear, Exponential, ExponentialJitter) and error predicates.
Package securityheaders provides HTTP middleware setting OWASP-recommended defensive headers (HSTS, CSP, X-Frame-Options, X-Content-Type-Options) and stripping server tokens.
Package securityheaders provides HTTP middleware setting OWASP-recommended defensive headers (HSTS, CSP, X-Frame-Options, X-Content-Type-Options) and stripping server tokens.
Package shutdown provides coordinated graceful teardown management for microservices, intercepting OS termination signals and executing registered cleanup hooks concurrently within a strict timeout budget.
Package shutdown provides coordinated graceful teardown management for microservices, intercepting OS termination signals and executing registered cleanup hooks concurrently within a strict timeout budget.
Package sliceutil provides generic, zero-dependency functional slice transformations including Reduce, GroupBy, Chunk, Unique, Flatten, and First.
Package sliceutil provides generic, zero-dependency functional slice transformations including Reduce, GroupBy, Chunk, Unique, Flatten, and First.
Package sqlite provides a zero-dependency, driver-agnostic embedded SQLite WAL helper over database/sql with busy_timeout tuning, BEGIN IMMEDIATE write-serialized transactions, PRAGMA user_version schema migrations, WAL checkpointing, and atomic VACUUM INTO backups for desktop and edge Go services.
Package sqlite provides a zero-dependency, driver-agnostic embedded SQLite WAL helper over database/sql with busy_timeout tuning, BEGIN IMMEDIATE write-serialized transactions, PRAGMA user_version schema migrations, WAL checkpointing, and atomic VACUUM INTO backups for desktop and edge Go services.
Package sse provides a first-class Server-Sent Events (text/event-stream) helper for AI token streaming, live background sync progress, and real-time SDUI delta updates with flushing, heartbeat keepalives, Last-Event-ID resumption, and clean context cancellation.
Package sse provides a first-class Server-Sent Events (text/event-stream) helper for AI token streaming, live background sync progress, and real-time SDUI delta updates with flushing, heartbeat keepalives, Last-Event-ID resumption, and clean context cancellation.
Package stringutil provides domain-agnostic string utilities including sensitive PII masking (MaskEmail, MaskPhone) and cryptographically secure random string generation.
Package stringutil provides domain-agnostic string utilities including sensitive PII masking (MaskEmail, MaskPhone) and cryptographically secure random string generation.
Package telemetry initializes OpenTelemetry tracing providers and propagators, providing process-global setup (InitProvider) and instance-scoped providers (NewTracerProvider) without global mutation, plus span creation helpers (StartSpan).
Package telemetry initializes OpenTelemetry tracing providers and propagators, providing process-global setup (InitProvider) and instance-scoped providers (NewTracerProvider) without global mutation, plus span creation helpers (StartSpan).
Package timeutil provides domain-agnostic time helpers including UTC normalization, timezone conversions, and business day calculations.
Package timeutil provides domain-agnostic time helpers including UTC normalization, timezone conversions, and business day calculations.
Package uuidutil provides domain-agnostic UUID generation, parsing, and validation helpers.
Package uuidutil provides domain-agnostic UUID generation, parsing, and validation helpers.
Package validation provides helpers to transform and format go-playground/validator error structures into client-safe, uniform field-error JSON representations.
Package validation provides helpers to transform and format go-playground/validator error structures into client-safe, uniform field-error JSON representations.
Package workerpool provides a bounded, panic-safe worker pool for concurrent background task execution, preventing unbounded goroutine growth under high-load spikes.
Package workerpool provides a bounded, panic-safe worker pool for concurrent background task execution, preventing unbounded goroutine growth under high-load spikes.

Jump to

Keyboard shortcuts

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