geektutu/7days-golang · warning
key is required
Error message
key is required
What it means
Same guard in day4 (consistent-hash peers): Group.Get rejects an empty key with 'key is required' before local lookup or consistent-hash peer selection. Empty keys would otherwise be hashed and possibly routed to a peer pointlessly.
Source
Thrown at gee-cache/day4-consistent-hash/geecache/geecache.go:62
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)
}
func (g *Group) load(key string) (value ByteView, err error) {
return g.getLocally(key)
}
func (g *Group) getLocally(key string) (ByteView, error) {
bytes, err := g.getter.Get(key)
if err != nil {
return ByteView{}, errView on GitHub (pinned to cf36443821)
Solutions
- Ensure the key query parameter is present and non-empty on all cache requests
- Validate the key before calling group.Get in application code
- Return a 400 response for empty keys at the HTTP boundary
- Check consistent-hash peer URL construction preserves the key parameter
Example fix
// before
key := r.URL.Query().Get("key")
v, err := group.Get(key)
// after
key := r.URL.Query().Get("key")
if key == "" { http.Error(w, "key is required", http.StatusBadRequest); return }
v, err := group.Get(key) Defensive patterns
Strategy: validation
Validate before calling
func getFromCache(g *geecache.Group, key string) (geecache.ByteView, error) {
if strings.TrimSpace(key) == "" {
return geecache.ByteView{}, errors.New("cache: key must be non-empty")
}
return g.Get(key)
} Try / catch
v, err := group.Get(key)
if err != nil {
if err.Error() == "key is required" {
http.Error(w, "missing cache key", http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
} Prevention
- Guard empty keys before they enter the consistent-hash routing layer
- Check the key query parameter in the peer-aware HTTP handler
- Cover the empty-key path in unit tests for both Group.Get and ServeHTTP
When it happens
Trigger: Calling group.Get("") directly, or an HTTP cache request with a missing/empty key parameter, or an upstream caller forwarding an empty string from user input into the cache API.
Common situations: Missing query parameter in requests proxied through the consistent-hash peer pool; buggy URL builders; tests exercising the validation path.
Related errors
AI-assisted analysis of geektutu/7days-golang@cf36443821 (2026-09-03).
Data as JSON: /api/errors/e6ff9d822c0853be.
Report an issue: GitHub.