fix(transport/http): responseEncoder should not write any data when it 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
feat/error_middleware
张东龙 3 years ago committed by GitHub
parent 4e73384a9e
commit 60465ccca2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      transport/http/codec.go
  2. 22
      transport/http/codec_test.go

@ -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 {

@ -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),

Loading…
Cancel
Save