common-library-golang

module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: Apache-2.0

README

PHCP:common-library-golang

Go Reference LICENSE

Common-library-golang is a collection of functional components used within the PHCP ecosystem, providing numerous components for microservice development. 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 ./...
go test ./...
Run tests with coverage
# All packages
go test ./... -cover -timeout 60s

Packages

Package Import path Description
env .../common-library-golang/env TOML config + environment variable loader
log .../common-library-golang/log Structured JSON logger with file rotation and ringbuf
ringbuf .../common-library-golang/ringbuf Lock-free ring buffers (SPSC and MPSC)
dbsqlc/postgres .../common-library-golang/dbsqlc/postgres PostgreSQL connection pool via pgx/v5
dbsqlc/sqlite .../common-library-golang/dbsqlc/sqlite SQLite connection via pure-Go modernc driver

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)

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.CloseLogFile() // 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.


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.


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. 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.

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.

See full examples.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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