From 0d5c1900601cc9a39fc0937acc7496df03d89726 Mon Sep 17 00:00:00 2001 From: dlcq Date: Sun, 27 Apr 2025 12:42:43 +0800 Subject: [PATCH 1/2] fix(transport): check if body is empty before get Content-Type decoder If body is empty, we may not hav Content-Type header, and will return a CODEC error Close #3653 --- transport/http/codec.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/transport/http/codec.go b/transport/http/codec.go index 9c026f833be..d57b729b037 100644 --- a/transport/http/codec.go +++ b/transport/http/codec.go @@ -59,10 +59,6 @@ func DefaultRequestQuery(r *http.Request, v any) error { // DefaultRequestDecoder decodes the request body to object. func DefaultRequestDecoder(r *http.Request, v any) error { - codec, ok := CodecForRequest(r, "Content-Type") - if !ok { - return errors.BadRequest("CODEC", fmt.Sprintf("unregister Content-Type: %s", r.Header.Get("Content-Type"))) - } data, err := io.ReadAll(r.Body) // reset body. @@ -74,6 +70,12 @@ func DefaultRequestDecoder(r *http.Request, v any) error { if len(data) == 0 { return nil } + + codec, ok := CodecForRequest(r, "Content-Type") + if !ok { + return errors.BadRequest("CODEC", fmt.Sprintf("unregister Content-Type: %s", r.Header.Get("Content-Type"))) + } + if err = codec.Unmarshal(data, v); err != nil { return errors.BadRequest("CODEC", fmt.Sprintf("body unmarshal %s", err.Error())) } From e400048e647912b0e98251e79e8d01c36460002e Mon Sep 17 00:00:00 2001 From: MikasaAkerman Date: Fri, 25 Jul 2025 15:03:34 +0800 Subject: [PATCH 2/2] Update codec.go check error --- transport/http/codec.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/transport/http/codec.go b/transport/http/codec.go index d57b729b037..7e8a2e62219 100644 --- a/transport/http/codec.go +++ b/transport/http/codec.go @@ -60,16 +60,15 @@ func DefaultRequestQuery(r *http.Request, v any) error { // DefaultRequestDecoder decodes the request body to object. func DefaultRequestDecoder(r *http.Request, v any) error { data, err := io.ReadAll(r.Body) - - // reset body. - r.Body = io.NopCloser(bytes.NewBuffer(data)) - if err != nil { return errors.BadRequest("CODEC", err.Error()) } if len(data) == 0 { return nil } + + // reset body. + r.Body = io.NopCloser(bytes.NewBuffer(data)) codec, ok := CodecForRequest(r, "Content-Type") if !ok {