Skip to content

Commit db022d2

Browse files
committed
fix: trying to solve a superfluous response call from json stream encoder
1 parent aa84cac commit db022d2

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

http/json/encoder.go

+12-6
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,18 @@ func (d *DefaultEncoder) Encode(
5353
)
5454
}
5555

56+
// Set the Content-Type header if it hasn't been set already
57+
if w.Header().Get("Content-Type") == "" {
58+
w.Header().Set("Content-Type", "application/json")
59+
}
60+
61+
// Write the HTTP status if it hasn't been written already
62+
if w.Header().Get("X-Status-Written") == "" {
63+
w.Header().Set("X-Status-Written", "true")
64+
w.WriteHeader(httpStatus)
65+
}
66+
5667
// Write the JSON body to the response
57-
w.WriteHeader(httpStatus)
58-
w.Header().Set("Content-Type", "application/json")
5968
_, err = w.Write(jsonBody)
60-
if err != nil {
61-
return err
62-
}
63-
return nil
69+
return err
6470
}

http/json/stream_encoder.go

+15-3
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,23 @@ func (d *DefaultStreamEncoder) Encode(
3131
body := response.Body(d.mode)
3232
httpStatus := response.HTTPStatus()
3333

34+
// Set the Content-Type header if it hasn't been set already
35+
if w.Header().Get("Content-Type") == "" {
36+
w.Header().Set("Content-Type", "application/json")
37+
}
38+
39+
// Write the HTTP status if it hasn't been written already
40+
if w.Header().Get("X-Status-Written") == "" {
41+
w.Header().Set("X-Status-Written", "true")
42+
w.WriteHeader(httpStatus)
43+
}
44+
3445
// Encode the JSON body
3546
if err = json.NewEncoder(w).Encode(body); err != nil {
47+
// Overwrite the status on error
48+
w.Header().Set("X-Status-Written", "true")
49+
w.WriteHeader(http.StatusInternalServerError)
50+
3651
_ = d.Encode(
3752
w,
3853
gonethttpstatusresponse.NewJSendDebugInternalServerError(
@@ -42,8 +57,5 @@ func (d *DefaultStreamEncoder) Encode(
4257
)
4358
return err
4459
}
45-
w.Header().Set("Content-Type", "application/json")
46-
w.WriteHeader(httpStatus)
47-
4860
return nil
4961
}

0 commit comments

Comments
 (0)