Backend Engineer Guide: Designing a Zero-Global-State Go Platform SDK with Functional Options
When an organization scales past ten Go microservices, teams naturally want a shared platform library (`pkg/platform`) for structured `slog` logging, OpenTelemetry trace propagation, RFC 7807 HTTP problem responses, and graceful shutdown orchestration. Yet poorly designed Go shared libraries quickly become a liability when they rely on package-level global variables, call `os.Exit` or `panic` inside library functions, or force every caller to import 40 transitive cloud SDK dependencies. As a backend engineer, I design zero-global-state Go platform SDKs using the Functional Options pattern and small, consumer-defined interfaces.
1. Functional Options with Safe Production Defaults in Go
Instead of exposing mutable globals or breaking function signatures every time a new timeout parameter is added, the Functional Options pattern guarantees backward compatibility while enforcing safe defaults (`ReadHeaderTimeout`, `IdleTimeout`, and structured error encoding):
// platform/httpserver/server.go
package httpserver
import (
"context"
"log/slog"
"net/http"
"time"
)
type Config struct {
addr string
readHeaderTimeout time.Duration
shutdownTimeout time.Duration
logger *slog.Logger
}
type Option func(*Config)
func WithAddr(addr string) Option {
return func(c *Config) { c.addr = addr }
}
func WithShutdownTimeout(d time.Duration) Option {
return func(c *Config) { c.shutdownTimeout = d }
}
func RunGracefully(ctx context.Context, handler http.Handler, opts ...Option) error {
cfg := Config{
addr: ":8080",
readHeaderTimeout: 5 * time.Second, // Mitigates Slowloris attacks by default
shutdownTimeout: 20 * time.Second,
logger: slog.Default(),
}
for _, opt := range opts {
opt(&cfg)
}
srv := &http.Server{
Addr: cfg.addr,
Handler: handler,
ReadHeaderTimeout: cfg.readHeaderTimeout,
}
errCh := make(chan error, 1)
go func() {
cfg.logger.Info("starting HTTP server", "addr", cfg.addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- err
}
close(errCh)
}()
select {
case err := <-errCh:
return err
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.shutdownTimeout)
defer cancel()
cfg.logger.Info("draining in-flight HTTP requests")
return srv.Shutdown(shutdownCtx)
}
}
2. Returning Structured RFC 7807 Problem Details
Standardizing all microservice error responses around RFC 7807 (`type`, `title`, `status`, `detail`, `trace_id`) allows API gateways and React/TypeScript clients to handle errors uniformly across every Go service.