From 3decc2e0002667fdee6fa6efa6fc054cc44edcbe Mon Sep 17 00:00:00 2001 From: wbtiger <28288271@qq.com> Date: Sat, 4 Apr 2026 13:33:53 +0800 Subject: [PATCH] fix: return empty array instead of 500 on empty database Co-Authored-By: Claude Opus 4.6 --- handlers/items.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/handlers/items.go b/handlers/items.go index 16c0f49..7cb90ea 100644 --- a/handlers/items.go +++ b/handlers/items.go @@ -24,14 +24,19 @@ func GetItems(w http.ResponseWriter, r *http.Request) { storeMu.RLock() defer storeMu.RUnlock() - // BUG: when store is nil (fresh start), json.Marshal(nil map values) - // causes unexpected behavior — should return [] but may panic or 500. + w.Header().Set("Content-Type", "application/json") + + if store == nil || len(store) == 0 { + w.WriteHeader(http.StatusOK) + w.Write([]byte("[]")) + return + } + items := make([]Item, 0, len(store)) for _, item := range store { items = append(items, item) } - w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(items); err != nil { http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError) }