common-library-golang

module
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0

README

PHCP: common-library-golang

English | 简体中文

Go Reference LICENSE CI codecov

common-library-golang

Common-library-golang is a collection of functional components used within the PHCP ecosystem, providing numerous components for microservice development, it provides some out-of-the-box functions, such as environment, log, database, etc. To make it more widely available, it is now open-sourced under the Apache license.

Requirements

  • Go 1.25+

Installation

go get github.com/phcp-tech/common-library-golang

Build and Test

go mod tidy
go vet ./...
go build ./...
Short mode test — fast CI verification

Some tests start a real TCP listener (e.g. httpserver integration tests). Pass -short to skip them and keep the test run lightweight:

go test ./... -short
Full test run — including integration tests
go test ./...
Run test with coverage
# All packages
go test ./... -cover -timeout 60s

Packages

Group Package Import path Description
Basic env .../common-library-golang/env TOML config + environment variable loader
Basic log .../common-library-golang/log Structured JSON logger with file rotation and ringbuf
Basic health .../common-library-golang/health Composable health-check aggregator for /health endpoints
Basic version .../common-library-golang/version Application version and build metadata for /version endpoints
Basic shutdown .../common-library-golang/shutdown Block until OS signal or programmatic trigger, then continue for cleanup
Basic ringbuf .../common-library-golang/ringbuf Lock-free ring buffers (SPSC and MPSC)
Basic maps .../common-library-golang/maps Thread-safe generic concurrent maps with pluggable replacement strategies
Basic cache .../common-library-golang/cache In-process key-value cache with TTL, backed by Otter
Basic cgroup .../common-library-golang/cgroup Read CPU and memory resource limits from cgroup v2 (Linux only; returns 0 on other platforms)
Basic metrics .../common-library-golang/metrics Runtime and system metrics snapshot (CPU, memory, goroutines, cgroup limits, uptime)
Basic file .../common-library-golang/file Upload policy checks (content types, size limit, file name), safe file download, binary file detection
Basic encrypt .../common-library-golang/encrypt PBKDF2-HMAC-SHA256 password hashing
Basic email .../common-library-golang/email SMTP email sending (go-mail) and email address check
Bootstrap bootstrap .../common-library-golang/bootstrap Sequential Init + LIFO Close orchestrator; 1st Add() = env, 2nd Add() = log (convention)
Bootstrap env/component .../common-library-golang/env/component IComponent adapter for the env package
Bootstrap log/component .../common-library-golang/log/component IComponent adapter for the log package
Bootstrap auth/component .../common-library-golang/auth/component IComponent adapter for the auth (casbin) package
Bootstrap token/component .../common-library-golang/token/component IComponent adapter for the token (JWT) package; fails Init if jwt.issuer or jwt.access.secretcode is unset/placeholder, or if jwt.refresh.secretcode is explicitly declared but left at its placeholder
Bootstrap gin/component .../common-library-golang/gin/component IComponent adapter for the gin engine
Bootstrap redis/component .../common-library-golang/redis/component IComponent adapter for the redis package
Bootstrap storage/component .../common-library-golang/storage/component IComponent adapter for the storage package
Bootstrap email/component .../common-library-golang/email/component IComponent adapter for the email package; fails Init on a missing or invalid [email] setting
Bootstrap dbgorm/clickhouse/component .../common-library-golang/dbgorm/clickhouse/component IComponent adapter for the GORM ClickHouse connection (pings on Init)
Bootstrap dbgorm/mysql/component .../common-library-golang/dbgorm/mysql/component IComponent adapter for the GORM MySQL connection (pings on Init)
Bootstrap dbgorm/postgres/component .../common-library-golang/dbgorm/postgres/component IComponent adapter for the GORM PostgreSQL connection (pings on Init)
Bootstrap dbgorm/sqlite/component .../common-library-golang/dbgorm/sqlite/component IComponent adapter for the GORM SQLite connection
Bootstrap dbsqlc/mysql/component .../common-library-golang/dbsqlc/mysql/component IComponent adapter for the MySQL connection (sql.Open, lazy)
Bootstrap dbsqlc/postgres/component .../common-library-golang/dbsqlc/postgres/component IComponent adapter for the PostgreSQL pool
Bootstrap dbsqlc/sqlite/component .../common-library-golang/dbsqlc/sqlite/component IComponent adapter for the SQLite connection
Bootstrap dbsqlx/clickhouse/component .../common-library-golang/dbsqlx/clickhouse/component IComponent adapter for the sqlx ClickHouse connection (pings on Init)
Bootstrap dbsqlx/clickhouse-native/component .../common-library-golang/dbsqlx/clickhouse-native/component IComponent adapter for the native-driver ClickHouse connection (lazy open)
Bootstrap dbsqlx/mysql/component .../common-library-golang/dbsqlx/mysql/component IComponent adapter for the sqlx MySQL connection (pings on Init)
Bootstrap dbsqlx/postgres/component .../common-library-golang/dbsqlx/postgres/component IComponent adapter for the sqlx PostgreSQL connection (pings on Init)
Bootstrap dbsqlx/sqlite/component .../common-library-golang/dbsqlx/sqlite/component IComponent adapter for the sqlx SQLite connection
Bootstrap httpserver/component .../common-library-golang/httpserver/component IComponent adapter for the HTTP server; ComponentWithRunner for custom runner injection
Bootstrap httpserver/componentwithlambda .../common-library-golang/httpserver/componentwithlambda IComponent adapter with AWS Lambda support; selects runner via app.runmode
Database redis .../common-library-golang/redis Redis client (standalone and cluster) with connection pool and key scan utilities
Database dbgorm/clickhouse .../common-library-golang/dbgorm/clickhouse ClickHouse via GORM — eager ping on Open, shared process-wide *gorm.DB
Database dbgorm/mysql .../common-library-golang/dbgorm/mysql MySQL via GORM — eager ping on Open, shared process-wide *gorm.DB
Database dbgorm/postgres .../common-library-golang/dbgorm/postgres PostgreSQL via GORM — eager ping on Open, shared process-wide *gorm.DB
Database dbgorm/sqlite .../common-library-golang/dbgorm/sqlite SQLite via GORM — embedded, no network, file auto-created on Open
Database dbgorm/sqlite/vfs .../common-library-golang/dbgorm/sqlite/vfs SQLite via GORM over embedded FS — binary-embedded read-only databases
Database dbsqlc/mysql .../common-library-golang/dbsqlc/mysql MySQL connection via standard database/sql and go-sql-driver
Database dbsqlc/postgres .../common-library-golang/dbsqlc/postgres PostgreSQL connection pool via pgx/v5
Database dbsqlc/sqlite .../common-library-golang/dbsqlc/sqlite SQLite connection via pure-Go modernc driver
Database dbsqlc/sqlite/vfs .../common-library-golang/dbsqlc/sqlite/vfs SQLite over embedded FS via VFS (binary-embedded databases)
Database dbsqlx/clickhouse .../common-library-golang/dbsqlx/clickhouse ClickHouse via sqlx (clickhouse-go/v2 database/sql driver) — eager ping on Open, shared process-wide *sqlx.DB
Database dbsqlx/clickhouse-native .../common-library-golang/dbsqlx/clickhouse-native ClickHouse native TCP client via clickhouse-go/v2 — returns driver.Conn, not *sqlx.DB
Database dbsqlx/mysql .../common-library-golang/dbsqlx/mysql MySQL via sqlx — eager ping on Open, shared process-wide *sqlx.DB
Database dbsqlx/postgres .../common-library-golang/dbsqlx/postgres PostgreSQL via sqlx (pgx stdlib driver) — eager ping + SHOW search_path on Open
Database dbsqlx/sqlite .../common-library-golang/dbsqlx/sqlite SQLite via sqlx — embedded, no network, file auto-created on Open
Database dbsqlx/sqlite/vfs .../common-library-golang/dbsqlx/sqlite/vfs SQLite via sqlx over embedded FS — binary-embedded read-only databases
Database storage .../common-library-golang/storage S3-compatible object storage client (Cloudflare R2, AWS S3, MinIO, Aliyun OSS)
Network network .../common-library-golang/network Network utilities helpers
Network auth .../common-library-golang/auth Casbin RBAC authorisation middleware for Gin
Network token .../common-library-golang/token JWT access/refresh token creation, parsing, and Gin middleware
Network gin .../common-library-golang/gin Gin engine factory with slog request logging and CORS
Network gin/pprof .../common-library-golang/gin/pprof Optional pprof profiling endpoints for Gin (explicit opt-in)
Network gin/download .../common-library-golang/gin/download Gin file download route over file.ServeAttachment (root-confined, no directory listing)
Network cdn .../common-library-golang/cdn CDN cache purge by URL (Cloudflare, or none)
Network httpclient .../common-library-golang/httpclient Resty-based HTTP client with retry, JWT auth, and JSON helpers
Network httpclient/retryable .../common-library-golang/httpclient/retryable hashicorp/go-retryablehttp wrapper returning standard *http.Client
Network httpserver .../common-library-golang/httpserver Production HTTP/HTTPS server with timeouts and graceful shutdown
Network httpserver/lambda .../common-library-golang/httpserver/lambda AWS Lambda adapter implementing httpserver.IRunner (explicit opt-in)

env — Configuration Management

Loads a TOML config file and merges OS environment variables on top. Built on koanf. Implements the singleton pattern: only the first InitEnv call takes effect.

import "github.com/phcp-tech/common-library-golang/env"

// Call once at startup before any Env() usage.
if err := env.InitEnv("config.toml"); err != nil {
    log.Fatal(err)
}

host := env.Env().String("server.host")
port := env.Env().Int("server.port")

For single-binary deployments the config file can be embedded at compile time:

//go:embed config.toml
var configFS embed.FS

env.InitEnv("config.toml", &configFS)

Placeholders. In app.toml, a setting whose real value is set at deployment has the value env.Placeholder ("TOBE_REPLACED"). After the environment variables are merged, InitEnv fails while any setting, or any list element, still has this value. The error names every such key with the environment variable that sets it (app.env.prefix + key in upper case, . → _):

config keys still set to TOBE_REPLACED, set them with environment variables:
db.password (TM_DB_PASSWORD), email.host (TM_EMAIL_HOST)

Use the placeholder only for required settings. For an optional setting, or one used only by some configurations (for example the keys of a storage type that is not selected), write "" and check it where it is used:

// Fails with all missing keys at once, each with its environment variable.
if err := env.RequireStrings("email.host", "email.port"); err != nil {
    return err
}
name := env.VarName("email.host") // "TM_EMAIL_HOST"

RequireStrings rejects empty values and the placeholder. Format checks (a port number, an email address) stay in the component that reads the setting.

See full examples.


log — Structured Logging

Structured JSON logging via log/slog with UTC timestamps. File writes are fully asynchronous: the caller returns immediately after pushing the formatted entry into an internal RingMPSC buffer; a dedicated consumer goroutine performs the actual I/O. This makes the package suitable for high-throughput, latency-sensitive scenarios where blocking on disk I/O is unacceptable.

InitLog must be called once at application startup before any log function. Omit the argument for stdout output at INFO level; pass a Config to customise.

import "github.com/phcp-tech/common-library-golang/log"

// Stdout mode at default INFO level.
log.InitLog()
log.Info("application started")
log.Infof("listening on port %d", 8080)
log.InfoWith("request", "method", "GET", "path", "/api/v1", "status", 200)

// Stdout mode with custom level.
log.InitLog(&log.Config{Level: "debug"})

// File mode: set FilePath to enable rotating file logging.
log.InitLog(&log.Config{
    Level:      "info",
    FilePath:   "/var/log/app.log",
    MaxSizeMB:  100,
    MaxBackups: 7,
    MaxAgeDays: 30,
    Compress:   true,
})
defer log.Close() // flush async buffer and close file on shutdown

Available log functions: Debug / Info / Warn / Error and their f (format) and With (structured key-value) variants. Log level can be changed at runtime with SetLevel.

See full examples.


health — Composable Health Checks

Interface-based health-check aggregator for /health HTTP endpoints. Each infrastructure package supplies a Checker that owns its own component name and reachability status; Check runs all checkers and returns their combined results.

import (
    "github.com/phcp-tech/common-library-golang/health"
    db    "github.com/phcp-tech/common-library-golang/dbsqlc/postgres"
    cache "github.com/phcp-tech/common-library-golang/redis"
)

// Compose any number of checkers in a /health handler.
router.GET("/health", func(c *gin.Context) {
    c.JSON(http.StatusOK, health.Check(
        c.Request.Context(),
        db.HealthChecker(),
        cache.HealthChecker(),
    ))
})
// JSON response: [{"name":"postgres","status":1},{"name":"redis","status":1}]
Constant Value Meaning
health.StatusHealthy 1 Component is reachable
health.StatusUnhealthy 0 Component is unreachable or not initialised

See full examples.


version — Application Version Metadata

Returns application version and build metadata for /version HTTP endpoints. Reads app.name, app.version, and app.env.value from env.Env(), and populates GoVersion / BuildInfo from the embedded Go build info. Requires env.InitEnv to be called at application startup.

import "github.com/phcp-tech/common-library-golang/version"

router.GET("/version", func(c *gin.Context) {
    c.JSON(http.StatusOK, version.Get())
})
// JSON response:
// {
//   "name": "my-service",
//   "version": "1.2.3",
//   "environment": "production",
//   "goVersion": "go1.27.1",
//   "buildInfo": "v1.2.3"
// }

See full examples.


shutdown — Graceful Shutdown

Two primitives for application shutdown coordination:

  • Wait blocks the calling goroutine until an OS signal (SIGINT, SIGTERM, SIGHUP, SIGQUIT) or Trigger is called. After it returns, the caller performs cleanup and exits.
  • Trigger unblocks Wait programmatically from any goroutine — useful for a /shutdown HTTP endpoint or a metrics failure handler. Safe to call multiple times.
import "github.com/phcp-tech/common-library-golang/shutdown"

// In main: start services, then block until shutdown.
shutdown.Wait()

// Cleanup runs here (or via defer before Wait).
runner.Shutdown(ctx)
// From a /shutdown HTTP endpoint or metrics failure handler.
shutdown.Trigger()

Note: Trigger has no effect when the process is forcibly terminated by the OS (e.g. IDE stop button on Windows calls TerminateProcess — no signal is delivered).

See full examples.


ringbuf — Ring Buffers

High-performance fixed-capacity ring buffers for producer-consumer pipelines.

Type Use case Thread safety
RingSPSC Single producer, single consumer Lock-free (atomic only)
RingMPSC Multiple producers, single consumer Mutex on producer side

Both types support an optional ProcessFunc that starts a consumer goroutine automatically, or manual Pop / TryPop for caller-managed consumption. Push blocks when the buffer is full (backpressure); TryPush returns false immediately.

import "github.com/phcp-tech/common-library-golang/ringbuf"

// SPSC — single producer, automatic consumer goroutine
rb := ringbuf.NewRingSPSC(ringbuf.RingSPSCConfig[string]{
    Capacity:    1024,
    ProcessFunc: func(s string) { fmt.Println(s) },
})
rb.Push("hello")
rb.Close() // drain and wait for consumer to finish

// MPSC — multiple producers, automatic consumer goroutine
rb := ringbuf.NewRingMPSC(ringbuf.RingMPSCConfig[[]byte]{
    Capacity:    4096,
    ProcessFunc: func(b []byte) { os.Stdout.Write(b) },
})

See full examples.

Performance

Benchmarks run with go test -bench=. -benchtime=3s -benchmem. All operations produce zero heap allocations.

Test environment

CPU 11th Gen Intel® Core™ i7-11850H @ 2.50 GHz (8 cores / 16 threads)
RAM 32 GB
OS Windows 11 Enterprise
Go 1.26.2 windows/amd64

Results

Benchmark ns/op Throughput Allocs
SPSC Push (1P-1C, blocking) 76.65 ~13.0 M ops/s 0
SPSC TryPush (1P-1C, non-blocking) 87.91 ~11.4 M ops/s 0
SPSC ProducerConsumer (end-to-end with ProcessFunc) 83.72 ~11.9 M ops/s 0
SPSC Push string (realistic log payload) 91.06 ~11.0 M ops/s 0
MPSC Push (1 producer) 151.1 ~6.6 M ops/s 0
MPSC Push (4 producers concurrent) 192.2 ~5.2 M ops/s 0
MPSC Push (8 producers concurrent) 200.7 ~5.0 M ops/s 0
MPSC ProducerConsumer (4P end-to-end) 197.5 ~5.1 M ops/s 0
Go channel (buffered 4096, reference) 126.3 ~7.9 M ops/s 0

Key observations

  • SPSC is ~1.6× faster than a buffered Go channel for the same single-producer / single-consumer pattern.
  • MPSC trades some throughput for multi-producer safety via a mutex; with 8 concurrent producers it remains above 5 M ops/s.
  • Throughput scales gracefully under producer contention: going from 1 to 8 producers adds only ~33% latency per item.
  • Both types maintain zero allocations per operation, making them suitable as the async I/O backbone for the log package.

maps — Thread-Safe Concurrent Maps

Thread-safe generic concurrent maps backed by orcaman/concurrent-map with pluggable replacement strategies.

Two implementations are provided:

Type Key Value Strategy
CMap string (fixed) int64 (fixed) Greater-value wins (built-in)
CMapGen[K, V] any comparable any Unconfigured: always overwrites. Configurable via SetDefaultCompare or SetDefaultStrategy

Built-in strategy types: NumericGreaterStrategy[V cmp.Ordered] (real numeric/ordered comparison — requires V to satisfy cmp.Ordered), AlwaysReplaceStrategy, TimestampStrategy. Until SetDefaultCompare/SetDefaultStrategy is called, CMapGen.Replace behaves like ReplaceAlways — V is unconstrained, so there is no strategy that can be wired up automatically for an arbitrary type.

import "github.com/phcp-tech/common-library-golang/maps"

// Generic map — configure a default compare function.
m := maps.NewCMapGen[string, int64]()
m.SetDefaultCompare(func(old, new int64) bool { return new > old })

m.Set("EURUSD", 10500)
m.Replace("EURUSD", 10600)       // stored: 10600 > 10500
m.ReplaceAlways("EURUSD", 9000)  // always stored
m.ReplaceIfNotExists("GBPUSD", 12800) // stored only if key absent

// Read-modify-write via callback (not atomic for concurrent writes to the same key — see below).
m.UpsertWithCallback("USDJPY", 15100, func(exists bool, old, new int64) int64 {
    if !exists || new > old { return new }
    return old
})

// Fixed string→int64 map (no configuration needed).
cm := maps.NewCMap()
cm.Set("tick", 10000)
cm.Replace("tick", 10050) // stored: 10050 > 10000

Replace/ReplaceWithCompare/ReplaceWithStrategy/UpsertWithCallback all read the old value and write the new one as two separately-locked operations, not one atomic operation — safe under concurrent writes to different keys, and safe (no corruption/panic) even under concurrent writes to the same key, but the value left standing after a race is whichever Set executed last, not necessarily the one the compare/strategy/callback logic says should have won. For a true atomic read-modify-write on a single key, call the underlying cmap.ConcurrentMap.Upsert directly — it holds the shard lock for the whole callback.

See full examples.

Performance

Benchmarks run with go test -bench=. -benchtime=3s -benchmem.

Test environment — same machine as ringbuf benchmarks: Intel® Core™ i7-11850H @ 2.50 GHz · 8 cores / 16 threads · 32 GB RAM · Go 1.26.2 / Windows 11

CMap (fixed string→int64, built-in greater-value strategy)

Benchmark ns/op Throughput B/op Allocs
Set 27.51 ~36.3 M ops/s 0 0
Get 15.70 ~63.7 M ops/s 0 0
Replace 43.99 ~22.7 M ops/s 0 0
Set (parallel, 16 goroutines) 70.82 ~14.1 M ops/s 0 0
Replace (parallel, 16 goroutines) 151.5 ~6.6 M ops/s 0 0

CMapGen (generic [K comparable, V any])

Benchmark ns/op Throughput B/op Allocs Note
Set 31.75 ~31.5 M ops/s 0 0
Get 18.20 ~55.0 M ops/s 0 0
Replace (NumericGreaterStrategy, explicitly configured) 47.63 ~21.0 M ops/s 0 0
ReplaceWithCompare 46.32 ~21.6 M ops/s 0 0
ReplaceAlways 30.05 ~33.3 M ops/s 0 0
UpsertWithCallback 49.29 ~20.3 M ops/s 0 0
Set (parallel, 16 goroutines) 71.17 ~14.1 M ops/s 0 0
Replace (parallel, 16 goroutines) 167.9 ~6.0 M ops/s 0 0
Mixed read/write (parallel) 25.96 ~38.5 M ops/s 0 0

sync.Map (stdlib reference)

Benchmark ns/op Throughput B/op Allocs
Store 60.90 ~16.4 M ops/s 56 1
Load 10.48 ~95.4 M ops/s 0 0
Store (parallel, 16 goroutines) 110.0 ~9.1 M ops/s 56 1

Key observations

  • CMap.Set is ~2.2× faster than sync.Map.Store and allocates nothing.
  • CMapGen.Replace is zero-allocation whether it's driven by an explicitly configured NumericGreaterStrategy/SetDefaultStrategy, SetDefaultCompare, or left unconfigured (in which case it behaves like ReplaceAlways, also zero-allocation) — there is no default path that falls back to string formatting.
  • CMapGen.ReplaceAlways is the fastest write path (~33.3 M ops/s) when no conditional logic is needed.
  • Under 16-goroutine parallel write contention CMap.Replace degrades to ~6.6 M ops/s due to single-key hot-spot; spreading writes across many keys restores throughput.

cache — In-Process Cache (Otter)

An in-process key-value cache with TTL support, defined behind the ICache interface so callers never depend on the concrete implementation. The only implementation today, OtterCache, is backed by maypok86/otter (a W-TinyLFU admission cache). There is no Default()/Component() for this package — just the plain constructor, same as httpclient/maps/ringbuf.

import "github.com/phcp-tech/common-library-golang/cache"

c := cache.NewOtterCache() // capacity 10,000 entries, default TTL 1 hour

// Config is optional — customize capacity and/or the default TTL:
c2 := cache.NewOtterCache(cache.Config{MaxSize: 500, DefaultTTL: 10 * time.Minute})

// DefaultTTL: cache.NoExpiry builds a cache that never expires entries —
// this is a whole-cache setting: on a NoExpiry cache every Set's expire
// argument is ignored (see below), there's no per-key "except this one".
permanent := cache.NewOtterCache(cache.Config{DefaultTTL: cache.NoExpiry})

_ = c.Set("session-token", "abc123", 5*time.Minute) // custom per-entry TTL
_ = c.Set("counter", 1, 0)                          // 0 (or negative) uses the cache's default TTL

val, ok := c.Get("session-token")

_ = c.Update("counter", 2) // replaces the value, leaves the TTL untouched
_ = c.Delete("session-token")

c.Size()   // number of entries currently held (estimated)
c.Keys()   // []interface{} snapshot of all keys
c.Values() // []interface{} snapshot of all values
_ = c.Clear()

expire <= 0 in Set does not mean "never expires" — it means "use the cache's default TTL" (1 hour unless Config.DefaultTTL overrides it). This is the opposite of what a zero-value TTL means in some other cache APIs, so double-check this if you're porting code from one of those. For a cache where entries genuinely never expire, construct it with Config.DefaultTTL: NoExpiry instead — don't try to simulate "forever" with an arbitrarily large expire duration on a per-Set basis.

See full examples.

Performance

Benchmarks run with go test -bench=. -benchtime=2s -benchmem.

Test environment: Intel® Core™ i7-11850H @ 2.50 GHz · 8 cores / 16 threads · 32 GB RAM · Go 1.26.2 / Windows 11

Benchmark ns/op Throughput B/op Allocs
Set 389.4 ~2.6 M ops/s 120 4
Set (custom TTL) 1175 ~0.85 M ops/s 118 4
Get (hit) 638.8 ~1.6 M ops/s 16 2
Get (miss) 176.6 ~5.7 M ops/s 24 2
Mixed (80% read / 20% write) 239.7 ~4.2 M ops/s 34 2
Mixed, parallel (16 goroutines) 85.43 ~11.7 M ops/s 33 2
Delete 110.0 ~9.1 M ops/s 15 1
Set (1 KB value) 448.7 ~2.2 M ops/s (2282 MB/s) 123 4
Get (1 KB value, hit) 181.8 ~5.5 M ops/s (5633 MB/s) 16 1
Get (Zipf hot-key distribution) 619.7 ~1.6 M ops/s 10 1

Key observations

  • A cache miss is ~3.6× faster than a hit (176.6 ns vs 638.8 ns) — a hit runs Otter's afterRead bookkeeping (records the hit, updates the TinyLFU admission/eviction policy state), while a miss only records a counter and returns; this is inherent to the admission-cache design, not a bug.
  • Set with a custom TTL (1175 ns) costs ~3× a plain Set (389.4 ns) — a custom TTL is a second call (SetExpiresAfter after Set), not a single write.
  • 16-goroutine parallel mixed read/write throughput (~11.7 M ops/s) is higher, not lower, than the single-goroutine Get/Set numbers — unlike maps.CMap's single-key hot-spot case above, this benchmark spreads keys across a 10,000-key space, so contention stays low and the numbers reflect genuine parallel scaling rather than a hot-spot artifact.

cgroup — Linux Resource Limits

Reads CPU and memory resource limits from the cgroup v2 unified hierarchy (/sys/fs/cgroup), and falls back to cgroup v1 when v2 is not available or the v2 file can not be read. Intended for containerised workloads (Kubernetes, Docker) where the process runs inside a cgroup with configured CPU and memory constraints.

On non-Linux platforms (macOS, Windows) all functions return zero values and a nil error — no cgroup filesystem is available and no error is raised.

Function cgroup v2 file (v1 fallback) Returns
CPULimitMilli() cpu.max (cpu.cfs_quota_us, cpu.cfs_period_us) CPU limit in millicores; 0 = unlimited
CPURequestMilli() cpu.weight (cpu.shares) CPU request in millicores; 0 = no request (BestEffort)
MemoryLimitBytes() memory.max (memory.limit_in_bytes) Memory limit in bytes; 0 = unlimited
MemoryRequestBytes() memory.low (memory.soft_limit_in_bytes) Memory soft limit in bytes; see the note below
CPUThrottleStat() cpu.stat Cumulative CPU throttle counters (CPUThrottle: Periods, Throttled, ThrottledNs); take the difference of two reads

Note on MemoryRequestBytes(): Kubernetes does not write the memory request into the cgroup (memory.min and memory.low are 0 unless MemoryQoS is on), so 0 does not mean "no request is set" — it means the request can not be read. Do not use this value to decide whether a request exists. For this reason metrics.GetMetrics() no longer outputs memoryRequest.

import "github.com/phcp-tech/common-library-golang/cgroup"

// Read CPU limit and cap GOMAXPROCS accordingly.
if milli, err := cgroup.CPULimitMilli(); err == nil && milli > 0 {
    cpus := milli / 1000
    if cpus < 1 {
        cpus = 1
    }
    runtime.GOMAXPROCS(cpus)
}

// Size an in-process cache as 25 % of the container memory limit.
if limitBytes, err := cgroup.MemoryLimitBytes(); err == nil && limitBytes > 0 {
    cacheBytes := limitBytes / 4
    cache.SetMaxSize(cacheBytes)
}

See full examples.


metrics — Runtime Metrics Snapshot

Collects a one-shot snapshot of key runtime and system metrics as a flat []NameValue slice, suitable for a /metrics or /health HTTP endpoint.

Each call samples CPU usage over one second via gopsutil, so it is intended for periodic polling (e.g. every 10–30 s), not hot-path use.

Metric name Description
cpuPercent Process CPU usage (%) across all cores, sampled over 1 s
memorySize Resident set size (RSS) in MiB
threads OS thread count
goroutines Live goroutine count
gomaxprocs runtime.GOMAXPROCS(0)
numCPU runtime.NumCPU()
cpuThrottledPercent Percent of CFS periods in the latest 5 s in which the cgroup was throttled by its CPU limit (0 = not throttled; always 0 without a limit or on non-Linux)
cpuThrottledMillis Time in milliseconds the cgroup was throttled in the latest 5 s (0 without a limit or on non-Linux)
cpuRequest cgroup CPU request in millicores (0 if not set or non-Linux)
cpuLimit cgroup CPU limit in millicores (0 if unlimited or non-Linux)
memoryLimit cgroup memory limit in bytes (0 if unlimited or non-Linux)
age Process uptime formatted as Xd Xh Xm Xs
import "github.com/phcp-tech/common-library-golang/metrics"

// Periodic metrics poll — call from a background goroutine.
snapshot := metrics.GetMetrics()

// Look up a specific entry.
for _, nv := range snapshot {
    if nv.Name == "goroutines" {
        slog.Info("runtime", "goroutines", nv.Value)
    }
}

// Serialize to JSON for a /health endpoint.
b, _ := json.Marshal(snapshot)
w.Write(b)

See full examples.


bootstrap — Application Lifecycle Orchestrator

bootstrap orchestrates the sequential initialization and LIFO cleanup of application components at startup.

Component registration order convention

The first Add() call MUST register the env component. The second Add() call MUST register the log component. All subsequent calls (Add, AddParallel, PreReady) are free.

This convention exists because:

  • every component's Init() reads configuration via env.Env(), so env must initialize first;
  • Go's slog package has a usable default instance from program start (writes to stderr), so Init() failures at any stage — including before log.Init() — are captured by slog;
  • env.Close() is a no-op, so LIFO naturally makes log.Close() the last meaningful shutdown operation.
import (
    "github.com/phcp-tech/common-library-golang/bootstrap"
    envComp  "github.com/phcp-tech/common-library-golang/env/component"
    logComp  "github.com/phcp-tech/common-library-golang/log/component"
    dbComp   "github.com/phcp-tech/common-library-golang/dbsqlc/postgres/component"
    ginComp  "github.com/phcp-tech/common-library-golang/gin/component"
    httpComp "github.com/phcp-tech/common-library-golang/httpserver/component"
)

func main() {
    var router *gin.Engine
    bootstrap.New().
        Add(envComp.Component("config/app.toml", &configFS)). // 1st — MUST be env
        Add(logComp.Component()).                              // 2nd — MUST be log
        AddParallel(dbComp.Component()).
        PreReady(migrate).
        PreReady(initServices).
        Add(ginComp.Component(func(r *gin.Engine) { router = r; mount(r) })).
        Add(httpComp.Component(func() http.Handler { return router })).
        PostReady(func() { slog.Info("server ready") }).
        Run()
}
API
Method Signature Description
New () *App Creates an empty orchestrator
Add (cs ...IComponent) *App Sequential phase: Init in registration order, Close in LIFO order. 1st call = env, 2nd call = log
AddParallel (cs ...IComponent) *App Concurrent phase: all Init calls run in parallel; all must succeed before the next step starts
PreReady (fn func() error) *App Inline setup function in the startup sequence; non-nil error aborts startup; no Close, not tracked in LIFO
PostReady (fn func()) *App Notification hook invoked after all steps succeed; multiple calls accumulate in registration order
Run () Executes all steps, waits for SIGINT/SIGTERM, then closes in LIFO order
IComponent interface
type IComponent interface {
    Name() string   // displayed in log messages
    Init() error    // non-nil error aborts startup and exits with code 1
    Close()         // called during shutdown in LIFO order; must never panic
}

Use bootstrap.Func to wrap a function pair as an IComponent when Close logic exists but no struct is needed:

bootstrap.Func("worker", startWorker, stopWorker)
Startup and shutdown sequence
New()
  → Add(env).Init   ← slog (default handler writes to stderr before log.Init)
  → Add(log).Init   ← slog
  → steps (in registration order)
        ├── stepPhase    → Init, added to closeStack
        └── stepPreReady → fn(), not added to closeStack
  → PostReady callbacks
  → wait for signal
        ↓
  ← single closeAll (LIFO)
        custom components (reverse order)
        → log.Close   (last meaningful close — env.Close is a no-op)
        → env.Close   (no-op)
PreReady

PreReady registers a function into the startup sequence, sharing the same ordered list as Add/AddParallel. A non-nil error aborts startup identically to a failed component Init(). PreReady steps have no Close and do not participate in LIFO shutdown.

.AddParallel(dbComp.Component()).
PreReady(migrate).        // runs after DB is ready
PreReady(initServices).   // runs after migrate
Add(ginComp.Component(mount)).
bootstrap.Func(..., nil) PreReady(fn)
Appears in step list ✓ as stepPhase ✓ as stepPreReady
Participates in LIFO closeStack ✓ (Close is a no-op) ✗
Semantic "a component without Close" "one-shot code in the startup sequence"
PostReady

PostReady can be called multiple times. Each call appends a callback; all run in registration order after every step succeeds and before the process blocks on an OS signal. Suitable for actions that do not affect request-handling correctness:

.PostReady(func() { slog.Info("server ready", "addr", ":8080") }).
PostReady(func() { discovery.Register(serviceID) })

Code placed after Run() in main, or in a defer before Run(), executes after the full shutdown sequence completes and is suitable for post-shutdown teardown.

See full examples.


Bootstrap Component Packages

Each base package ships a companion component/ sub-package that adapts it to the IComponent interface. Component packages read all configuration from env.Env() inside Init() — never in the constructor — so they are safe to construct before bootstrap.New() is called.

Component package Env keys read on Init
env/component (none — reads the config file itself)
log/component log.level, log.file.path, log.file.max.size.mb, log.file.max.backups, log.file.max.age.days, log.file.compress
auth/component (model and policy passed as constructor arguments)
token/component jwt.issuer (required — must be identical across every service; Init fails if empty or "TOBE_REPLACED"), jwt.access.secretcode (required — Init fails if empty or "TOBE_REPLACED"), jwt.refresh.secretcode (optional if unset; Init fails if explicitly left at "TOBE_REPLACED")
gin/component app.env.value, cors.allow.origins.prod, cors.allow.origins.dev
redis/component redis.clusters, redis.database, redis.password
storage/component storage.endpoint, storage.region, storage.access.key.id, storage.secret.access.key, storage.bucket (required — Init fails if empty or "TOBE_REPLACED"), storage.path.style, storage.archive.bucket, storage.public.base.url (optional)
email/component email.host, email.port, email.username, email.password, email.from.address (required — Init fails if empty or invalid), email.from.name (optional)
dbgorm/clickhouse/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbgorm/mysql/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbgorm/postgres/component db.host, db.port, db.name, db.schema, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbgorm/sqlite/component db.sqlite.path
dbsqlc/mysql/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbsqlc/postgres/component db.host, db.port, db.name, db.schema, db.username, db.password, db.pool.*
dbsqlc/sqlite/component db.sqlite.path
dbsqlx/clickhouse/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbsqlx/clickhouse-native/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime
dbsqlx/mysql/component db.host, db.port, db.name, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbsqlx/postgres/component db.host, db.port, db.name, db.schema, db.username, db.password, db.max.open.conns, db.max.idle.conns, db.conn.max.lifetime, db.conn.max.idletime
dbsqlx/sqlite/component db.sqlite.path
httpserver/component http.server.port, http.server.host (optional; e.g. 127.0.0.1 for local-only access, empty binds all interfaces)
httpserver/componentwithlambda app.runmode ("aws_lambda" → Lambda runner), http.server.port, http.server.host (optional; other modes)

redis — Redis Client

Thread-safe Redis client supporting both standalone and cluster modes, backed by go-redis/v9. Connection pool settings (PoolSize, MinIdleConns) are configurable via Config with sensible defaults (100 / 5). The caller reads values from env.Env() at the composition root — this package has no dependency on env.

import "github.com/phcp-tech/common-library-golang/redis"

// Standalone mode (single address).
cli := redis.NewRedisClient(&redis.Config{
    Clusters: []string{env.Env().String("redis.addr")},
    Password: env.Env().String("redis.password"),
    DB:       env.Env().Int("redis.db"),
})
defer cli.Close()

// Cluster mode — more than one address enables cluster automatically.
cli := redis.NewRedisClient(&redis.Config{
    Clusters:     env.Env().Strings("redis.clusters"),
    PoolSize:     200,
    MinIdleConns: 10,
})

// Basic operations.
cli.Set(ctx, "key", "value", 5*time.Minute)
val, err := cli.Get(ctx, "key")
cli.Del(ctx, "key")
cli.Unlink(ctx, "key") // async deletion — preferred for large keys

// Remove all keys starting with a prefix.
cli.CleanCache(ctx, "user:42:")

// Count matching keys across all nodes.
n, err := cli.GetKeysCount(ctx, "session:*")

Implements the singleton pattern via InitDefault / Default.

Health check

HealthChecker() returns a health.Checker that pings the default client. Reports StatusUnhealthy when no client has been initialised or when the ping fails.

import (
    "github.com/phcp-tech/common-library-golang/health"
    "github.com/phcp-tech/common-library-golang/redis"
)

results := health.Check(c.Request.Context(), redis.HealthChecker())
// → []health.Result{{Name: "redis", Status: health.StatusHealthy}}

See full examples.


storage — S3-compatible Object Storage

One generic S3 client (aws-sdk-go-v2) for Cloudflare R2, AWS S3, MinIO and Aliyun OSS. Switching platforms only changes Config; no field carries a platform name. Request checksums are sent only when an operation requires them, because not every S3-compatible store accepts the SDK's default checksums.

import "github.com/phcp-tech/common-library-golang/storage"

s, err := storage.New(storage.Config{
    Endpoint:        "https://{accountId}.r2.cloudflarestorage.com",
    Region:          "auto",
    AccessKeyID:     id,
    SecretAccessKey: secret,
    Bucket:          "zhishi-content-dev",
    ArchiveBucket:   "zhishi-archive-dev", // optional
})
if err != nil {
    return err
}
if err := s.Check(ctx); err != nil { // lists at most one object per bucket
    return err
}
out, err := s.Client().PutObject(ctx, &s3.PutObjectInput{ /* ... */ })

storage/component reads the storage.* keys, fails Init when a required key is empty (the error names the environment variable to set; env.InitEnv already rejects "TOBE_REPLACED"), and stores the result in storage.Default(). It does not contact the store; call Check for that.

PresignPut(ctx, key, PutOptions) returns a URL that uploads one object to the main bucket with a plain HTTP PUT, e.g. straight from a browser, and the headers that PUT must send (Host and Content-Length excluded; the browser sets them). The URL expires after PutOptions.Expires, 5 minutes by default. See file for checking the upload first.

file — Upload Policy Checks

Checks one upload against a Policy: the allowed content types, the size limit and the optional file name. The package has no storage and no database — where the file goes, who may upload it, the object key and the upload record stay in the application. Pair it with storage.PresignPut for browser uploads straight to the store.

import (
    "github.com/phcp-tech/common-library-golang/file"
    "github.com/phcp-tech/common-library-golang/storage"
)

images := file.Policy{Types: file.ImageTypes(), MaxSize: 5_000_000}
docs := file.Policy{Types: file.DocumentTypes(), MaxSize: 20_000_000, Disposition: "attachment"}

ext, err := images.Check(req.ContentType, req.Size, req.Filename) // errors wrap file.ErrInvalid
if err != nil {
    return err // e.g. HTTP 400
}
key := "images/2026/11/" + uuid.NewString() + "." + ext // never build a key from the file name
p, err := store.PresignPut(ctx, key, storage.PutOptions{
    ContentType:        req.ContentType,
    Size:               req.Size,
    CacheControl:       "public, max-age=31536000, immutable",
    ContentDisposition: images.Disposition,
    Metadata:           map[string]string{"uploader-id": "7"},
})
// the browser PUTs to p.URL and must send every header in p.Headers
  • ImageTypes(): png, jpeg, webp, gif. SVG is left out because it can carry scripts.
  • DocumentTypes(): pdf, docx, xlsx, pptx. Legacy binary formats and macro-enabled formats are left out.
  • Both return a new map on every call, so one caller cannot change another's policy.
  • ValidFilename accepts an empty name, or at most 255 characters without control characters, / or \.
  • The content of the file is not checked; a client can declare a wrong content type.

ServeAttachment sends a file under a root directory as a download, with net/http only (no Gin dependency):

// in a Gin handler
err := file.ServeAttachment(c.Writer, c.Request, dataDir, c.Query("file"))
if errors.Is(err, file.ErrNotFound) {
    c.JSON(http.StatusNotFound, gin.H{"message": "file not found"})
} else if err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
}
  • The name cannot leave the root: .., absolute paths and symbolic links pointing outside are refused (os.Root). Directories and missing files are ErrNotFound; nothing is listed.
  • Content-Disposition: attachment carries the file name, encoded for non-ASCII characters. A Content-Type set by the caller is kept. Range and If-Modified-Since work.
  • On an error nothing has been written, so the caller answers in its own format.

IsBinary(io.ReadSeeker) reports whether a file looks binary from its first 512 bytes (a NUL byte, or invalid UTF-8 with more than 5% non-text bytes), and leaves the reader at its start. A multi-byte character cut at the 512-byte boundary does not make UTF-8 text look binary.

email — Email Sending

Sends email over SMTP with go-mail, and checks address syntax (IsEmail). email.Sender is the interface to depend on; replace it with a fake in tests.

import (
    "github.com/phcp-tech/common-library-golang/email"
    emailComp "github.com/phcp-tech/common-library-golang/email/component"
)

// Register after env and log; Init reads [email] and fails on a bad config.
bootstrap.New().
    Add(envComp.Component("config/app.toml", &configFS)).
    Add(logComp.Component()).
    Add(emailComp.Component()).
    // ...
    Run()

// No From: the default sender (email.from.address / email.from.name) is used.
err := email.Default().Send(&email.Message{
    To:      []string{"user@example.com"},
    Subject: "Verification code",
    Body:    "<p>Your code is 123456.</p>",
})

// Without bootstrap, or for a second server:
s, err := email.NewSMTPSender(email.Config{Host: "smtp.example.com", Port: 587,
    Username: "user", Password: "secret", FromAddress: "noreply@example.com"})

ok := email.IsEmail("user@example.com") // address syntax check
  • TLS by port. Port 465 uses implicit TLS. Any other port (587, 25) must offer STARTTLS; a server without it is an error, so the password is never sent unencrypted.
  • Auth is chosen from what the server offers: SCRAM, CRAM-MD5, PLAIN, LOGIN (PLAIN and LOGIN only over TLS).
  • Timeouts. 15 s to connect, 30 s for one Send. Each Send opens its own connection, so a sender is safe for concurrent use.
  • Message. Body is text/html unless ContentType is text/plain; the message is UTF-8, quoted-printable. Bcc is not written into the message. There is no User-Agent/X-Mailer header. Attachments are not supported. Every address is parsed before connecting.

email/component reads email.host, email.port, email.username, email.password, email.from.address (required) and email.from.name (optional). A missing value, a port that is not a number in 1–65535, or an invalid email.from.address fails Init.

See full examples.


cdn — CDN Cache Purge

Purges cached copies of URLs from a CDN, e.g. after an object in storage is changed or deleted. Callers use only the Purger interface; standard library only.

import "github.com/phcp-tech/common-library-golang/cdn"

p, err := cdn.New("cloudflare", zoneID, purgeToken, // or cdn.New("none", "", "")
    cdn.WithOrigins("https://example.com", "http://localhost:5173"))
if err != nil {
    return err
}
err = p.PurgeURLs(ctx, []string{
    "https://example.com/articles/hello",
    "https://content.example.com/articles/2026/11/hello/r1.md",
})
  • "cloudflare" calls POST /zones/{zoneID}/purge_cache with the URLs, 30 files per request; it tries every batch and returns all failures joined. The token needs only the Zone > Cache Purge > Purge permission.
  • WithOrigins (optional): the CDN keys a cached copy by the request Origin header too, and a purge by URL alone clears only the copy cached without an Origin. With origins, each URL is purged once without an Origin and once per origin, so one URL is 1 + len(origins) files of the 30. Pass the origins that read the URLs cross-origin with fetch (the CORS origins of the bucket), each as scheme://host[:port]; New rejects any other form.
  • "none" purges nothing: cached entries expire by their TTL. Use it for local runs without a token.
  • URLs must match the cached URLs exactly (scheme, host, path and query).
  • Purge by tag or by host name is not offered: they are plan features of some CDNs, with no common equivalent.
  • A purge is best effort. Log a failure and let the TTL clean up instead of failing the request that changed the data.

dbgorm/clickhouse — GORM ClickHouse

GORM-based ClickHouse adapter. GORM's driver pings the server during Open — InitDefault returns a non-nil error immediately when the database is unreachable, causing bootstrap to abort startup. The default instance is a process-wide *gorm.DB shared via dbgorm.Default() / dbgorm.SetDefault().

Note: PrepareStmt is automatically disabled for ClickHouse because the driver maps Prepare() to batch INSERT; it must be off for regular SELECT queries. This is handled transparently inside dbgorm.Open.

import (
    dbgorm     "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/dbgorm/clickhouse"
)

err := clickhouse.InitDefault(&clickhouse.Config{
    Host:     "localhost",
    Port:     "9440",   // native TCP+TLS; use 8123/8443 for HTTP
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err)
}

db := dbgorm.Default() // *gorm.DB, ready for GORM operations
Health check

Use dbgorm.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbgorm.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbgorm/mysql — GORM MySQL

GORM-based MySQL adapter. Unlike dbsqlc/mysql, GORM's driver pings the server during Open — InitDefault returns a non-nil error immediately when the database is unreachable, which causes bootstrap to abort startup. The default instance is a process-wide *gorm.DB shared via dbgorm.Default() / dbgorm.SetDefault() (no sync.Once — can be replaced at runtime).

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/dbgorm/mysql"
)

// Open and store as the process-wide default.
err := mysql.InitDefault(&mysql.Config{
    Host:     "localhost",
    Port:     "3306",
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err) // server was unreachable — GORM pinged on Open
}

db := dbgorm.Default() // *gorm.DB, ready for GORM operations

For cases that require multiple databases, use NewMySQL directly and store the returned *gorm.DB in explicit fields rather than the shared default.

Health check

Use dbgorm.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbgorm.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbgorm/postgres — GORM PostgreSQL

GORM-based PostgreSQL adapter. GORM's driver pings the server and runs SHOW search_path during Open — InitDefault returns a non-nil error immediately when the database is unreachable, causing bootstrap to abort startup. Supports an optional SearchPath for schema isolation. When Config.QueryExecMode is empty, the dialector does not override pgx's default (cache_statement in the currently used pgx version). The adapter never infers a mode from a port. Applications using PgBouncer, Supavisor, or another transaction-mode pooler must explicitly select exec to avoid prepared statement does not exist when physical backend connections change. exec retains PostgreSQL's extended protocol and parameter type encoding, including JSON/JSONB.

Constant Use and constraint
QueryExecModeExec Explicitly required for Supabase transaction pooler 6543 and other transaction poolers.
QueryExecModeCacheStatement Prepared-statement cache for stable session-pool or direct PostgreSQL connections after a production-like benchmark.
QueryExecModeCacheDescribe Caches parameter/result descriptions; requires the same stable backend and schema assumptions as cached statements.
QueryExecModeDescribeExec Gets a description for every query; uses two round trips and is unsuitable for transaction poolers that can switch the backend between them.
QueryExecModeSimpleProtocol Compatibility fallback for a proxy or server without extended-protocol support; []byte is encoded as bytea, so JSON/JSONB values require special care.

For Supabase 6543, applications must set:

QueryExecMode: postgres.QueryExecModeExec,

The default instance is a process-wide *gorm.DB shared via dbgorm.Default() / dbgorm.SetDefault().

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/dbgorm/postgres"
)

err := postgres.InitDefault(&postgres.Config{
    Host:       "localhost",
    Port:       "5432",
    Database:   "mydb",
    Username:   "user",
    Password:   "pass",
    SearchPath: "myschema", // optional
})
if err != nil {
    log.Fatal(err) // server was unreachable
}

db := dbgorm.Default() // *gorm.DB, ready for GORM operations
Health check

Use dbgorm.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbgorm.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbgorm/sqlite — GORM SQLite

GORM-based SQLite adapter backed by glebarez/sqlite (pure Go, no CGO). SQLite is an embedded database — no network connection is involved. InitDefault opens (and auto-creates) the file; it fails only when the path is empty or the file cannot be created. MaxOpenConns is fixed at 1 to prevent database is locked errors under concurrent writes.

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    "github.com/phcp-tech/common-library-golang/dbgorm/sqlite"
)

// File-based database.
err := sqlite.InitDefault(&sqlite.Config{
    Path: "file:app.db?cache=shared",
})
if err != nil {
    log.Fatal(err)
}

db := dbgorm.Default() // *gorm.DB, ready for GORM operations

// In-memory database (tests, ephemeral data).
db, _ := sqlite.NewSQLite(&sqlite.Config{
    Path: "file::memory:?cache=shared",
})

No HealthChecker: SQLite is embedded — if it fails, the application is already broken. A health endpoint for an embedded database provides no operational value.

See full examples.


dbgorm/sqlite/vfs — GORM Embedded SQLite via VFS

Opens a SQLite database embedded inside the Go binary using modernc.org/sqlite/vfs and Go's embed.FS. The embedded file must reside at config/sqlite.db inside the provided embed.FS.

Import this sub-package only when distributing a SQLite database as part of the binary. For regular file-based databases use dbgorm/sqlite instead.

InitDefault uses sync.Once — the first call wins; subsequent calls are silently ignored.

import (
    dbgorm "github.com/phcp-tech/common-library-golang/dbgorm"
    sqlvfs "github.com/phcp-tech/common-library-golang/dbgorm/sqlite/vfs"
)

//go:embed config/sqlite.db
var sqliteFS embed.FS

// Open directly (no singleton).
db, err := sqlvfs.New(&sqliteFS)

// Or store as the process-wide default (sync.Once).
if err := sqlvfs.InitDefault(&sqliteFS); err != nil {
    log.Fatal(err)
}
db := dbgorm.Default() // *gorm.DB, ready for GORM operations

See full examples.


dbsqlc/mysql — MySQL Connection

Standard database/sql connection for use with sqlc (sql_package: "database/sql"), backed by go-sql-driver/mysql. Connection pool settings (MaxOpenConns, MaxIdleConns, ConnMaxLifetime, ConnMaxIdletime) are configurable via Config with sensible defaults. Implements the singleton pattern via InitDefault / Default.

Note: sql.Open is lazy — no connection is established during InitDefault. Init() always returns nil. Use an explicit PingContext in a PreReady step if an eager connectivity check is required at startup.

import "github.com/phcp-tech/common-library-golang/dbsqlc/mysql"

// Singleton mode: call once at startup.
err := mysql.InitDefault(&mysql.Config{
    Host:     "localhost",
    Port:     "3306",
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err)
}

db := mysql.Default() // *sql.DB, pass to sqlc Queries

For cases that require multiple connections, use NewMySQL directly instead of the singleton.

Health check

HealthChecker() returns a health.Checker that pings the default connection. Reports StatusUnhealthy when no connection has been initialised or when the ping fails.

import (
    "github.com/phcp-tech/common-library-golang/health"
    "github.com/phcp-tech/common-library-golang/dbsqlc/mysql"
)

results := health.Check(c.Request.Context(), mysql.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbsqlc/postgres — PostgreSQL Connection Pool

pgx/v5 connection pool for use with sqlc (sql_package: "pgx/v5"). Pool creation is lazy: NewPostgres returns immediately without establishing any connections, so no live server is required at startup. When Config.QueryExecMode is empty, NewPostgres preserves pgx's default DefaultQueryExecMode (cache_statement in the currently used pgx version). It never infers a mode from a port. Applications using Supabase 6543 must explicitly set QueryExecModeExec; use QueryExecModeCacheStatement or QueryExecModeCacheDescribe only with a stable session-pool or direct PostgreSQL connection, avoid QueryExecModeDescribeExec on transaction poolers, and use QueryExecModeSimpleProtocol only as a compatibility fallback because []byte values are encoded as bytea. Implements the singleton pattern via InitDefault / Default.

import "github.com/phcp-tech/common-library-golang/dbsqlc/postgres"

// Singleton mode: call once at startup.
err := postgres.InitDefault(&postgres.Config{
    Host:            "localhost",
    Port:            "5432",
    Database:        "mydb",
    Username:        "user",
    Password:        "pass",
    MaxOpenConns:    100,
    MaxIdleConns:    25,
    ConnMaxLifetime: 60, // minutes
    ConnMaxIdletime: 10, // minutes
    SearchPath:      "myschema", // optional
})
if err != nil {
    log.Fatal(err)
}

pool := postgres.Default() // *pgxpool.Pool, pass to sqlc Queries

For cases that require multiple pools, use NewPostgres directly instead of the singleton.

Health check

HealthChecker() returns a health.Checker that pings the default pool. Reports StatusUnhealthy when no pool has been initialised or when the ping fails.

import (
    "github.com/phcp-tech/common-library-golang/health"
    db "github.com/phcp-tech/common-library-golang/dbsqlc/postgres"
)

results := health.Check(c.Request.Context(), db.HealthChecker())
// → []health.Result{{Name: "postgres", Status: health.StatusHealthy}}

See full examples.


dbsqlc/sqlite — SQLite Connection

Pure-Go SQLite driver (modernc.org/sqlite, no CGO required). For use with sqlc (sql_package: "database/sql"). Implements the singleton pattern via InitDefault / Default.

import "github.com/phcp-tech/common-library-golang/dbsqlc/sqlite"

// In-memory database (tests and short-lived operations).
db, err := sqlite.NewSQLite(&sqlite.Config{Path: ":memory:"})

// File-based database with WAL mode and foreign key enforcement.
err := sqlite.InitDefault(&sqlite.Config{
    Path: "file:app.db?_journal_mode=WAL&_foreign_keys=on",
})
if err != nil {
    log.Fatal(err)
}

db := sqlite.Default() // *sql.DB, pass to sqlc Queries

SQLite allows only one writer at a time. NewSQLite calls SetMaxOpenConns(1) automatically to prevent database is locked errors when WAL mode is not in use.

No HealthChecker: SQLite is embedded — if it fails, the application is already broken. A health endpoint for an embedded database provides no operational value.

See full examples.


dbsqlc/sqlite/vfs — Embedded SQLite via VFS

Opens a SQLite database that is embedded inside the Go binary using modernc.org/sqlite/vfs and Go's embed.FS. The database file must reside at config/sqlite.db inside the embedded filesystem.

Import this sub-package only when the database is distributed as part of the binary. For regular file-based databases use dbsqlc/sqlite instead.

import sqlitevfs "github.com/phcp-tech/common-library-golang/dbsqlc/sqlite/vfs"

//go:embed config/sqlite.db
var sqliteFS embed.FS

// Singleton mode: call once at startup.
if err := sqlitevfs.InitDefault(&sqliteFS); err != nil {
    log.Fatal(err)
}

db := sqlitevfs.Default() // *sql.DB, pass to sqlc-generated Queries

For cases that require multiple VFS connections, use New directly instead of the singleton.

See full examples.


dbsqlx/clickhouse — sqlx ClickHouse

ClickHouse adapter built on github.com/vinovest/sqlx, via clickhouse-go/v2's database/sql driver (registers as "clickhouse") — the same driver mode used internally by gorm.io/driver/clickhouse. dbsqlx.Open pings the server eagerly — InitDefault returns a non-nil error immediately when the database is unreachable, which causes bootstrap to abort startup. The default instance is a process-wide *sqlx.DB shared via dbsqlx.Default() / dbsqlx.SetDefault().

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/dbsqlx/clickhouse"
)

err := clickhouse.InitDefault(&clickhouse.Config{
    Host:     "localhost",
    Port:     "9440", // native TCP+TLS
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err) // server was unreachable — Open pinged eagerly
}

db := dbsqlx.Default() // *sqlx.DB, ready for Get/Select/Exec
Health check

Use dbsqlx.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbsqlx.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbsqlx/clickhouse-native — ClickHouse Native Driver

Native TCP ClickHouse client backed by clickhouse-go/v2. Returns driver.Conn — not *sqlx.DB — so it does not integrate with dbsqlx.Open/Default/Exec/Transact from the parent dbsqlx package. Use this package for direct, high-performance native protocol access; use dbsqlx/clickhouse instead when you want the shared *sqlx.DB conveniences.

Lazy open: clickhousenative.NewClickHouse only configures the connection; the TCP dial happens on the first operation (Ping/Query/etc.). InitDefault therefore always returns nil. Use a PreReady step with conn.Ping(ctx) for an eager check.

import "github.com/phcp-tech/common-library-golang/dbsqlx/clickhouse-native"

// Singleton mode — call once at startup.
err := clickhousenative.InitDefault(&clickhousenative.Config{
    Host:     "localhost",
    Port:     "9440", // native TCP+TLS
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err)
}

conn := clickhousenative.Default() // driver.Conn, ready to use
Health check

HealthChecker() returns a health.Checker that calls conn.Ping(ctx) on the default client. Reports StatusUnhealthy when no client has been initialised or when the ping fails.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx/clickhouse-native"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), clickhousenative.HealthChecker())
// → []health.Result{{Name: "clickhouse-native", Status: health.StatusHealthy}}

See full examples.


dbsqlx/mysql — sqlx MySQL

MySQL adapter built on github.com/vinovest/sqlx (a database/sql extension with reflection-based struct scanning and Go generics), via the go-sql-driver/mysql driver. Unlike dbsqlc/mysql, dbsqlx.Open pings the server eagerly — InitDefault returns a non-nil error immediately when the database is unreachable, which causes bootstrap to abort startup. The default instance is a process-wide *sqlx.DB shared via dbsqlx.Default() / dbsqlx.SetDefault() (no sync.Once — can be replaced at runtime).

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/dbsqlx/mysql"
)

// Open and store as the process-wide default.
err := mysql.InitDefault(&mysql.Config{
    Host:     "localhost",
    Port:     "3306",
    Database: "mydb",
    Username: "user",
    Password: "pass",
})
if err != nil {
    log.Fatal(err) // server was unreachable — Open pinged eagerly
}

db := dbsqlx.Default() // *sqlx.DB, ready for Get/Select/Exec

For cases that require multiple databases, use NewMySQL directly and store the returned *sqlx.DB in explicit fields rather than the shared default.

Health check

Use dbsqlx.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbsqlx.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbsqlx/postgres — sqlx PostgreSQL

PostgreSQL adapter built on github.com/vinovest/sqlx, via the pgx/v5/stdlib driver (registers as "pgx" with database/sql). dbsqlx.Open pings the server and runs SHOW search_path eagerly — InitDefault returns a non-nil error immediately when the database is unreachable. Supports an optional SearchPath for schema isolation. Generated DSNs omit default_query_exec_mode when Config.QueryExecMode is empty, preserving pgx's default (cache_statement in the currently used pgx version). The adapter never infers a mode from a port. Applications using Supabase 6543 must explicitly set QueryExecModeExec; use QueryExecModeCacheStatement or QueryExecModeCacheDescribe only with a stable session-pool or direct PostgreSQL connection, avoid QueryExecModeDescribeExec on transaction poolers, and use QueryExecModeSimpleProtocol only as a compatibility fallback because []byte values are encoded as bytea. The default instance is a process-wide *sqlx.DB shared via dbsqlx.Default() / dbsqlx.SetDefault().

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/dbsqlx/postgres"
)

err := postgres.InitDefault(&postgres.Config{
    Host:       "localhost",
    Port:       "5432",
    Database:   "mydb",
    Username:   "user",
    Password:   "pass",
    SearchPath: "myschema", // optional
})
if err != nil {
    log.Fatal(err) // server was unreachable
}

db := dbsqlx.Default() // *sqlx.DB, ready for Get/Select/Exec
Health check

Use dbsqlx.HealthChecker() from the root package — the checker is dialect-agnostic and works with any driver initialised via InitDefault.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/health"
)

results := health.Check(c.Request.Context(), dbsqlx.HealthChecker())
// → []health.Result{{Name: "database", Status: health.StatusHealthy}}

See full examples.


dbsqlx/sqlite — sqlx SQLite

SQLite adapter built on github.com/vinovest/sqlx, via the pure-Go modernc.org/sqlite driver (no CGO). SQLite is an embedded database — no network connection is involved. InitDefault opens (and auto-creates) the file and its parent directory; it fails only when the path is empty or the file cannot be created. Every connection gets the standard PRAGMA settings (WAL, foreign keys, busy timeout, 32 MB cache). MaxOpenConns is fixed at 4 / MaxIdleConns at 2 — SQLite allows only one writer at a time, so a larger pool provides no benefit even under WAL.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    "github.com/phcp-tech/common-library-golang/dbsqlx/sqlite"
)

// File-based database.
err := sqlite.InitDefault(&sqlite.Config{
    Path: "file:app.db?cache=shared",
})
if err != nil {
    log.Fatal(err)
}

db := dbsqlx.Default() // *sqlx.DB, ready for Get/Select/Exec

// In-memory database (tests, ephemeral data).
db, _ = sqlite.NewSQLite(&sqlite.Config{
    Path: "file::memory:?cache=shared",
})

No HealthChecker: SQLite is embedded — if it fails, the application is already broken. A health endpoint for an embedded database provides no operational value.

See full examples.


dbsqlx/sqlite/vfs — sqlx Embedded SQLite via VFS

Opens a SQLite database embedded inside the Go binary using modernc.org/sqlite/vfs and Go's embed.FS. The embedded file must reside at config/sqlite.db inside the provided embed.FS.

Import this sub-package only when distributing a SQLite database as part of the binary. For regular file-based databases use dbsqlx/sqlite instead.

InitDefault uses sync.Once — the first call wins; subsequent calls are silently ignored.

import (
    "github.com/phcp-tech/common-library-golang/dbsqlx"
    sqlvfs "github.com/phcp-tech/common-library-golang/dbsqlx/sqlite/vfs"
)

//go:embed config/sqlite.db
var sqliteFS embed.FS

// Open directly (no singleton).
db, err := sqlvfs.New(&sqliteFS)

// Or store as the process-wide default (sync.Once).
if err := sqlvfs.InitDefault(&sqliteFS); err != nil {
    log.Fatal(err)
}
db = dbsqlx.Default() // *sqlx.DB, ready for Get/Select/Exec

See full examples.


network — Network Utilities

Helpers for request IP extraction, local interface inspection, and IPv4 ↔ uint32 conversion.

IP address helpers
import "github.com/phcp-tech/common-library-golang/network"

// Real client IP — inspects X-Forwarded-For → X-Real-IP → RemoteAddr.
// Returns the first address in X-Forwarded-For when multiple proxies are chained.
// "::1" is normalised to "127.0.0.1".
ip := network.GetRemoteIp(req)

// All non-loopback IPv4 addresses on the local machine.
addrs := network.GetLocalIpAddress()
IPv4 ↔ uint32 conversion

Two byte orders are supported:

Function Byte order Typical use
Ip2IntWithBigEndian Big-endian (network order) Standard TCP/IP, databases
Int2IpWithBigEndian Big-endian Same as above
Ip2IntWithLittleEndian Little-endian MT4 / MT5 trading platforms
Int2IpWithLittleEndian Little-endian Same as above
// Big-endian (network byte order): "1.2.3.4" → 0x01020304
n := network.Ip2IntWithBigEndian("1.2.3.4")   // → 16909060
ip := network.Int2IpWithBigEndian(0x01020304)  // → "1.2.3.4"

// Little-endian (MT4/MT5 format): "1.2.3.4" → 0x04030201
n := network.Ip2IntWithLittleEndian("1.2.3.4")   // → 67305985
ip := network.Int2IpWithLittleEndian(0x04030201)  // → "1.2.3.4"

// Both return 0 / "" for empty, invalid, or IPv6 input.
Address validation
// IsValidAddr checks if the string is a valid IP address (with or without port)
// or a resolvable hostname.
network.IsValidAddr("192.168.1.1:8080") // true
network.IsValidAddr("192.168.1.1")      // true
network.IsValidAddr("example.com:443")  // true (DNS lookup)
network.IsValidAddr("999.999.999.999")  // false

See full examples.


auth — Casbin RBAC Authorisation

Role-based access control (RBAC) Gin middleware backed by Casbin. Enforces policy using method-2 semantics: every role in the user's role list must pass the policy check — if any role is denied, the request is rejected with HTTP 403 Forbidden.

InitCasbin must be called once at application startup before Authorize is registered. Model and policy can be loaded from in-memory strings (fs=true) or from files on disk (fs=false).

import "github.com/phcp-tech/common-library-golang/auth"

// Load model and policy from in-memory strings (e.g. embedded at build time).
if err := auth.InitCasbin(true, modelString, policyString); err != nil {
    log.Fatal(err)
}

// Load model and policy from files.
if err := auth.InitCasbin(false, "model.conf", "policy.csv"); err != nil {
    log.Fatal(err)
}

// Register as a Gin middleware after token.Authenticate.
// It reads roles from the "userInfo" context key set by token.Authenticate.
r := gin.New()
r.Use(token.Authenticate())
r.Use(auth.Authorize())

See full examples.


token — JWT Authentication

HS256 JWT access and refresh token creation, parsing, and a Gin bearer-token middleware. Built on golang-jwt/jwt.

InitToken must be called once at application startup before any token function. The secrets and issuer are typically read from env.Env() after env.InitEnv(). Prefer wiring this in via token/component in a bootstrap chain — its Init() fails fast if jwt.access.secretcode is empty or left at a placeholder value, instead of silently signing/validating every token with a non-secret string.

import "github.com/phcp-tech/common-library-golang/token"

// Initialise once at startup (composition root), after env.InitEnv().
token.InitToken(
    env.Env().String("jwt.issuer"),             // e.g. "phcp"
    env.Env().String("jwt.access.secretcode"),  // access token signing key
    env.Env().String("jwt.refresh.secretcode"), // refresh token signing key
)

// Create a short-lived access token (valid for 1 hour).
tok, err := token.CreateToken(userId, username, orgId, productId, roles, time.Hour)

// Validate and parse an access token from an incoming request.
user, err := token.ParseToken(tok)
fmt.Println(user.Username, user.UserId, user.OrgId, user.ProductId, user.Roles)

// Create a long-lived refresh token (no roles embedded).
refresh, err := token.CreateRefreshToken(userId, username, orgId, productId, 24*time.Hour)

// Register as a Gin middleware; stores LoginUser in context under key "userInfo".
r := gin.New()
r.Use(token.Authenticate())

Authenticate aborts with HTTP 401 if the Authorization: Bearer <token> header is missing, malformed, or carries an invalid/expired token.

CreateToken/ParseToken/CreateRefreshToken/ParseRefreshToken all reject an uninitialised or placeholder secret — InitToken never being called (accessSecret/ refreshSecret left at their zero value ""), or being called with token.PlaceholderSecret ("TOBE_REPLACED", the scaffolding value shipped in this workspace's config/app.toml files) — with an error, rather than silently signing/validating every token with a well-known, non-secret string (HMAC accepts any key, including an empty or constant one, so this doesn't fail on its own). token.IsUsableSecret is the exported check behind this — token/component calls the same function to validate config at bootstrap Init() time, so the two layers of defense never disagree on what counts as "configured".

See full examples.


encrypt — Password Hashing

EncryptPassword(password, salt) hashes a password with PBKDF2-HMAC-SHA256 (4096 iterations, 32-byte key) and returns it as standard base64 (44 characters). It is a one-way hash: the password cannot be recovered from it.

import "github.com/phcp-tech/common-library-golang/encrypt"

// Hash a password with a per-user salt. Store the salt next to the hash.
hash := encrypt.EncryptPassword(password, salt)

// Check a login: hash the entered password with the stored salt and compare.
ok := encrypt.EncryptPassword(entered, salt) == hash

See full examples.


gin — Gin Engine Factory

Pre-configured Gin engine with structured slog-based request logging (slog-gin) and optional CORS support. Always runs in ReleaseMode.

InitGin is the single entry point. Pass a slice of allowed origins to enable CORS; entries containing * are treated as single-level wildcard patterns (e.g. https://*.example.com matches https://api.example.com but not https://a.b.example.com).

import libgin "github.com/phcp-tech/common-library-golang/gin"

// No CORS.
router := libgin.InitGin(nil)

// Exact origins and wildcard patterns can be mixed.
router := libgin.InitGin([]string{
    "https://app.example.com",   // exact
    "https://*.example.com",     // wildcard: root + any single subdomain
})

See full examples.


gin/pprof — Profiling Endpoints

Registers Go runtime pprof endpoints on a Gin engine via gin-contrib/pprof.

Import this sub-package only in services that require profiling. Importing it is an explicit opt-in — it does not affect services that only import gin.

Two route groups are mounted:

Path Purpose
/debug/pprof/* Standard Go pprof path for direct access
<path>/admin/pprof/* API-gateway-friendly alias
import (
    libgin   "github.com/phcp-tech/common-library-golang/gin"
    ginpprof "github.com/phcp-tech/common-library-golang/gin/pprof"
)

router := libgin.InitGin(nil)
ginpprof.Mount(router, "/api/v1") // mounts /debug/pprof/* and /api/v1/admin/pprof/*

See full examples.


gin/download — File Download Route

Gin handler and route for downloading files under one directory. The checks are in file.ServeAttachment: the name cannot leave the root (.., absolute paths, symbolic links pointing outside), and directories are not listed.

import (
    "github.com/phcp-tech/common-library-golang/gin/download"
    "github.com/phcp-tech/common-library-golang/token"
)

dir, err := download.ExeDir() // the executable's directory; also right for Windows services
if err != nil {
    return err
}
// GET /reqapi/v1/admin/files/download?file=./report.csv
download.Mount(router, "/reqapi/v1", dir, token.Authenticate())

// or call the handler from your own route, e.g. after setting a Content-Type
c.Header("Content-Type", "text/csv; charset=utf-8")
download.Handler(dir)(c)
  • The file query parameter must start with ./.
  • Errors are JSON {"code", "message"}: 400 without ./, 404 for a missing file, a directory or a name outside the root, 500 when the root cannot be opened.
  • Access-Control-Expose-Headers: Content-Disposition lets a browser client read the file name.
  • Mount panics without at least one handler (e.g. token.Authenticate()), so the route cannot become public by mistake.

httpclient — Resty HTTP Client

Feature-rich HTTP client built on go-resty/resty with pre-configured retry, JWT bearer-token support, and automatic JSON handling. Suitable for structured service-to-service calls.

RetryMax only retries transport-level failures by default (connection refused, timeout, DNS failure, ...) — this is resty's own default retry condition, which looks solely at the error returned by the round trip. A well-formed HTTP 500/503/429 response is not a Go error, so RetryMax alone never retries those. Set RetryOnServerErrors: true to also retry on 429 and 5xx responses.

import "github.com/phcp-tech/common-library-golang/httpclient"

// Default settings: Timeout=10s, RetryMax=3 (transport-level failures only).
cli := httpclient.NewHttpClient()

// Custom settings — zero-value fields fall back to defaults.
cli := httpclient.NewHttpClient(httpclient.Config{
    Timeout:             15 * time.Second,
    RetryMax:            5,
    InsecureSkipVerify:  true, // only for internal self-signed certs
    RetryOnServerErrors: true, // also retry on HTTP 429/5xx responses
})

resp, err := cli.Get(url, jwtToken, nil)
resp, err := cli.Post(url, jwtToken, body)
resp, err := cli.Put(url, jwtToken, body)
resp, err := cli.Delete(url, jwtToken, body)

// Access the underlying resty.Client for advanced use.
restyClient := cli.Client()

See full examples.


httpclient/retryable — Retryable HTTP Client

Wraps hashicorp/go-retryablehttp and exposes it as a standard *http.Client with configurable retry and timeout. Use this sub-package when existing code already uses net/http directly and you need to add retry behaviour without switching to resty.

Unlike httpclient above, this package's default retry policy already retries on HTTP 429 and most 5xx responses in addition to transport-level failures — no equivalent of RetryOnServerErrors is needed here.

Import this sub-package only when needed — it pulls in the hashicorp library independently of the parent httpclient package.

import "github.com/phcp-tech/common-library-golang/httpclient/retryable"

cli := retryable.NewHttpClient(retryable.Config{
    Timeout:  15 * time.Second,
    RetryMax: 5,
})

// Obtain a standard *http.Client with retry built in.
stdClient := cli.Client().StandardClient()
resp, err := stdClient.Do(req)

See full examples.


httpserver — Production HTTP/HTTPS Server

A production-ready HTTP/HTTPS server built on net/http with secure defaults. It wraps http.Server directly (not gin.Run()) to provide:

  • Configurable timeouts — ReadTimeout, WriteTimeout, IdleTimeout, ReadHeaderTimeout. A zero WriteTimeout falls back to the 60s default, not "unlimited" — pass httpserver.NoWriteTimeout for that (e.g. large file downloads).
  • TLS 1.2+ with strong cipher suites — activated when CrtFile and KeyFile are set
  • Graceful shutdown — Shutdown(ctx) drains in-flight requests before stopping

The IRunner interface unifies HTTP and Lambda modes so the composition root selects the backend and the rest of the application code is unchanged.

import "github.com/phcp-tech/common-library-golang/httpserver"

// Plain HTTP with package defaults.
runner := httpserver.NewHttpServer(httpserver.Config{Port: "8080"})

// HTTPS with custom timeouts.
runner := httpserver.NewHttpServer(httpserver.Config{
    Port:         "8443",
    CrtFile:      "/etc/ssl/server.crt",
    KeyFile:      "/etc/ssl/server.key",
    ReadTimeout:  15 * time.Second,
    WriteTimeout: httpserver.NoWriteTimeout, // unlimited (required for file downloads) — a literal 0 falls back to the 60s default instead
})

// Start in a goroutine; block until OS signal, then shut down gracefully.
go func() { _ = runner.Start(ginRouter) }()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = runner.Shutdown(ctx)

See full examples.


httpserver/lambda — AWS Lambda Adapter

Implements httpserver.IRunner for AWS Lambda via aws-lambda-go-api-proxy. It bridges APIGatewayProxyRequest events to any http.Handler (including *gin.Engine) with no handler changes required.

Import this sub-package only for Lambda deployments — it pulls in the AWS Lambda SDK. Services that run as plain HTTP servers are unaffected.

import (
    "github.com/phcp-tech/common-library-golang/httpserver"
    lambdarunner "github.com/phcp-tech/common-library-golang/httpserver/lambda"
)

// Composition root selects the runner based on the deployment environment.
var runner httpserver.IRunner
if isLambda {
    runner = lambdarunner.NewHttpServer()
} else {
    runner = httpserver.NewHttpServer(httpserver.Config{Port: port})
}
_ = runner.Start(ginRouter) // same call regardless of mode

See full examples.

Directories

Path Synopsis
component
Package component provides Casbin lifecycle integration for bootstrap.
Package component provides Casbin lifecycle integration for bootstrap.
Package bootstrap orchestrates the sequential initialization and LIFO cleanup of application components at startup.
Package bootstrap orchestrates the sequential initialization and LIFO cleanup of application components at startup.
Package cdn purges CDN cache entries by URL.
Package cdn purges CDN cache entries by URL.
clickhouse/component
Package component provides GORM ClickHouse lifecycle integration for bootstrap.
Package component provides GORM ClickHouse lifecycle integration for bootstrap.
mysql/component
Package component provides GORM MySQL lifecycle integration for bootstrap.
Package component provides GORM MySQL lifecycle integration for bootstrap.
postgres/component
Package component provides GORM PostgreSQL lifecycle integration for bootstrap.
Package component provides GORM PostgreSQL lifecycle integration for bootstrap.
sqlite/component
Package component provides GORM SQLite lifecycle integration for bootstrap.
Package component provides GORM SQLite lifecycle integration for bootstrap.
sqlite/vfs
Package vfs opens a SQLite database embedded inside a Go binary using modernc.org/sqlite/vfs and Go's embed.FS.
Package vfs opens a SQLite database embedded inside a Go binary using modernc.org/sqlite/vfs and Go's embed.FS.
mysql/component
Package component provides MySQL lifecycle integration for bootstrap.
Package component provides MySQL lifecycle integration for bootstrap.
postgres/component
Package component provides PostgreSQL lifecycle integration for bootstrap.
Package component provides PostgreSQL lifecycle integration for bootstrap.
sqlite/component
Package component provides SQLite lifecycle integration for bootstrap.
Package component provides SQLite lifecycle integration for bootstrap.
sqlite/vfs
Package vfs opens a SQLite database embedded in a Go binary via modernc.org/sqlite/vfs.
Package vfs opens a SQLite database embedded in a Go binary via modernc.org/sqlite/vfs.
Package dbsqlx is a thin wrapper around github.com/vinovest/sqlx (a database/sql extension with reflection-based struct scanning and Go generics).
Package dbsqlx is a thin wrapper around github.com/vinovest/sqlx (a database/sql extension with reflection-based struct scanning and Go generics).
clickhouse-native
Package clickhousenative provides a ClickHouse client using the native TCP protocol via github.com/ClickHouse/clickhouse-go/v2.
Package clickhousenative provides a ClickHouse client using the native TCP protocol via github.com/ClickHouse/clickhouse-go/v2.
clickhouse-native/component
Package component provides ClickHouse native-driver lifecycle integration for bootstrap.
Package component provides ClickHouse native-driver lifecycle integration for bootstrap.
clickhouse/component
Package component provides sqlx ClickHouse lifecycle integration for bootstrap.
Package component provides sqlx ClickHouse lifecycle integration for bootstrap.
mysql/component
Package component provides sqlx MySQL lifecycle integration for bootstrap.
Package component provides sqlx MySQL lifecycle integration for bootstrap.
postgres/component
Package component provides sqlx PostgreSQL lifecycle integration for bootstrap.
Package component provides sqlx PostgreSQL lifecycle integration for bootstrap.
sqlite/component
Package component provides sqlx SQLite lifecycle integration for bootstrap.
Package component provides sqlx SQLite lifecycle integration for bootstrap.
sqlite/vfs
Package vfs opens a SQLite database embedded inside a Go binary using modernc.org/sqlite/vfs and Go's embed.FS.
Package vfs opens a SQLite database embedded inside a Go binary using modernc.org/sqlite/vfs and Go's embed.FS.
component
Package component provides email sender lifecycle integration for bootstrap.
Package component provides email sender lifecycle integration for bootstrap.
env
component
Package component provides env lifecycle integration for bootstrap.
Package component provides env lifecycle integration for bootstrap.
Package file checks file uploads against an upload policy: the allowed content types, the size limit and the file name.
Package file checks file uploads against an upload policy: the allowed content types, the size limit and the file name.
gin
component
Package component provides Gin lifecycle integration for bootstrap.
Package component provides Gin lifecycle integration for bootstrap.
download
Package download serves files under one directory as downloads on a Gin engine.
Package download serves files under one directory as downloads on a Gin engine.
pprof
Package pprof exposes Go runtime profiling endpoints on a Gin engine via github.com/gin-contrib/pprof.
Package pprof exposes Go runtime profiling endpoints on a Gin engine via github.com/gin-contrib/pprof.
Package health provides a composable health-check mechanism.
Package health provides a composable health-check mechanism.
retryable
Package retryable wraps hashicorp/go-retryablehttp and exposes it as a standard *http.Client with configurable retry and timeout.
Package retryable wraps hashicorp/go-retryablehttp and exposes it as a standard *http.Client with configurable retry and timeout.
component
Package component provides HTTP server lifecycle integration for bootstrap.
Package component provides HTTP server lifecycle integration for bootstrap.
componentwithlambda
Package componentwithlambda provides HTTP server lifecycle integration for bootstrap, with AWS Lambda support.
Package componentwithlambda provides HTTP server lifecycle integration for bootstrap, with AWS Lambda support.
log
component
Package component provides log lifecycle integration for bootstrap.
Package component provides log lifecycle integration for bootstrap.
component
Package component provides Redis lifecycle integration for bootstrap.
Package component provides Redis lifecycle integration for bootstrap.
Package shutdown provides two primitives for application shutdown:
Package shutdown provides two primitives for application shutdown:
Package storage accesses S3-compatible object storage (Cloudflare R2, AWS S3, MinIO, Aliyun OSS) through one generic S3 client, so switching platforms only changes configuration.
Package storage accesses S3-compatible object storage (Cloudflare R2, AWS S3, MinIO, Aliyun OSS) through one generic S3 client, so switching platforms only changes configuration.
component
Package component provides object storage lifecycle integration for bootstrap.
Package component provides object storage lifecycle integration for bootstrap.
component
Package component provides JWT token lifecycle integration for bootstrap.
Package component provides JWT token lifecycle integration for bootstrap.
Package version provides application version and build metadata for API endpoints.
Package version provides application version and build metadata for API endpoints.

Jump to

Keyboard shortcuts

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