Skip to content

Commit

Permalink
fix(transport/http): responseEncoder should not write any data when i…
Browse files Browse the repository at this point in the history
…t need to write nil (#1945)

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

* test(transport/http): adjust the test of response encoder encode nil value

* fix(transport/http): remove content-type setting
  • Loading branch information
Donglong committed Apr 27, 2022
1 parent 4e73384 commit 60465cc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
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

0 comments on commit 60465cc

Please sign in to comment.