geektutu/7days-golang · warning

key is required

Error message

key is required

What it means

Identical to the day2 check: Group.Get in day3 (HTTP server) returns 'key is required' when Get is called with an empty string, before any cache lookup or peer fetch. The HTTP handler passes the request's key parameter straight through, so blank keys surface this error.

Source

Thrown at gee-cache/day3-http-server/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. Always send a non-empty key query parameter to the cache HTTP endpoint
  2. Validate/sanitize inputs before constructing the cache request URL
  3. Handle the returned error and return 400 to the end client instead of a 500
  4. Add a client-side check: if key == "" skip the call

Example fix

// before
group.Get(r.URL.Query().Get("key")) // may be ""
// after
key := r.URL.Query().Get("key")
if key == "" { http.Error(w, "key is required", http.StatusBadRequest); return }
group.Get(key)
Defensive patterns

Strategy: validation

Validate before calling

key := r.URL.Query().Get("key")
if key == "" {
    http.Error(w, "key is required", http.StatusBadRequest)
    return
}
v, err := group.Get(key)

Try / catch

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

Prevention

When it happens

Trigger: group.Get("") in application code, or requests like GET /api/?key= / GET /api/ where the key query parameter is missing (ServeHTTP would also return http.StatusBadRequest for missing query param — the error text appears when Get is invoked with "").

Common situations: Clients hitting the cache API without the key parameter; URL encoding mistakes; empty form values forwarded as the key; test code calling Get with "" to assert validation.

Related errors


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