Pārlūkot izejas kodu

fix data structure of response (#3143)

Signed-off-by: Alex Meijer <alexander.meijer@ibm.com>
Alex Meijer 1 gadu atpakaļ
vecāks
revīzija
aafb2459f2
2 mainītis faili ar 22 papildinājumiem un 1 dzēšanām
  1. 6 1
      core/pkg/protocol/http.go
  2. 16 0
      core/pkg/protocol/http_test.go

+ 6 - 1
core/pkg/protocol/http.go

@@ -153,7 +153,12 @@ func (hp HTTPProtocol) WriteData(w http.ResponseWriter, data interface{}) {
 	w.Header().Set("Content-Type", "application/json")
 	status := http.StatusOK
 	w.WriteHeader(status)
-	if err := json.NewEncoder(w).Encode(data); err != nil {
+
+	resp := &HTTPResponse{
+		Code: status,
+		Data: data,
+	}
+	if err := json.NewEncoder(w).Encode(resp); err != nil {
 		log.Error("Failed to encode response: " + err.Error())
 		w.WriteHeader(http.StatusInternalServerError)
 		w.Write([]byte(internalServerErrorJSON))

+ 16 - 0
core/pkg/protocol/http_test.go

@@ -168,3 +168,19 @@ func TestHTTPProtocol_WriteResponse(t *testing.T) {
 	assert.Equal(t, 200, rw.Code)
 	assert.Contains(t, rw.Body.String(), "foo")
 }
+
+func TestHTTPProtocol_WriteData_Structure(t *testing.T) {
+	hp := HTTPProtocol{}
+	rw := httptest.NewRecorder()
+	data := map[string]string{"foo": "bar"}
+	hp.WriteData(rw, data)
+	assert.Equal(t, http.StatusOK, rw.Code)
+	assert.Equal(t, "application/json", rw.Header().Get("Content-Type"))
+
+	// Check the structure of the JSON response
+	body := rw.Body.String()
+	assert.Contains(t, body, "\"code\":200")
+	assert.Contains(t, body, "\"data\":{\"foo\":\"bar\"}")
+	assert.NotContains(t, body, "message")
+	assert.NotContains(t, body, "warning")
+}