medium.com 4 min read Original Source

We removed three popular Go Libraries — And the code got better

I dont know about you as a developer but there is a certain comfort in reaching for a well-known library.

Those stars on GitHub, the familiar import path, the Stack Overflow answers that practically

— write themselves. It feels responsible. Defensive, even.

But at some point during a code review on our payments service, someone asked a question that stuck: “Do we actually need this, or are we just used to it?”

For the next two weeks, we removed three libraries we had treated as defaults.

No rewrites from scratch, no big architectural shifts — just deliberate subtraction. The code got smaller, faster to understand, and easier to test. Here’s what we removed, why, and what we learned.

Library 1: github.com/spf13/viper — Configuration management

Viper is everywhere in Go services. It handles config files, environment variables, remote config, and a dozen other sources with a unified API. For a long time, we didn’t question it.

The problem surfaced when a new engineer was trying to trace where a specific config value came from during an incident.

Viper’s layered precedence system — flags override env vars override config files override defaults — is powerful, but in production, that power becomes ambiguity. The value was being set in three places.

Which one won? You had to know Viper’s resolution order by heart.

We replaced it with a single Config struct loaded explicitly at startup:

type Config struct {
    DatabaseURL     string
    RedisAddr       string
    PaymentGateway  string
    Port            int
}

func LoadConfig() (Config, error) {
    return Config{
        DatabaseURL:    requireEnv("DATABASE_URL"),
        RedisAddr:      requireEnv("REDIS_ADDR"),
        PaymentGateway: requireEnv("PAYMENT_GATEWAY_URL"),
        Port:           envIntOrDefault("PORT", 8080),
    }, nil
}

func requireEnv(key string) string {
    v := os.Getenv(key)
    if v == "" {
        panic(fmt.Sprintf("required env var %s is not set", key))
    }
    return v
}
type Config struct {
    DatabaseURL     string
    RedisAddr       string
    PaymentGateway  string
    Port            int
}

func LoadConfig() (Config, error) {
    return Config{
        DatabaseURL:    requireEnv("DATABASE_URL"),
        RedisAddr:      requireEnv("REDIS_ADDR"),
        PaymentGateway: requireEnv("PAYMENT_GATEWAY_URL"),
        Port:           envIntOrDefault("PORT", 8080),
    }, nil
}

func requireEnv(key string) string {
    v := os.Getenv(key)
    if v == "" {
        panic(fmt.Sprintf("required env var %s is not set", key))
    }
    return v
}

That’s it. No reflection magic, no config file parsing, no remote key-value store integration which as a matter of fact, we were never using anyway.

The struct gets passed explicitly to the components that need it. If something is misconfigured, it fails immediately at startup with a clear message, not silently mid-request.

The test setup got simpler too. Constructing a Config in a test is just a struct literal. No viper.Set() calls, no global state leaking between tests.

Library 2: github.com/pkg/errors — Error wrapping

This one surprised us.

pkg/errors was one of the first libraries the Go ecosystem rallied around for better error handling, and for years it was the right call. errors.Wrap, stack traces on demand — it felt like the professional choice.

Then Go 1.13 shipped %w. And everything changed.

We would still find ourselves importing pkg/errors in a codebase running Go 1.22.

The wrapping semantics were nearly identical to what the standard library now provides, but we had two wrapping styles coexisting: some files used fmt.Errorf("doing X: %w", err), others used errors.Wrap(err, "doing X").

Reviewers would inconsistently flag one or the other. The error handling chapter of the internal style guide had a footnote that quietly apologized for the inconsistency.

The migration was mechanical. We ran a codebase-wide replacement, switching errors.Wrap(err, msg) to fmt.Errorf("%s: %w", msg, err) and errors.New(msg) to errors.New(msg) from the standard library.

The stack traces from pkg/errors were genuinely useful in the early days, but our structured logging setup (zerolog with a Sentry integration) was already capturing stack traces at the log site.

We were paying the cost of the dependency without getting the benefit.

One import dropped. One style enforced. errors.Is and errors.As work perfectly for sentinel matching and type assertions down the unwrap chain.

Library 3: github.com/gin-gonic — Http Router

This is the one people push back on most.

Gin is fast, popular, and genuinely explicitly good. We’re not saying it isn’t. But for an internal gRPC-first service that exposed exactly four HTTP endpoints — health check, readiness probe, Prometheus metrics, and a single webhook receiver — it was the wrong tool.

We were pulling in Gin’s entire middleware ecosystem, its custom context type, its router tree, its recovery middleware, for four routes.

The *gin.Context type was bleeding into function signatures that had no business knowing about HTTP routing internals.

Writing unit tests for handlers meant either constructing Gin’s context by hand or writing integration-style tests against a running server.

The replacement was net/http with a thin function-based approach:

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /healthz", healthzHandler)
    mux.HandleFunc("GET /readyz", readyzHandler)
    mux.Handle("GET /metrics", promhttp.Handler())
    mux.HandleFunc("POST /webhooks/payment", webhookHandler)

    srv := &http.Server{
        Addr:         ":8080",
        Handler:      mux,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    // graceful shutdown wiring
}
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /healthz", healthzHandler)
    mux.HandleFunc("GET /readyz", readyzHandler)
    mux.Handle("GET /metrics", promhttp.Handler())
    mux.HandleFunc("POST /webhooks/payment", webhookHandler)

    srv := &http.Server{
        Addr:         ":8080",
        Handler:      mux,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    // graceful shutdown wiring
}

Go 1.22’s enhanced ServeMux gave us method-based routing without any third-party dependency.

Handler functions take http.ResponseWriter and *http.Request — the types every Go developer knows cold. Tests use httptest.NewRecorder. No framework context to construct, no middleware chain to understand.

For a service that needs 40 routes, complex middleware chains, or request binding with validation, Gin earns its place.

For four endpoints behind an internal load balancer, it was like importing a city to deliver one package.

The Pattern We Kept Seeing

Across all three removals, the same shape emerged.

Each library had been pulled in to solve a real problem, and solved it well. But the problem either had a standard library solution now, or our actual requirements were narrower than what the library assumed.

The cost isn’t just binary size or compile time. It’s cognitive.

Every non-standard abstraction is a translation layer between what the code does and what a reader expects. pkg/errors.Wrap and fmt.Errorf("%w", ...) do the same thing, but one of them requires knowing a library’s conventions.

Over a large codebase, those small translation costs compound drastically.

Its worth giving the Go team credit as the Go’s standard library has gotten dramatically better across the versions most production services run.

The language’s culture — interfaces over inheritance, explicit over implicit, composition over configuration — pairs naturally with keeping the dependency tree shallow.

Before adding the next dependency do this

The question isn’t whether a library is good. Most of the popular ones are. The question is whether your specific service, with its actual load patterns, its actual feature requirements, and its actual team, needs what that library provides.

In my opinion, the best dependency is often the one you didn’t add.

Thanks for reading. Read these too

Forget perfect microservices — build this instead
Complexity feels smart — until it starts slowing everything down

I Stopped Writing Tests This Way — Everything Improved
Get this right once and you’ll never write tests badly in any of your Go projects again.

The biggest mistake most teams make with Go microservices
The Architecture Mistake That Makes Go Microservices Hard to Maintain