Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,27 @@ type Meta struct {
// - errs: A slice of Error structs to describe issues. Use `nil` for successful responses.
// - meta: Optional metadata, such as pagination information. Use `nil` if not needed.
func SendResponse[T any](w http.ResponseWriter, code int, data T, errs []Error, meta *Meta) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Type", "application/json; charset=utf-8")

response := &Response[T]{
Data: data,
Errors: errs,
Meta: meta,
}

// Set the status code after encoding to ensure no issues with writing the response body
w.WriteHeader(code)

// Attempt to encode the response as JSON
var buffer bytes.Buffer
if err := json.NewEncoder(&buffer).Encode(response); err != nil {
log.Printf("Error writing response: %v", err)

errResponse := `{"errors":[{"code":500,"message":"Internal Server Error"}]}`
http.Error(w, errResponse, http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(&Response[T]{
Errors: []Error{{
Code: http.StatusInternalServerError,
Message: "Internal Server Error",
Details: err.Error(),
}},
})
return
}

Expand All @@ -75,6 +78,7 @@ func SendResponse[T any](w http.ResponseWriter, code int, data T, errs []Error,

// Write the encoded response to the ResponseWriter
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Printf("Error writing response: %v", err)
// Note: Cannot change status code here as headers are already sent
log.Printf("Failed to write response body (status=%d): %v", code, err)
}
}
2 changes: 1 addition & 1 deletion response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func Test_SendResponse(t *testing.T) {
}

assert.Equal(t, tt.expectedCode, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
assert.JSONEq(t, tt.expectedJSON, w.Body.String())
})
}
Expand Down
Loading