geektutu/7days-golang · error

nil Getter

Error message

nil Getter

What it means

Same "nil Getter" fast-fail as errors 90/92, in the day5-multi-nodes version: NewGroup panics when the getter parameter is nil. A Group cannot fetch values on cache miss without a Getter, so construction with nil is treated as a programming error.

Source

Thrown at gee-cache/day5-multi-nodes/geecache/geecache.go:38

}

// A GetterFunc implements Getter with a function.
type GetterFunc func(key string) ([]byte, error)

// Get implements Getter interface function
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

var (
	mu     sync.RWMutex
	groups = make(map[string]*Group)
)

// NewGroup create a new instance of Group
func NewGroup(name string, cacheBytes int64, getter Getter) *Group {
	if getter == nil {
		panic("nil Getter")
	}
	mu.Lock()
	defer mu.Unlock()
	g := &Group{
		name:      name,
		getter:    getter,
		mainCache: cache{cacheBytes: cacheBytes},
	}
	groups[name] = g
	return g
}

// GetGroup returns the named group previously created with NewGroup, or
// nil if there's no such group.
func GetGroup(name string) *Group {
	mu.RLock()
	g := groups[name]
	mu.RUnlock()

View on GitHub (pinned to cf36443821)

Solutions

  1. Pass a non-nil Getter implementation to NewGroup
  2. Ensure initialization order: data source first, then groups
  3. Guard against typed-nil by asserting the concrete value is usable

Example fix

// before
var dbGetter geecache.Getter // never assigned
grp := geecache.NewGroup("scores", 2<<20, dbGetter)
// after
dbGetter := geecache.GetterFunc(func(key string) ([]byte, error) {
    return db.Get(key)
})
grp := geecache.NewGroup("scores", 2<<20, dbGetter)
Defensive patterns

Strategy: validation

Validate before calling

if getter == nil {
    panic("NewGroup requires a non-nil Getter")
}
grp := geecache.NewGroup("scores", 2<<20, getter)

Type guard

func getterReady(g geecache.Getter) bool { return g != nil }

Try / catch

// Recover at the top of server startup:
defer func() {
    if r := recover(); r != nil { log.Fatalf("cache init: %v", r) }
}()

Prevention

When it happens

Trigger: geecache.NewGroup(name, cacheBytes, nil) in multi-node setups — often when the getter is meant to come from a shared config/DB pool that was not initialized.

Common situations: Config loading order bugs where the cache group is built before its data source; typed-nil interface values from factory functions; copy-pasted group setup code with the getter left nil.

Related errors


AI-assisted analysis of geektutu/7days-golang@cf36443821 (2026-09-03). Data as JSON: /api/errors/f41c4b18cd6144d9. Report an issue: GitHub.