Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(transport/http): responseEncoder should not write any data when it need to write nil #1945

Merged
merged 3 commits into from
Apr 27, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions transport/http/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ func DefaultRequestDecoder(r *http.Request, v interface{}) error {

// DefaultResponseEncoder encodes the object to the HTTP response.
func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error {
if v == nil {
_, err := w.Write(nil)
return err
}
codec, _ := CodecForRequest(r, "Accept")
data, err := codec.Marshal(v)
if err != nil {
Expand Down
22 changes: 22 additions & 0 deletions transport/http/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,28 @@ func TestDefaultResponseEncoderWithError(t *testing.T) {
}
}

func TestDefaultResponseEncoderEncodeNil(t *testing.T) {
w := &mockResponseWriter{StatusCode: 204, header: make(nethttp.Header)}
req1 := &nethttp.Request{
Header: make(nethttp.Header),
}
req1.Header.Set("Content-Type", "application/json")

err := DefaultResponseEncoder(w, req1, nil)
if err != nil {
t.Errorf("expected no error, got %v", err)
}
if !reflect.DeepEqual("", w.Header().Get("Content-Type")) {
t.Errorf("expected empty string, got %v", w.Header().Get("Content-Type"))
}
if !reflect.DeepEqual(204, w.StatusCode) {
t.Errorf("expected %v, got %v", 204, w.StatusCode)
}
if w.Data != nil {
t.Errorf("expected nil, got %v", w.Data)
}
}

func TestCodecForRequest(t *testing.T) {
req1 := &nethttp.Request{
Header: make(nethttp.Header),
Expand Down