Skip to content

Commit a6dcc8b

Browse files
committed
fix(http): handle JSON encoding errors in responder
1 parent 3bbc7d4 commit a6dcc8b

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

pkg/gofr/http/responder.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package http
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"errors"
67
"net/http"
@@ -53,9 +54,18 @@ func (r Responder) Respond(data any, err error) {
5354
r.w.Header().Set("Content-Type", "application/json")
5455
}
5556

57+
var buf bytes.Buffer
58+
encoder := json.NewEncoder(&buf)
59+
60+
if err := encoder.Encode(resp); err != nil {
61+
// JSON encoding failed (e.g. NaN, Inf, unsupported types)
62+
http.Error(r.w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
63+
return
64+
}
65+
5666
r.w.WriteHeader(statusCode)
67+
_, _ = r.w.Write(buf.Bytes())
5768

58-
_ = json.NewEncoder(r.w).Encode(resp)
5969
}
6070

6171
// handleSpecialResponseTypes handles special response types that bypass JSON encoding.

0 commit comments

Comments
 (0)