fix: nil slices return [] not null in all API responses

This commit is contained in:
2026-03-28 14:33:36 +03:00
parent c2040656bd
commit a47f703910
2 changed files with 9 additions and 3 deletions
-3
View File
@@ -27,9 +27,6 @@ func (s *Server) listProjects(w http.ResponseWriter, r *http.Request) {
respondError(w, http.StatusInternalServerError, "failed to list projects: "+err.Error())
return
}
if projects == nil {
projects = []store.Project{}
}
respondJSON(w, http.StatusOK, projects)
}
+9
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"log/slog"
"net/http"
"reflect"
)
// envelope is the standard API response wrapper.
@@ -14,7 +15,15 @@ type envelope struct {
}
// respondJSON writes a JSON success response with the given status code and data.
// Nil slices are converted to empty arrays to avoid "null" in JSON output.
func respondJSON(w http.ResponseWriter, status int, data any) {
// Convert nil slices to empty arrays so JSON encodes as [] not null.
if data != nil {
v := reflect.ValueOf(data)
if v.Kind() == reflect.Slice && v.IsNil() {
data = reflect.MakeSlice(v.Type(), 0, 0).Interface()
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(envelope{Success: true, Data: data}); err != nil {