From d7b78d63f386ba432c11e969fe24de0b0ea8656a Mon Sep 17 00:00:00 2001 From: DevinZeng Date: Tue, 26 Nov 2024 18:39:05 +0800 Subject: [PATCH] fix: ParseJsonBody error when request has []byte field #4450 --bug=4450 --- core/mapping/unmarshaler.go | 11 ++++++++++- rest/httpx/requests_test.go | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index b4fb356ee319..96c542b14504 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -2,6 +2,7 @@ package mapping import ( "encoding" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -737,7 +738,15 @@ func (u *Unmarshaler) processFieldTextUnmarshaler(fieldType reflect.Type, value return true, tval.UnmarshalText(mv) } } - + //[]byte + if fieldType.Kind() == reflect.Slice && fieldType.Elem().Kind() == reflect.Uint8 { + b, err := base64.StdEncoding.DecodeString(mapValue.(string)) + if err != nil { + return false, err + } + value.SetBytes(b) + return true, nil + } return false, nil } diff --git a/rest/httpx/requests_test.go b/rest/httpx/requests_test.go index 437b9a136fb5..8faf0d3fa01e 100644 --- a/rest/httpx/requests_test.go +++ b/rest/httpx/requests_test.go @@ -2,6 +2,7 @@ package httpx import ( "bytes" + "encoding/json" "errors" "net/http" "net/http/httptest" @@ -350,6 +351,25 @@ func TestParseJsonBody(t *testing.T) { assert.Equal(t, "apple", v[0].Name) assert.Equal(t, 18, v[0].Age) }) + t.Run("bytes field", func(t *testing.T) { + type v struct { + Signature []byte `json:"signature,optional"` + } + v1 := v{ + Signature: []byte{0x01, 0xff, 0x00}, + } + body, _ := json.Marshal(v1) + t.Logf("body:%s", string(body)) + r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(body))) + r.Header.Set(ContentType, header.JsonContentType) + var v2 v + err := ParseJsonBody(r, &v2) + if assert.NoError(t, err) { + assert.Greater(t, len(v2.Signature), 0) + } + t.Logf("%x", v2.Signature) + assert.EqualValues(t, v1.Signature, v2.Signature) + }) } func TestParseRequired(t *testing.T) {