geektutu/7days-golang · error

key is required

Error message

key is required

What it means

Group.Get validates that the cache key is a non-empty string before doing any lookup. GeeCache keys are the identity of a cache entry, and an empty key can never exist in mainCache, so the library fails fast with a clear message instead of a silent cache miss that would then trigger a peer fetch or loader callback for a bogus key. This guard runs before the local cache lookup, the peer selection, and the user-supplied Getter.

Source

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

		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()
	return g
}

// Get value for a key from cache
func (g *Group) Get(key string) (ByteView, error) {
	if key == "" {
		return ByteView{}, fmt.Errorf("key is required")
	}

	if v, ok := g.mainCache.get(key); ok {
		log.Println("[GeeCache] hit")
		return v, nil
	}

	return g.load(key)
}

// RegisterPeers registers a PeerPicker for choosing remote peer
func (g *Group) RegisterPeers(peers PeerPicker) {
	if g.peers != nil {
		panic("RegisterPeerPicker called more than once")
	}
	g.peers = peers
}

View on GitHub (pinned to cf36443821)

Solutions

  1. Check the key for emptiness (after strings.TrimSpace) at the call site before invoking group.Get and return a client-facing bad-request error
  2. Trace where the key is constructed (handler params, path segments, config) and fix the upstream source of the empty value
  3. If empty keys are legitimate, define a sentinel/mapped key instead of using ""

Example fix

// before
v, err := group.Get(key) // key may be ""
// after
if key = strings.TrimSpace(key); key == "" {
    http.Error(w, "missing cache key", http.StatusBadRequest)
    return
}
v, err := group.Get(key)
Defensive patterns

Strategy: validation

Validate before calling

if strings.TrimSpace(key) == "" {
    return ByteView{}, errors.New("cache key must be non-empty")
}
v, err := group.Get(key)

Type guard

func validKey(k string) bool { return strings.TrimSpace(k) != "" }

Prevention

When it happens

Trigger: Calling group.Get("") with an empty string key; building a key from string concatenation/formatting where a variable part is empty (e.g. fmt.Sprintf("user:%d", 0 misused) or a missing query parameter); calling Get before the key variable is initialized.

Common situations: HTTP handlers that pass a request parameter straight through without trimming/validating it; keys derived from config or environment values that are unset; refactored code where a prefix/suffix component of a composite key became empty.

Related errors


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