geektutu/7days-golang · warning

key is required

Error message

key is required

What it means

Group.Get in the day2 single-node geecache validates that the requested key is non-empty before consulting the cache; an empty key returns this error immediately. It prevents cache pollution/ambiguity from blank keys.

Source

Thrown at gee-cache/day2-single-node/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{}, err

View on GitHub (pinned to cf36443821)

Solutions

  1. Check that the HTTP request URL includes ?key=<name> (e.g. /_geecache/scores?key=math)
  2. Reject empty keys on the caller side before calling group.Get
  3. Fix URL-building code that omits the query parameter

Example fix

// before
resp, _ := http.Get(baseURL + "/_geecache/scores?key=" + key) // key may be ""
// after
if key == "" { return nil, errors.New("missing key") }
resp, _ := http.Get(baseURL + "/_geecache/scores?key=" + url.QueryEscape(key))
Defensive patterns

Strategy: validation

Validate before calling

func cacheGet(g *geecache.Group, key string) (geecache.ByteView, error) {
    if key == "" {
        return geecache.ByteView{}, errors.New("cache: empty key")
    }
    return g.Get(key)
}

Try / catch

v, err := group.Get(key)
if err != nil {
    if err.Error() == "key is required" {
        http.Error(w, "missing key", http.StatusBadRequest)
        return
    }
    http.Error(w, err.Error(), http.StatusInternalServerError)
}

Prevention

When it happens

Trigger: Calling group.Get("") directly, or an HTTP request reaching the cache server with an empty or missing 'key' query parameter (e.g. GET /_geecache/ or /_geecache/?key=).

Common situations: Misconfigured URL construction that drops the query string; a proxy stripping empty query params; tests or callers not validating user input before hitting the cache.

Related errors


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