go-utils

module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT

README

go-utils

go get github.com/deepworx/go-utils

Shared Go utility library for services.

Installation

go get github.com/deepworx/go-utils

Packages

Package Import Description
ctxutil pkg/ctxutil Context helpers (request ID, user claims)
shutdown pkg/shutdown Graceful shutdown orchestration
otel pkg/otel OpenTelemetry initialization
tracing pkg/tracing Manual span creation helpers
postgres pkg/postgres Database pool, transactions, and UnitOfWork
nats pkg/nats NATS/JetStream connection with tracing and metrics
grpchealth pkg/grpchealth gRPC health check aggregator
slogutil pkg/slogutil Global slog logger setup
koanfutil pkg/koanfutil Koanf configuration helpers
jwtauth pkg/connectrpc/jwtauth JWT authentication interceptor
recovery pkg/connectrpc/recovery Panic recovery interceptor
logging pkg/connectrpc/logging Request/response logging interceptor
requestid pkg/connectrpc/requestid Request ID propagation interceptor
errors pkg/connectrpc/errors Error mapping interceptor
deadline pkg/connectrpc/deadline Deadline enforcement interceptor
interceptor pkg/connectrpc/interceptor Default interceptor chain builder
otelconnect connectrpc.com/otelconnect OpenTelemetry tracing/metrics (external)
validate connectrpc.com/validate Request validation with protovalidate (external)

Documentation

ctxutil

Store and retrieve request-scoped values: request ID and JWT claims (UserID, TenantID, Roles, Permissions).

ctx = ctxutil.WithRequestID(ctx, "req-123")
ctx = ctxutil.WithClaims(ctx, ctxutil.Claims{UserID: "user-456", TenantID: "tenant-789"})

id, ok := ctxutil.RequestID(ctx)
userID, ok := ctxutil.UserID(ctx)
shutdown

Graceful shutdown orchestration with LIFO handler execution and OS signal support.

shutdown.Register(otel.Shutdown)  // called 3rd
shutdown.Register(server.Stop)    // called 2nd
shutdown.Register(db.Close)       // called 1st (LIFO)

shutdown.WaitForSignal(ctx) // blocks until SIGINT/SIGTERM, 30s timeout for handlers

Custom timeout:

shutdown.WaitForSignalWithTimeout(ctx, 60*time.Second) // 60s for handlers to complete

Default: shutdown.DefaultShutdownTimeout (30s)

otel

OpenTelemetry setup for tracing, metrics, and logging. Configurable via OTEL_* env vars.

otel.Setup(ctx, otel.Config{ServiceName: "my-service", ServiceVersion: "1.0.0"})
// Shutdown is automatically registered with the shutdown orchestrator

Env vars: OTEL_TRACES_EXPORTER, OTEL_METRICS_EXPORTER, OTEL_LOGS_EXPORTER (otlp|console|none)

tracing

Span wrapper with automatic error recording. Works without TracerProvider (no-op).

err := tracing.WithSpan(ctx, "operation", func(ctx context.Context) error {
    return doWork(ctx)
})

result, err := tracing.WithSpanResult(ctx, "fetch", func(ctx context.Context) (User, error) {
    return fetchUser(ctx)
})
postgres

Database pool with OpenTelemetry tracing and health checking.

pool, _ := postgres.NewPool(ctx, postgres.Config{DSN: "postgres://localhost/db"})

// Health check for grpchealth aggregator
checker := postgres.NewHealthChecker(pool)

// UnitOfWork for testable transaction management
uow := postgres.NewUnitOfWork(pool)
uow.Execute(ctx, func(ctx context.Context, tx postgres.Transaction) error {
    return repo.Save(ctx, tx.Tx(), data)
})

// For testing: InMemoryUnitOfWork (tx.Tx() returns nil)
memUoW := postgres.NewInMemoryUnitOfWork()
nats

NATS and JetStream connection with TLS/mTLS support, health checks, tracing, and metrics.

conn, _ := nats.Connect(ctx, nats.Config{URL: "nats://localhost:4222"})

// Health check for grpchealth aggregator
checker := nats.NewHealthChecker(conn)

Publish with trace context:

nats.Publish(ctx, conn, nats.PublishInput{
    Subject: "orders.created",
    Data:    payload,
})

// JetStream with deduplication
js, _ := jetstream.New(conn)
nats.JetStreamPublish(ctx, js, nats.JetStreamPublishInput{
    Subject: "orders.created",
    Data:    payload,
    MsgID:   "order-123", // optional deduplication
})

Consume with automatic trace extraction:

nats.ConsumeWithTracing(ctx, nats.ConsumeInput{
    Consumer: consumer,
    Handler: func(ctx context.Context, msg jetstream.Msg) error {
        // ctx contains extracted trace context
        return processOrder(ctx, msg)
    },
})
grpchealth

Health check aggregator for connectrpc.com/grpchealth. Probes checkers in parallel, sets StatusServing only if all pass. Automatically registers with shutdown for graceful termination.

aggregator := grpchealth.NewAggregator(ctx, grpchealth.DefaultConfig()).
    Register("postgres", postgres.NewHealthChecker(pool)).
    Register("redis", redisChecker)

mux.Handle(aggregator.Handler())
// Background goroutine runs automatically, stopped by shutdown.WaitForSignal()
slogutil

Configure the global slog logger with level and format.

slogutil.Setup(slogutil.Config{Level: "debug", Format: "json"})
// or with defaults (level: info, format: text)
slogutil.Setup(slogutil.DefaultConfig())
koanfutil

Helpers for koanf configuration loading.

k := koanf.New(".")
k.Load(koanfutil.WithDefaults(postgres.DefaultConfig()), nil) // load defaults
k.Load(file.Provider("config.toml"), toml.Parser())           // override with file
k.Load(koanfutil.FileResolver(k), nil)                        // resolve file:// URIs
  • WithDefaults(T) - Load struct as default values (uses koanf tags)
  • FileResolver(k) - Resolve file:///path URIs to file contents

All packages provide DefaultConfig() with sensible defaults (see godoc).

connectrpc/jwtauth

JWT authentication interceptor with JWKS support. IDP-independent, configurable claims mapping.

auth, _ := jwtauth.NewAuthenticator(ctx, jwtauth.Config{
    JWKSURL:  "https://auth.example.com/.well-known/jwks.json",
    Issuer:   "https://auth.example.com",
    Audience: "my-api",
    ClaimsMapping: &jwtauth.ClaimsMapping{
        UserID:   "sub",
        TenantID: "tenant_id",
        Roles:    "realm_access.roles",
    },
})

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(jwtauth.NewInterceptor(auth)),
))

Claims available via ctxutil.UserID(ctx), ctxutil.Roles(ctx), etc.

connectrpc/recovery

Panic recovery interceptor. Catches panics, logs with stack trace, returns CodeInternal.

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(
        recovery.NewInterceptor(),
        // ... other interceptors
    ),
))

Logs include: procedure, panic value, stack trace, request_id (if present).

connectrpc/logging

Structured request/response logging. Success at Info, errors at Warn.

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(logging.NewInterceptor()),
))

Log attributes: procedure, status, request_id, user_id, error (on failure).

connectrpc/requestid

Propagates or generates request IDs. Stores in context via ctxutil.WithRequestID.

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(requestid.NewInterceptor(requestid.Config{
        HeaderName: "X-Request-ID", // default
    })),
))

Generated IDs are UUID v4 without hyphens (32 characters).

connectrpc/errors

Maps errors to Connect RPC codes. Unmapped errors return CodeInternal with sanitized message.

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(errors.NewInterceptor()),
))

Implement ConnectCoder on errors:

type ErrNotFound struct{ ID string }

func (e *ErrNotFound) Error() string {
    return fmt.Sprintf("resource %s not found", e.ID)
}

func (e *ErrNotFound) ConnectCode() connect.Code {
    return connect.CodeNotFound
}

Error mapping priority:

  1. context.Canceled → CodeCanceled
  2. context.DeadlineExceeded → CodeDeadlineExceeded
  3. ConnectCoder interface → custom code
  4. *connect.Error → preserved
  5. Other errors → CodeInternal (message: "internal error")

Mapped errors (1-4) preserve original message. Unmapped errors (5) hide details.

connectrpc/deadline

Enforces deadlines on server-side unary calls. Applies a default timeout when none exists, and caps existing deadlines to a maximum.

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(deadline.NewInterceptor(deadline.Config{
        DefaultTimeout: 30 * time.Second, // applied when no deadline exists
        MaxTimeout:     60 * time.Second, // caps existing deadlines (0 = no cap)
    })),
))
connectrpc/interceptor

Default interceptor chain builder. Order: recovery → deadline → requestid → otel → logging → [jwtauth] → validate → errors.

interceptors, _ := interceptor.BuildDefault()                      // 7 interceptors
interceptors, _ := interceptor.BuildDefaultWithAuth(auth)          // 8 interceptors (with JWT)
interceptors, _ := interceptor.BuildDefault(                       // with options
    interceptor.WithDeadline(deadline.Config{DefaultTimeout: 60 * time.Second}),
)
connectrpc/tracing (via otelconnect)

For OpenTelemetry tracing and metrics, use the official otelconnect library:

go get connectrpc.com/otelconnect
import "connectrpc.com/otelconnect"

otelInterceptor, _ := otelconnect.NewInterceptor()

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(otelInterceptor),
))

Options:

  • WithTrustRemote() - Trust incoming trace context (internal services)
  • WithoutServerPeerAttributes() - Reduce metric cardinality
connectrpc/validation (via validate)

For request validation using protovalidate rules, use the official validate library:

go get connectrpc.com/validate
import "connectrpc.com/validate"

validateInterceptor, _ := validate.NewInterceptor()

mux.Handle(servicepb.NewServiceHandler(
    &Server{},
    connect.WithInterceptors(validateInterceptor),
))

Returns CodeInvalidArgument with field-level violation details on validation failure.

Directories

Path Synopsis
pkg
connectrpc
Package connectrpc provides interceptors for Connect RPC services.
Package connectrpc provides interceptors for Connect RPC services.
connectrpc/deadline
Package deadline provides deadline enforcement for Connect RPC handlers.
Package deadline provides deadline enforcement for Connect RPC handlers.
connectrpc/errors
Package errors provides error mapping for Connect RPC handlers.
Package errors provides error mapping for Connect RPC handlers.
connectrpc/interceptor
Package interceptor provides default interceptor chain builders for Connect RPC services.
Package interceptor provides default interceptor chain builders for Connect RPC services.
connectrpc/jwtauth
Package jwtauth provides JWT authentication for Connect RPC services.
Package jwtauth provides JWT authentication for Connect RPC services.
connectrpc/logging
Package logging provides structured request/response logging for Connect RPC handlers.
Package logging provides structured request/response logging for Connect RPC handlers.
connectrpc/recovery
Package recovery provides panic recovery for Connect RPC handlers.
Package recovery provides panic recovery for Connect RPC handlers.
connectrpc/requestid
Package requestid provides request ID propagation for Connect RPC handlers.
Package requestid provides request ID propagation for Connect RPC handlers.
ctxutil
Package ctxutil provides utility functions for storing and retrieving request-scoped values in context.Context.
Package ctxutil provides utility functions for storing and retrieving request-scoped values in context.Context.
grpchealth
Package grpchealth provides a health check aggregator for connectrpc.com/grpchealth.
Package grpchealth provides a health check aggregator for connectrpc.com/grpchealth.
koanfutil
Package koanfutil provides utilities for koanf configuration loading.
Package koanfutil provides utilities for koanf configuration loading.
nats
Package nats provides NATS and JetStream connection utilities with tracing integration.
Package nats provides NATS and JetStream connection utilities with tracing integration.
otel
Package otel provides OpenTelemetry initialization for tracing, metrics, and logging.
Package otel provides OpenTelemetry initialization for tracing, metrics, and logging.
postgres
Package postgres provides database access utilities with tracing integration.
Package postgres provides database access utilities with tracing integration.
shutdown
Package shutdown provides graceful shutdown orchestration for services.
Package shutdown provides graceful shutdown orchestration for services.
slogutil
Package slogutil provides configuration and setup utilities for slog.
Package slogutil provides configuration and setup utilities for slog.
tracing
Package tracing provides utility functions for manual span creation.
Package tracing provides utility functions for manual span creation.

Jump to

Keyboard shortcuts

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