SyntaxPilot
Courses/Go Programming/Lesson 71
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 71 of 89

Configuration and dependency injection

twelve-factor app configconfiguration from flagsenvironment and filesconfig structs and validationfunctional options patternconstructor injectionavoiding package-level globalswiring in maingoogle/wire (concept)interfaces at boundaries for testing

These are the notes for Go episode 71. Raju's order service now runs in three places: his laptop, a test copy, and production. Its port and its database password are written straight into the code. A second copy on the same laptop crashes, production needs a rebuild for every setting, and the password sits in git. And because the service keeps its orders and its SMS sender in global variables, a test sends a real SMS and the next test fails. Today we invent the fixes: configuration that lives outside the code, and dependency injection, where each part receives what it needs instead of reaching for globals.

All outputs below are from real runs (Go 1.24.7, linux/amd64), through the same runner the video's compiler uses. When stderr lines (like exit status 1) appear at the end of an output block, that's because the runner prints the error stream after the normal output.

Facts and sources

  • The Twelve-Factor App, factor III "Config" (12factor.net/config, read for this episode): "An app's config is everything that is likely to vary between deploys (staging, production, developer environments, etc)." It "requires strict separation of config from code". The litmus test is "whether the codebase could be made open source at any moment, without compromising any credentials." And "The twelve-factor app stores config in environment variables".
  • google/wire (the project's README, read from its GitHub repository for this episode): "Wire is a code generation tool that automates connecting components using dependency injection." "Because Wire operates without runtime state or reflection, code written to be used with Wire is useful even for hand-written initialization." The README now carries the warning: "This project is no longer maintained." Its guide: the injector file has the wireinject build tag, Wire writes wire_gen.go beginning // Code generated by Wire. DO NOT EDIT., and you regenerate it with go generate.
  • Go Code Review Comments (go.dev/wiki/CodeReviewComments): "Go interfaces generally belong in the package that uses values of the interface type" and "Do not define interfaces before they are used".
  • errors.Join is listed in $(go env GOROOT)/api/go1.20.txt: it arrived in Go 1.20.

The problem: settings written in the code

Raju's first version keeps two settings as constants:

main.go:

package main

import (
    "fmt"
    "net"
)

// settings written straight into the code
const addr = ":8080"
const dbURL = "postgres://raju:Chai@123@db.prod:5432/shop"

func main() {
    first, err := net.Listen("tcp", addr) // the dev copy
    if err != nil {
        panic(err)
    }
    defer first.Close()
    fmt.Println("dev copy listening on", addr)

    _, err = net.Listen("tcp", addr) // a test copy on the same laptop
    fmt.Println("test copy:", err)
    fmt.Println("database:", dbURL) // and the password is in git
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go run .

Output:

$ go run .
dev copy listening on :8080
test copy: listen tcp :8080: bind: address already in use
database: postgres://raju:Chai@123@db.prod:5432/shop

Two things went wrong:

  1. The port is fixed. A port is a number (0 to 65535) that a program uses to receive network connections on a machine; only one program can listen on a given port at a time. With :8080 written in the code, a second copy (a test copy, or a second service) cannot start: bind: address already in use. To change it, you must edit the code and rebuild.
  2. The password is in the code, so it is in git (the history of the code) for anyone who can read the repository, forever, even after you delete it in a later commit.

The root cause: the code mixes what the program does (the same everywhere) with settings that change from place to place.

Twelve-factor config: the recipe and the order slip

A tiffin kitchen with many branches uses the same recipe for dal everywhere: that's your code, built once into one binary. Each day's order slip is different (40 plates, less spicy, deliver to sector 5): that's configuration. And the key to the cash locker is never written in the recipe book: that's a secret (passwords, API keys, tokens).

  • Config = everything that is likely to vary between deploys.
  • A deploy is one running copy of the app: the developer's laptop, a staging server (a production-like copy used for testing), or production (the real system customers use).
  • Strict separation of config from code. The litmus test: could you publish the code as open source today without leaking a credential?
  • Not config: routes, business rules, the structure of your program. They are the same in every deploy, so they stay in code.
  • Twelve-factor stores config in environment variables: named values the operating system gives a program when it starts. In a shell: SHOP_PORT=9090 ./shop. In Go: os.Getenv("SHOP_PORT") or os.LookupEnv("SHOP_PORT").

Four sources, one Config struct

Real services usually read config from four layers, each overriding the one before it:

Layer Example Good for
1. defaults in code Port: 8080 safe values that work locally
2. a config file config.json with {"port": 8000} many settings, checked-in non-secret defaults per environment
3. environment variables SHOP_PORT=9090 per-deploy values and secrets (twelve-factor)
4. command-line flags ./shop -port 7070 one-off overrides while running by hand

A flag (command-line flag) is an option typed after the program's name. Go's flag package parses them. The rule: load everything once, at startup, into one Config struct, then pass it (or its parts) to the code that needs it.

The episode's program (CFG1)

main.go:

package main

import (
    "encoding/json"
    "flag"
    "fmt"
    "net"
    "os"
    "strconv"
)

// Config: everything that changes between deploys
type Config struct {
    Port  int    `json:"port"`
    DBURL string `json:"db_url"`
    Debug bool   `json:"debug"`
}

func Load(args []string) (Config, error) {
    cfg := Config{Port: 8080} // 1. defaults
    if b, err := os.ReadFile("config.json"); err == nil { // 2. file
        if err := json.Unmarshal(b, &cfg); err != nil {
            return cfg, fmt.Errorf("config.json: %w", err)
        }
    }
    if v, ok := os.LookupEnv("SHOP_PORT"); ok { // 3. environment
        p, err := strconv.Atoi(v)
        if err != nil {
            return cfg, fmt.Errorf("SHOP_PORT: %w", err)
        }
        cfg.Port = p
    }
    if v, ok := os.LookupEnv("SHOP_DB_URL"); ok {
        cfg.DBURL = v
    }
    fs := flag.NewFlagSet("shop", flag.ContinueOnError) // 4. flags win
    fs.IntVar(&cfg.Port, "port", cfg.Port, "HTTP port")
    fs.BoolVar(&cfg.Debug, "debug", cfg.Debug, "verbose logging")
    return cfg, fs.Parse(args)
}

func main() {
    cfg, err := Load(os.Args[1:])
    if err != nil {
        fmt.Println("config error:", err)
        os.Exit(1)
    }
    fmt.Printf("%+v\n", cfg)
    ln, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.Port))
    if err != nil {
        fmt.Println("start failed:", err)
        os.Exit(1)
    }
    ln.Close()
}

config.json:

{"port": 8000, "db_url": "postgres://localhost/shop_dev"}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go run .
SHOP_PORT=9090 go run .
SHOP_PORT=9090 go run . -port 7070 -debug
SHOP_PORT=70000 go run .

Output:

$ go run .
{Port:8000 DBURL:postgres://localhost/shop_dev Debug:false}
$ SHOP_PORT=9090 go run .
{Port:9090 DBURL:postgres://localhost/shop_dev Debug:false}
$ SHOP_PORT=9090 go run . -port 7070 -debug
{Port:7070 DBURL:postgres://localhost/shop_dev Debug:true}
$ SHOP_PORT=70000 go run .
{Port:70000 DBURL:postgres://localhost/shop_dev Debug:false}
start failed: listen tcp: address 70000: invalid port
exit status 1

Line by line:

  • Struct tags like `json:"db_url"` tell encoding/json which JSON key fills which field.
  • json.Unmarshal(b, &cfg) decodes JSON into the struct. Fields missing from the file keep their current values, which is exactly what layering needs: the file only overrides what it mentions.
  • os.LookupEnv returns the value and whether the variable was set. That matters: SHOP_DB_URL= (set, but empty) is different from "not set". os.Getenv can't tell them apart.
  • strconv.Atoi ("ASCII to integer") turns text into an int, and returns an error for text like abc.
  • flag.NewFlagSet("shop", flag.ContinueOnError) makes our own flag set (instead of the global flag.CommandLine), so Load can be tested with any argument list and returns errors instead of exiting.
  • fs.IntVar(&cfg.Port, "port", cfg.Port, ...): the third argument is the flag's default. We pass the value so far, so a flag only changes the port when it's given.

Reading the runs: the plain run uses 8000 from the file; SHOP_PORT=9090 wins over the file; -port 7070 wins over the environment, and -debug sets Debug:true. Same binary, three behaviours, no rebuild.

The last run shows the next problem: SHOP_PORT=70000 was accepted, the program carried on, and only failed later: listen tcp: address 70000: invalid port. In a real service, that could be minutes later, after it had started half its work, or only on the code path that uses the value.

What a bad flag looks like

With flag.ContinueOnError, a bad flag value is returned as an error, and the flag set also prints its usage (to stderr):

$ go run . -port abc
config error: invalid value "abc" for flag -port: parse error
invalid value "abc" for flag -port: parse error
Usage of shop:
  -debug
        verbose logging
  -port int
        HTTP port (default 8000)
exit status 1

Note (default 8000): the default shown is the value after the file layer, because we passed cfg.Port as the default.

Validate at startup: fail fast

Fail fast means checking the configuration right after loading it, before doing any work, and stopping with a clear message if anything is wrong. A broken deploy should stop in its first second, not crash at 2 A.M. on the first request that needs a value.

We add a Validate method and collect every problem, not only the first, with errors.Join (Go 1.20+). It combines several errors into one, whose message has one line per error, and it returns nil when given no non-nil errors.

The episode's program (CFG2)

main.go:

package main

import (
    "encoding/json"
    "errors"
    "flag"
    "fmt"
    "os"
    "strconv"
)

// Config: everything that changes between deploys
type Config struct {
    Port  int    `json:"port"`
    DBURL string `json:"db_url"`
    Debug bool   `json:"debug"`
}

func Load(args []string) (Config, error) {
    cfg := Config{Port: 8080} // 1. defaults
    if b, err := os.ReadFile("config.json"); err == nil { // 2. file
        if err := json.Unmarshal(b, &cfg); err != nil {
            return cfg, fmt.Errorf("config.json: %w", err)
        }
    }
    if v, ok := os.LookupEnv("SHOP_PORT"); ok { // 3. environment
        p, err := strconv.Atoi(v)
        if err != nil {
            return cfg, fmt.Errorf("SHOP_PORT: %w", err)
        }
        cfg.Port = p
    }
    if v, ok := os.LookupEnv("SHOP_DB_URL"); ok {
        cfg.DBURL = v
    }
    fs := flag.NewFlagSet("shop", flag.ContinueOnError) // 4. flags win
    fs.IntVar(&cfg.Port, "port", cfg.Port, "HTTP port")
    fs.BoolVar(&cfg.Debug, "debug", cfg.Debug, "verbose logging")
    if err := fs.Parse(args); err != nil {
        return cfg, err
    }
    return cfg, cfg.Validate() // fail fast, at startup
}

func (c Config) Validate() error {
    var errs []error
    if c.Port < 1 || c.Port > 65535 {
        errs = append(errs, fmt.Errorf("port %d: must be 1-65535", c.Port))
    }
    if c.DBURL == "" {
        errs = append(errs, errors.New("db_url is required"))
    }
    return errors.Join(errs...) // nil when errs is empty
}

func main() {
    cfg, err := Load(os.Args[1:])
    if err != nil {
        fmt.Println("config error:", err)
        os.Exit(1)
    }
    fmt.Printf("%+v\n", cfg)
}

config.json:

{"port": 8000, "db_url": "postgres://localhost/shop_dev"}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

SHOP_PORT=70000 SHOP_DB_URL= go run .
SHOP_PORT=abc go run .
go run .

Output:

$ SHOP_PORT=70000 SHOP_DB_URL= go run .
config error: port 70000: must be 1-65535
db_url is required
$ SHOP_PORT=abc go run .
config error: SHOP_PORT: strconv.Atoi: parsing "abc": invalid syntax
$ go run .
{Port:8000 DBURL:postgres://localhost/shop_dev Debug:false}
exit status 1
exit status 1
  • Both problems in one go: port 70000: must be 1-65535 and db_url is required. The operator fixes both at once instead of redeploying twice.
  • SHOP_PORT=abc fails in Load with the wrapped strconv.Atoi error, which names the variable.
  • os.Exit(1): the exit code (also called exit status) tells the shell, the deploy tool or Kubernetes that the program failed. 0 means success; anything else means failure. go run reports it as exit status 1.

Config habits

  • Secrets come from the environment or a secret manager (a service that stores and hands out secrets, such as cloud key vaults), never from a file in git.
  • Prefix variables with the app's name (SHOP_PORT, SHOP_DB_URL) so they don't clash with other programs' variables.
  • Document every setting and its default. -h prints the flag set's usage automatically.
  • Read config in one place and pass it down. os.Getenv deep inside a package hides a setting nobody knows exists, and makes that package hard to test.
  • Prefer typed fields (int, time.Duration, bool) in Config and convert once, at load time.

Why globals break tests

A package-level variable (a global) is declared outside any function. Every function in the package shares the one copy. Raju keeps his orders and his SMS sender that way, like one order register for the whole kitchen: a trainee practises an order, and the real customer gets an SMS; the next trainee finds the practice order still written in the register.

The episode's program (GLOB)

orders.go:

package shop

import "fmt"

// package-level globals: shared by everything
var orders = map[string]bool{}
var sendSMS = func(phone, msg string) {
    fmt.Println("  REAL SMS sent to", phone, ":", msg)
}

func PlaceOrder(id, phone string) error {
    if orders[id] {
        return fmt.Errorf("order %s already exists", id)
    }
    orders[id] = true
    sendSMS(phone, "order "+id+" placed")
    return nil
}

orders_test.go:

package shop

import "testing"

func TestPlaceOrder(t *testing.T) {
    if err := PlaceOrder("A1", "+91 98100 00001"); err != nil {
        t.Fatal(err)
    }
}

func TestFreshShopAcceptsA1(t *testing.T) {
    if err := PlaceOrder("A1", "+91 98100 00002"); err != nil {
        t.Fatal(err)
    }
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go test -v .

Output:

$ go test -v .
=== RUN   TestPlaceOrder
  REAL SMS sent to +91 98100 00001 : order A1 placed
--- PASS: TestPlaceOrder (0.00s)
=== RUN   TestFreshShopAcceptsA1
    orders_test.go:13: order A1 already exists
--- FAIL: TestFreshShopAcceptsA1 (0.00s)
FAIL
FAIL    shop    0.002s
FAIL
  • REAL SMS sent to +91 98100 00001: a test reached the outside world. With a real SMS gateway that's a real message, and a real bill.
  • order A1 already exists: the second test expected a fresh shop, but the first test's order is still in the global map. Tests now depend on the order they run in. Run one test alone and it passes; run all and it fails.
  • Why: a function that uses a global hides its dependencies. You can't see from PlaceOrder's signature that it needs a store and an SMS sender, you can't give each test its own clean store, and swapping sendSMS from a test means changing shared state that other tests also see.

Constructor injection: a mixer grinder with a plug

A mixer grinder doesn't carry its own power station. It has a plug: it states what it needs, in a standard shape, and you plug it into whatever socket you have. In the factory, it's tested on a test socket that measures and sends nothing out.

  • Dependency = something a component needs to do its job: a store, an SMS sender, a clock, a logger.
  • Interface = the plug's shape: a list of methods the component needs (Store with Add, Notifier with Notify).
  • Dependency injection (DI) = giving a component its dependencies from outside, instead of it creating them or reaching for globals.
  • Constructor = the function that builds a value, by convention NewX. Constructor injection = passing the dependencies as the constructor's arguments.
  • Fake = a small, working pretend implementation for tests (an in-memory store, an SMS sender that only records). A mock is a fake that also checks how it was called (which methods, which arguments). A stub returns fixed answers.

The episode's program (DI)

orders.go:

package shop

import "fmt"

// what the service needs, described as small interfaces
type Store interface {
    Add(id string) error
}
type Notifier interface {
    Notify(phone, msg string) error
}

type OrderService struct {
    store  Store
    notify Notifier
}

// constructor injection: dependencies come in as arguments
func NewOrderService(s Store, n Notifier) *OrderService {
    return &OrderService{store: s, notify: n}
}

func (o *OrderService) Place(id, phone string) error {
    if err := o.store.Add(id); err != nil {
        return err
    }
    return o.notify.Notify(phone, "order "+id+" placed")
}

type MemStore struct{ ids map[string]bool }

func NewMemStore() *MemStore { return &MemStore{ids: map[string]bool{}} }
func (m *MemStore) Add(id string) error {
    if m.ids[id] {
        return fmt.Errorf("order %s already exists", id)
    }
    m.ids[id] = true
    return nil
}

orders_test.go:

package shop

import "testing"

type fakeSMS struct{ sent []string } // records, sends nothing

func (f *fakeSMS) Notify(phone, msg string) error {
    f.sent = append(f.sent, phone+": "+msg)
    return nil
}

func TestPlaceOrder(t *testing.T) {
    sms := &fakeSMS{}
    svc := NewOrderService(NewMemStore(), sms) // fresh, per test
    if err := svc.Place("A1", "+91 98100 00001"); err != nil {
        t.Fatal(err)
    }
    t.Log("fake SMS got:", sms.sent)
}

func TestFreshShopAcceptsA1(t *testing.T) {
    svc := NewOrderService(NewMemStore(), &fakeSMS{})
    if err := svc.Place("A1", "+91 98100 00002"); err != nil {
        t.Fatal(err)
    }
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go test -v .

Output:

$ go test -v .
=== RUN   TestPlaceOrder
    orders_test.go:18: fake SMS got: [+91 98100 00001: order A1 placed]
--- PASS: TestPlaceOrder (0.00s)
=== RUN   TestFreshShopAcceptsA1
--- PASS: TestFreshShopAcceptsA1 (0.00s)
PASS
ok      shop    0.002s
  • Both tests pass and no real SMS was sent: the fake recorded +91 98100 00001: order A1 placed, which t.Log prints in -v mode.
  • Each test builds its own NewMemStore(), so state can't leak between tests.
  • The constructor's signature documents the dependencies: anyone reading NewOrderService(s Store, n Notifier) knows exactly what the service needs.

Interfaces at the boundary

A boundary is where your code meets the outside world: the database, the SMS gateway, payments, the network, the file system, even the clock. Put small interfaces there, so tests can swap the outside world for fakes.

  • Define the interface where it is used (here, in the orders package), with only the methods that package calls. Go Code Review Comments: interfaces "generally belong in the package that uses values of the interface type", and "Do not define interfaces before they are used".
  • Go interfaces are satisfied implicitly (episode 21): *MemStore satisfies Store just by having Add(string) error, without saying so.
  • Don't add an interface for everything. Inside a package, plain structs and functions are fine. An interface earns its place when there's a second implementation, or a test needs a fake.

The functional options pattern

A constructor with many settings becomes unreadable: NewServer(":8443", 0, 10, true). What is 0? The default timeout, or "no timeout"? What is true? And adding one more setting changes the signature, so every caller must change.

Like ordering "one masala dosa" (the house way) and adding only "extra crispy, less oil": functional options keep the required value as a normal argument and make each optional setting a small function.

  • An option is a function that changes the thing being built: type Option func(*Server).
  • WithTimeout(d) returns such a function, with d captured inside it: a closure (episode 10).
  • A variadic parameter (opts ...Option) accepts zero or more values (episode 9).
  • The constructor sets safe defaults first, then applies each option in order.

The episode's program (OPTS)

main.go:

package main

import (
    "fmt"
    "time"
)

type Server struct {
    addr     string
    timeout  time.Duration
    maxConns int
    tls      bool
}

// an Option is a function that changes the server being built
type Option func(*Server)

func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func WithMaxConns(n int) Option          { return func(s *Server) { s.maxConns = n } }
func WithTLS() Option                    { return func(s *Server) { s.tls = true } }

func NewServer(addr string, opts ...Option) *Server {
    s := &Server{addr: addr, timeout: 5 * time.Second, maxConns: 100} // safe defaults
    for _, opt := range opts {
        opt(s) // each option overrides one default
    }
    return s
}

func main() {
    a := NewServer(":8080")
    b := NewServer(":8443", WithTLS(), WithTimeout(2*time.Second))
    c := NewServer(":9000", WithMaxConns(10))
    for _, s := range []*Server{a, b, c} {
        fmt.Printf("%s timeout=%v maxConns=%d tls=%v\n", s.addr, s.timeout, s.maxConns, s.tls)
    }
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go run .

Output:

$ go run .
:8080 timeout=5s maxConns=100 tls=false
:8443 timeout=2s maxConns=100 tls=true
:9000 timeout=5s maxConns=10 tls=false

Options or a config struct?

type ServerConfig struct {
    Timeout  time.Duration // 0 means "use the default, 5s"
    MaxConns int           // 0 means "use the default, 100"
    TLS      bool
}

func NewServer(addr string, c ServerConfig) *Server { ... }

Both are idiomatic.

Config struct Functional options
Simplicity simpler, one type one function per setting
Filling from your Config direct build a slice of options
Zero values must mean "default" defaults set in the constructor
Adding a setting add a field: old calls still compile add a WithX: old calls still compile
Validation per setting in the constructor each option can return an error (type Option func(*Server) error)
Typical use applications libraries with many optional settings (for example grpc.NewServer(opts...), episode 69)

Wiring in main: the composition root

In a house, every appliance only has a plug; all the wires meet at one switchboard, wired once. In a Go app, that switchboard is func main: it builds every concrete part and connects them. This single place is called the composition root. Nothing else in the program decides which store or which SMS sender is used.

The episode's program (WIRE)

main.go:

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "os"

    "shop/orders"
)

// main is the one place that knows every concrete type
func main() {
    store := orders.NewMemStore()
    var sms orders.Notifier = orders.PrintSMS{} // local runs: print, don't send
    if os.Getenv("SHOP_SMS") == "gateway" {
        sms = orders.GatewaySMS{APIKey: os.Getenv("SMS_API_KEY")}
    }
    svc := orders.NewService(store, sms)
    handler := orders.NewHandler(svc)
    fmt.Printf("wired: %T + %T -> %T\n", store, sms, handler)

    srv := httptest.NewServer(handler)
    defer srv.Close()
    for _, id := range []string{"A1", "A1"} {
        resp, _ := http.Post(srv.URL+"/orders?id="+id, "", nil)
        body, _ := io.ReadAll(resp.Body)
        resp.Body.Close()
        fmt.Printf("POST %s -> %d %s", id, resp.StatusCode, body)
    }
}

orders/orders.go:

package orders

import (
    "errors"
    "fmt"
    "net/http"
)

type Store interface{ Add(id string) error }
type Notifier interface{ Notify(msg string) error }

type Service struct {
    store Store
    sms   Notifier
}

func NewService(s Store, n Notifier) *Service { return &Service{store: s, sms: n} }

func (o *Service) Place(id string) error {
    if err := o.store.Add(id); err != nil {
        return err
    }
    return o.sms.Notify("order " + id + " placed")
}

var ErrExists = errors.New("order already exists")

type MemStore struct{ ids map[string]bool }

func NewMemStore() *MemStore { return &MemStore{ids: map[string]bool{}} }
func (m *MemStore) Add(id string) error {
    if m.ids[id] {
        return ErrExists
    }
    m.ids[id] = true
    return nil
}

type PrintSMS struct{}

func (PrintSMS) Notify(msg string) error { fmt.Println("  sms (printed, not sent):", msg); return nil }

type GatewaySMS struct{ APIKey string }

func (GatewaySMS) Notify(msg string) error { return errors.New("real gateway: not in this demo") }

type Handler struct{ svc *Service }

func NewHandler(s *Service) *Handler { return &Handler{svc: s} }

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    err := h.svc.Place(r.URL.Query().Get("id"))
    switch {
    case errors.Is(err, ErrExists):
        http.Error(w, err.Error(), http.StatusConflict)
    case err != nil:
        http.Error(w, "internal error", http.StatusInternalServerError)
    default:
        w.WriteHeader(http.StatusCreated)
        fmt.Fprintln(w, "created")
    }
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go run .

Output:

$ go run .
wired: *orders.MemStore + orders.PrintSMS -> *orders.Handler
  sms (printed, not sent): order A1 placed
POST A1 -> 201 created
POST A1 -> 409 order already exists
  • %T prints a value's type: *orders.MemStore, orders.PrintSMS, *orders.Handler.
  • The orders package never reads a setting, an environment variable or a global: it only receives its parts. Tomorrow, main can pass a Postgres store instead of MemStore, and nothing in orders changes.
  • The handler maps the service's errors to HTTP status codes: ErrExists → 409 Conflict, any other error → 500 with a generic message, success → 201 Created. (More on mapping errors at the boundary in episode 72.)

google/wire: generated wiring

In big programs main can grow long. google/wire is a code generation tool (a program that writes Go source for you): you list the constructors, Wire works out the order from their parameter and result types, and writes plain wiring code.

//go:build wireinject

package main

import "github.com/google/wire"

func initApp(cfg Config) (*App, error) {
    wire.Build(NewStore, NewSMS, NewService, NewHandler, NewApp)
    return nil, nil // Wire replaces this function body
}

Wire writes wire_gen.go:

// Code generated by Wire. DO NOT EDIT.

func initApp(cfg Config) (*App, error) {
    store := NewStore(cfg)
    sms := NewSMS(cfg)
    service := NewService(store, sms)
    handler := NewHandler(service)
    return NewApp(handler), nil
}
  • The wireinject build tag keeps the recipe file out of normal builds (build tags: episode 73). go generate regenerates wire_gen.go.
  • No reflection or container at run time: the generated code is what you would write by hand.
  • Status: its README now says "This project is no longer maintained." For most services, hand-written wiring in main is clear and enough. Whatever tool you use, the idea stays the same: constructors that take their dependencies.
  • (The two snippets above are illustrations of Wire's file layout; their constructors are placeholders, not a program from the video.)

Configuration and DI in one page

 defaults < config.json < environment < flags      (Load, once)
                    │
                Validate  ── errors.Join, exit 1 on bad config
                    │
                  main    ── builds every concrete part (composition root)
                    │
     NewStore  NewSMS  NewService(store, sms)  NewHandler(service)
  • Config out of code; secrets out of git.
  • No package-level globals for state or dependencies.
  • Small interfaces at the boundaries, defined where used → fakes in tests.
  • Functional options (or a config struct) for many optional settings.

Mini project: a configurable order service

Build:

  1. config.Load(args, lookup) with port, DB URL, SMS mode and an order cut-off hour; layers env < flags (add a file layer if you like); Validate with errors.Join.
  2. orders.Service that gets a Store, a Notifier and a Clock through NewService, plus a WithCutoff option.
  3. Tests that use fakes: a fixed clock, a recording SMS sender, a fresh store per test, and a fake environment (a map instead of os.LookupEnv).
  4. All wiring in main.
Solution

main.go:

package main

import (
    "fmt"
    "os"
    "time"

    "shop/config"
    "shop/orders"
)

type realClock struct{}

func (realClock) Now() time.Time { return time.Now() }

func main() {
    cfg, err := config.Load(os.Args[1:], os.LookupEnv)
    if err != nil {
        fmt.Fprintln(os.Stderr, "config:", err)
        os.Exit(1)
    }
    svc := orders.NewService(orders.NewMemStore(), orders.PrintSMS{}, realClock{},
        orders.WithCutoff(cfg.CutoffHour))
    fmt.Printf("config: %+v\n", cfg)
    fmt.Println("wired:", svc != nil)
}

config/config.go:

package config

import (
    "errors"
    "flag"
    "fmt"
    "strconv"
)

type Config struct {
    Port       int
    DBURL      string
    SMSMode    string // "print" or "gateway"
    CutoffHour int    // no new orders after this hour
}

// lookup is os.LookupEnv in main, a map in tests
func Load(args []string, lookup func(string) (string, bool)) (Config, error) {
    cfg := Config{Port: 8080, SMSMode: "print", CutoffHour: 22}
    if v, ok := lookup("SHOP_PORT"); ok {
        p, err := strconv.Atoi(v)
        if err != nil {
            return cfg, fmt.Errorf("SHOP_PORT: %w", err)
        }
        cfg.Port = p
    }
    if v, ok := lookup("SHOP_DB_URL"); ok {
        cfg.DBURL = v
    }
    if v, ok := lookup("SHOP_SMS"); ok {
        cfg.SMSMode = v
    }
    fs := flag.NewFlagSet("shop", flag.ContinueOnError)
    fs.IntVar(&cfg.Port, "port", cfg.Port, "HTTP port")
    fs.IntVar(&cfg.CutoffHour, "cutoff", cfg.CutoffHour, "last hour for orders (0-23)")
    if err := fs.Parse(args); err != nil {
        return cfg, err
    }
    return cfg, cfg.Validate()
}

func (c Config) Validate() error {
    var errs []error
    if c.Port < 1 || c.Port > 65535 {
        errs = append(errs, fmt.Errorf("port %d: must be 1-65535", c.Port))
    }
    if c.DBURL == "" {
        errs = append(errs, errors.New("db_url is required"))
    }
    if c.SMSMode != "print" && c.SMSMode != "gateway" {
        errs = append(errs, fmt.Errorf("sms mode %q: must be print or gateway", c.SMSMode))
    }
    if c.CutoffHour < 0 || c.CutoffHour > 23 {
        errs = append(errs, fmt.Errorf("cutoff %d: must be 0-23", c.CutoffHour))
    }
    return errors.Join(errs...)
}

config/config_test.go:

package config

import "testing"

func env(m map[string]string) func(string) (string, bool) {
    return func(k string) (string, bool) { v, ok := m[k]; return v, ok }
}

func TestLayers(t *testing.T) {
    cfg, err := Load([]string{"-port", "7070"}, env(map[string]string{"SHOP_PORT": "9090", "SHOP_DB_URL": "mem://"}))
    if err != nil || cfg.Port != 7070 {
        t.Fatalf("got %+v, %v; want port 7070", cfg, err)
    }
}

func TestAllProblemsReported(t *testing.T) {
    _, err := Load([]string{"-cutoff", "25"}, env(map[string]string{"SHOP_SMS": "pigeon"}))
    t.Log(err)
    if err == nil {
        t.Fatal("want an error")
    }
}

orders/orders.go:

package orders

import (
    "errors"
    "fmt"
    "time"
)

type Store interface{ Add(id string) error }
type Notifier interface{ Notify(msg string) error }
type Clock interface{ Now() time.Time }

var ErrClosed = errors.New("kitchen closed for today")

type Service struct {
    store  Store
    sms    Notifier
    clock  Clock
    cutoff int
}

type Option func(*Service)

func WithCutoff(hour int) Option { return func(s *Service) { s.cutoff = hour } }

func NewService(st Store, n Notifier, c Clock, opts ...Option) *Service {
    s := &Service{store: st, sms: n, clock: c, cutoff: 22}
    for _, o := range opts {
        o(s)
    }
    return s
}

func (s *Service) Place(id string) error {
    if s.clock.Now().Hour() >= s.cutoff {
        return ErrClosed
    }
    if err := s.store.Add(id); err != nil {
        return err
    }
    return s.sms.Notify("order " + id + " placed")
}

type MemStore struct{ ids map[string]bool }

func NewMemStore() *MemStore { return &MemStore{ids: map[string]bool{}} }
func (m *MemStore) Add(id string) error {
    if m.ids[id] {
        return fmt.Errorf("order %s already exists", id)
    }
    m.ids[id] = true
    return nil
}

type PrintSMS struct{}

func (PrintSMS) Notify(msg string) error { fmt.Println("sms:", msg); return nil }

orders/orders_test.go:

package orders

import (
    "errors"
    "testing"
    "time"
)

type fixedClock struct{ t time.Time }

func (f fixedClock) Now() time.Time { return f.t }

type fakeSMS struct{ sent []string }

func (f *fakeSMS) Notify(msg string) error { f.sent = append(f.sent, msg); return nil }

func at(h int) fixedClock { return fixedClock{time.Date(2026, 11, 14, h, 0, 0, 0, time.UTC)} }

func TestPlaceBeforeCutoff(t *testing.T) {
    sms := &fakeSMS{}
    svc := NewService(NewMemStore(), sms, at(21))
    if err := svc.Place("A1"); err != nil {
        t.Fatal(err)
    }
    t.Log("sent:", sms.sent)
}

func TestClosedAfterCutoff(t *testing.T) {
    svc := NewService(NewMemStore(), &fakeSMS{}, at(21), WithCutoff(20))
    if err := svc.Place("A1"); !errors.Is(err, ErrClosed) {
        t.Fatalf("got %v, want ErrClosed", err)
    }
}

Run it (from the folder with these files; go.mod says module shop, go 1.24):

go test -v ./...
SHOP_DB_URL=mem:// go run . -port 9090

Output:

$ go test -v ./...
?       shop    [no test files]
=== RUN   TestLayers
--- PASS: TestLayers (0.00s)
=== RUN   TestAllProblemsReported
    config_test.go:18: db_url is required
        sms mode "pigeon": must be print or gateway
        cutoff 25: must be 0-23
--- PASS: TestAllProblemsReported (0.00s)
PASS
ok      shop/config 0.004s
=== RUN   TestPlaceBeforeCutoff
    orders_test.go:25: sent: [order A1 placed]
--- PASS: TestPlaceBeforeCutoff (0.00s)
=== RUN   TestClosedAfterCutoff
--- PASS: TestClosedAfterCutoff (0.00s)
PASS
ok      shop/orders 0.002s
$ SHOP_DB_URL=mem:// go run . -port 9090
config: {Port:9090 DBURL:mem:// SMSMode:print CutoffHour:22}
wired: true

Design notes:

  • Load takes lookup func(string) (string, bool). main passes os.LookupEnv; tests pass a map-backed function. The environment is injected too.
  • The Clock interface turns "is it after 10 P.M.?" into something a test can control: at(21) is always 9 P.M., so the test never depends on when it runs.
  • One run of the config test shows all three problems from errors.Join, one per line.

Common mistakes (and the real messages)

Mistake What you see Why Fix
const addr = ":8080" listen tcp :8080: bind: address already in use settings in code port from env or a flag
password in code or in config.json in git credentials leak with the code fails the open-source litmus test secrets from the environment or a secret manager
no validation listen tcp: address 70000: invalid port, later bad value found too late Validate at startup, errors.Join
bad env value SHOP_PORT: strconv.Atoi: parsing "abc": invalid syntax text isn't a number report the variable's name, exit 1
bad flag value invalid value "abc" for flag -port: parse error flag parse failed the message names the flag; fix the command
os.Getenv deep in a package a hidden setting nobody documents config read everywhere load once in main, pass it down
os.Getenv when "unset" and "empty" differ can't tell SHOP_DB_URL= from unset Getenv returns "" for both os.LookupEnv
global var sendSMS / var orders tests print REAL SMS sent; order A1 already exists shared hidden state constructor injection, fresh fakes per test
an interface for every struct code that's hard to follow abstraction with no need interfaces at boundaries, defined where used
NewServer(":8443", 0, 10, true) nobody knows what 0 and true mean positional settings functional options or a config struct

Practice

  1. Add a -config flag that names the config file (default config.json). Why can't it be parsed in the same flag pass that overrides the file's values?
  2. Add Timeout time.Duration to Config, read from SHOP_TIMEOUT=2s. Which function parses "2s"?
  3. Write a test for Load that proves the environment beats the file, without touching the real environment.
  4. In the GLOB program, the second test passes when run alone (go test -run TestFreshShopAcceptsA1). Why? What does this tell you about globals?
  5. Turn NewServer into an options function that can fail: WithMaxConns(-1) should make NewServer return an error.
  6. Your service needs the current time to stamp orders. How do you make that testable?
Solutions

1. The config file must be known before the file layer is applied, but flags are applied last. Either parse -config in a small first pass (a separate FlagSet that only defines -config, ignoring others) or read it from an environment variable such as SHOP_CONFIG. Many programs do the first pass with fs.String("config", ...) on a copy of the arguments.

2. time.ParseDuration:

if v, ok := lookup("SHOP_TIMEOUT"); ok {
    d, err := time.ParseDuration(v) // "2s", "500ms", "1m30s"
    if err != nil {
        return cfg, fmt.Errorf("SHOP_TIMEOUT: %w", err)
    }
    cfg.Timeout = d
}

For a flag, fs.DurationVar(&cfg.Timeout, "timeout", cfg.Timeout, "request timeout") parses the same format.

3. Inject both the environment and the file reader, as the mini project does for the environment:

func Load(args []string, lookup func(string) (string, bool), readFile func(string) ([]byte, error)) (Config, error)

// test:
cfg, _ := Load(nil,
    env(map[string]string{"SHOP_PORT": "9090", "SHOP_DB_URL": "mem://"}),
    func(string) ([]byte, error) { return []byte(`{"port": 8000}`), nil })
// want cfg.Port == 9090

4. Alone, it is the first test to touch the global map, so A1 is new. With the other test first, A1 is already there. Globals make a test's result depend on which other tests ran before it, and on their order: a sign of hidden shared state.

5.

type Option func(*Server) error

func WithMaxConns(n int) Option {
    return func(s *Server) error {
        if n < 1 {
            return fmt.Errorf("max conns %d: must be at least 1", n)
        }
        s.maxConns = n
        return nil
    }
}

func NewServer(addr string, opts ...Option) (*Server, error) {
    s := &Server{addr: addr, timeout: 5 * time.Second, maxConns: 100}
    for _, opt := range opts {
        if err := opt(s); err != nil {
            return nil, err
        }
    }
    return s, nil
}

6. Inject a clock: type Clock interface{ Now() time.Time } with a real implementation calling time.Now() and a fixed fake in tests, exactly as in the mini project. (A plain now func() time.Time field works too.)

Quick quiz

1. Default port 8080, config.json says 8000, SHOP_PORT=9090, and the command is ./shop -port 7070. Which port? (From the video.)

A. 8080 · B. 8000 · C. 9090 · D. 7070

Answer

D. 7070. Each layer overrides the one before it, and flags are the last layer.

2. What does errors.Join() return when called with no errors (or only nil errors)?

Answer

nil. That's why return errors.Join(errs...) is a correct "no problems" result when errs is empty.

3. Which is not config in the twelve-factor sense? A. the database URL · B. the HTTP port · C. the rule "orders over Rs 500 get free delivery" · D. the SMS API key

Answer

C. A business rule is the same in every deploy, so it belongs in code. (If it must change without a deploy, it's product data, stored in a database, not deploy config.)

4. Why did the second test in GLOB fail?

Answer

The first test left order A1 in the package-level orders map, so the second test found it already there: state leaked between tests through a global.

Interview questions

  1. What counts as configuration? Everything that varies between deploys: ports, URLs, credentials, feature switches per environment. Code and business rules don't.
  2. Why environment variables for config? They're language- and OS-neutral, set per deploy without changing code or files in git, and easy to inject in containers and CI. Secrets especially should never be in the repository.
  3. How do you combine defaults, a file, env and flags? Load in layers into one struct, each overriding the last (defaults < file < env < flags), then validate once.
  4. What does "fail fast" mean for config? Validate at startup, report all problems together, and exit non-zero before serving traffic.
  5. os.Getenv vs os.LookupEnv? LookupEnv also reports whether the variable exists, so "set but empty" can be told apart from "unset".
  6. What is dependency injection, and why does Go code use it? Passing dependencies in (usually through constructors) instead of creating them inside or using globals. It makes dependencies explicit, lets tests swap fakes, and avoids hidden shared state.
  7. Where should interfaces be defined? In the package that uses them, small, containing only the methods it needs; not "just in case".
  8. Fake vs mock vs stub? A fake is a working lightweight implementation; a stub returns canned answers; a mock also verifies the calls made to it.
  9. Explain the functional options pattern. type Option func(*T); NewT(required, opts ...Option) sets defaults then applies each option. Readable calls, safe defaults, and new options don't break callers.
  10. What is a composition root? The one place (in Go, usually main) that builds concrete implementations and wires them together.
  11. What does google/wire do? Generates the wiring code from a list of constructors at build time, with no run-time reflection. Its README now says it is no longer maintained.
  12. Why are package-level mutable globals a problem? Hidden dependencies, shared state between tests, order-dependent results, and data races when several goroutines use them.

Glossary

Term Meaning Example
Configuration (config) settings that vary between deploys port, DB URL, API keys
Deploy one running copy of an app in one place Raju's laptop, staging, production
Staging a production-like copy used for testing before release staging.shop.example
Production the real system real customers use the live order API
Twelve-Factor App a well-known set of 12 rules for building services factor III: Config
Strict separation of config from code config never written into the source port from SHOP_PORT
Litmus test a simple test that decides a question "could this code be open-sourced today?"
Secret / credential a value that grants access and must stay private DB password, SMS API key
Secret manager a service that stores secrets and gives them to apps a cloud key vault
Port a number a program listens on for network connections :8080
Listener an open "counter" waiting for incoming connections net.Listen("tcp", ":8080")
bind: address already in use the error when another program already owns the port the second copy on :8080
Environment variable a named value the OS gives a program at start SHOP_PORT=9090
os.Getenv / os.LookupEnv read an environment variable / also say if it was set v, ok := os.LookupEnv("SHOP_PORT")
Config file a file holding settings config.json
JSON a text format for data: objects, lists, strings, numbers {"port": 8000}
Struct tag text after a field that packages read `json:"db_url"`
Unmarshal decode data (like JSON) into a Go value json.Unmarshal(b, &cfg)
Command-line flag an option typed after a program's name -port 7070, -debug
flag.FlagSet a set of flags you define and parse flag.NewFlagSet("shop", flag.ContinueOnError)
IntVar / BoolVar define a flag that writes into a variable fs.IntVar(&cfg.Port, "port", 8080, "HTTP port")
Layered config sources applied in order, later ones overriding defaults < file < env < flags
strconv.Atoi convert text to an int strconv.Atoi("9090") → 9090
Validation checking values follow the rules port must be 1–65535
Fail fast stop at the first moment a problem can be detected exit at startup on bad config
errors.Join combine several errors into one (Go 1.20+) both config problems in one message
Exit code / exit status the number a program returns when it ends; 0 = success os.Exit(1), exit status 1
Package-level variable (global) a variable declared outside functions, shared by the whole package var orders = map[string]bool{}
Hidden dependency something a function needs that its signature doesn't show PlaceOrder using sendSMS
Side effect an effect outside the function's result sending a real SMS
Dependency something a component needs to work store, notifier, clock
Dependency injection (DI) giving a component its dependencies from outside NewOrderService(store, sms)
Constructor a function that builds a value NewMemStore()
Constructor injection DI through a constructor's arguments NewService(s Store, n Notifier)
Interface a set of method signatures a type can satisfy type Notifier interface{ Notify(...) error }
Implicit satisfaction a type satisfies an interface just by having its methods *MemStore is a Store
Boundary where your code meets the outside world DB, SMS gateway, clock
Fake a small working pretend implementation for tests fakeSMS records messages
Mock a fake that also checks how it was called "Notify called once with A1"
Stub a pretend implementation that returns fixed answers a clock that always says 9 P.M.
Test isolation each test runs with its own state a fresh MemStore per test
t.Log print a message in test output (shown with -v or on failure) fake SMS got: [...]
Functional options optional settings passed as small functions NewServer(addr, WithTLS())
Option a function that changes the value being built type Option func(*Server)
Variadic parameter a parameter that takes zero or more values opts ...Option
Closure a function value that remembers variables from where it was made WithTimeout(d) remembers d
Default the value used when nothing else is given timeout 5s
TLS the encryption behind HTTPS WithTLS()
Wiring creating the parts and connecting them main building store → service → handler
Composition root the one place that wires concrete types together func main
%T the fmt verb that prints a value's type *orders.MemStore
Code generation a tool writing source code for you wire writes wire_gen.go
google/wire a compile-time DI code generator for Go (no longer maintained) wire.Build(NewStore, ...)
Reflection inspecting types and values while the program runs what Wire avoids
Build tag a condition that includes a file only in some builds //go:build wireinject

Summary

  • Config is everything that varies between deploys. Keep it out of the code and secrets out of git (twelve-factor); the open-source litmus test tells you if you got it right.
  • Load it once, into one Config struct, in layers: defaults < file (encoding/json) < environment (os.LookupEnv) < flags (flag.NewFlagSet). Same binary, different behaviour, no rebuild.
  • Validate at startup and report every problem with errors.Join; exit non-zero (fail fast).
  • Globals hide dependencies and share state: a test sent a "real" SMS and the next test failed with order A1 already exists.
  • Constructor injection: components take small interfaces (defined where used, at the boundaries) through NewX; tests pass fakes and get fresh state.
  • Functional options (type Option func(*T)) give readable calls with safe defaults; a config struct is the simpler alternative.
  • main is the composition root: it wires concrete types together. google/wire can generate that code, but it's no longer maintained; hand-written wiring is usually enough.

Next episode: Idiomatic design and application architecture: Go proverbs, naming, useful zero values, small interfaces, package by feature, hexagonal architecture, domain types, errors at boundaries, API stability.