fix: nil slices return [] not null in all API responses
This commit is contained in:
@@ -27,9 +27,6 @@ func (s *Server) listProjects(w http.ResponseWriter, r *http.Request) {
|
|||||||
respondError(w, http.StatusInternalServerError, "failed to list projects: "+err.Error())
|
respondError(w, http.StatusInternalServerError, "failed to list projects: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if projects == nil {
|
|
||||||
projects = []store.Project{}
|
|
||||||
}
|
|
||||||
respondJSON(w, http.StatusOK, projects)
|
respondJSON(w, http.StatusOK, projects)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
// envelope is the standard API response wrapper.
|
// 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.
|
// 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) {
|
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.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(status)
|
||||||
if err := json.NewEncoder(w).Encode(envelope{Success: true, Data: data}); err != nil {
|
if err := json.NewEncoder(w).Encode(envelope{Success: true, Data: data}); err != nil {
|
||||||
|
|||||||
Reference in New Issue
Block a user