Skip to content

Commit 42dfb07

Browse files
committed
fix: adding chartset to the response
1 parent ee395bd commit 42dfb07

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

response.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,24 +49,27 @@ type Meta struct {
4949
// - errs: A slice of Error structs to describe issues. Use `nil` for successful responses.
5050
// - meta: Optional metadata, such as pagination information. Use `nil` if not needed.
5151
func SendResponse[T any](w http.ResponseWriter, code int, data T, errs []Error, meta *Meta) {
52-
w.Header().Set("Content-Type", "application/json")
52+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
5353

5454
response := &Response[T]{
5555
Data: data,
5656
Errors: errs,
5757
Meta: meta,
5858
}
5959

60-
// Set the status code after encoding to ensure no issues with writing the response body
61-
w.WriteHeader(code)
62-
6360
// Attempt to encode the response as JSON
6461
var buffer bytes.Buffer
6562
if err := json.NewEncoder(&buffer).Encode(response); err != nil {
6663
log.Printf("Error writing response: %v", err)
6764

68-
errResponse := `{"errors":[{"code":500,"message":"Internal Server Error"}]}`
69-
http.Error(w, errResponse, http.StatusInternalServerError)
65+
w.WriteHeader(http.StatusInternalServerError)
66+
_ = json.NewEncoder(w).Encode(&Response[T]{
67+
Errors: []Error{{
68+
Code: http.StatusInternalServerError,
69+
Message: "Internal Server Error",
70+
Details: err.Error(),
71+
}},
72+
})
7073
return
7174
}
7275

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

7679
// Write the encoded response to the ResponseWriter
7780
if _, err := w.Write(buffer.Bytes()); err != nil {
78-
log.Printf("Error writing response: %v", err)
81+
// Note: Cannot change status code here as headers are already sent
82+
log.Printf("Failed to write response body (status=%d): %v", code, err)
7983
}
8084
}

response_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ func Test_SendResponse(t *testing.T) {
6767
}
6868

6969
assert.Equal(t, tt.expectedCode, w.Code)
70-
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
70+
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
7171
assert.JSONEq(t, tt.expectedJSON, w.Body.String())
7272
})
7373
}

0 commit comments

Comments
 (0)