@@ -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.
5151func 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}
0 commit comments