geektutu/7days-golang · error

key is required

Error message

key is required

What it means

Identical guard to the day5 version, in the day6-single-flight build: Group.Get rejects an empty key before consulting mainCache. With single-flight added, an empty key would otherwise be a cache miss funneled through a flight group and invoke the loader for a meaningless key, so the early validation also avoids pointless loader/peer work.

Source

Thrown at gee-cache/day6-single-flight/geecache/geecache.go:68

		loader:    &singleflight.Group{},
	}
	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. Validate/trim the key at the API boundary (HTTP handler) before calling group.Get
  2. Fix the path-parsing or parameter-extraction code that yields an empty key
  3. Return a 400 to the client when the key segment is missing

Example fix

// before
parts := strings.SplitN(r.URL.Path[len(p.basePath):], "/", 2)
key := parts[1]
v, _ := g.Get(key)
// after
if len(parts) != 2 || parts[1] == "" {
    http.Error(w, "key is required", http.StatusBadRequest)
    return
}
v, _ := g.Get(parts[1])
Defensive patterns

Strategy: validation

Validate before calling

key = strings.TrimSpace(key)
if key == "" {
    http.Error(w, "missing key", http.StatusBadRequest)
    return
}
v, err := group.Get(key)

Type guard

func nonEmpty(s string) bool { return strings.TrimSpace(s) != "" }

Prevention

When it happens

Trigger: group.Get("") on a day6 Group; empty key produced by handler parsing of the URL path (missing /<name>/<key> key segment after trimming the basePath).

Common situations: Requests like GET /_geecache/cachename/ (empty key part) forwarded into Get; keys taken from unvalidated request inputs; tests calling Get with placeholder empty strings.

Related errors


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