Skip to content

Commit

Permalink
fix: ParseJsonBody error when request has []byte field zeromicro#4450
Browse files Browse the repository at this point in the history
--bug=4450
  • Loading branch information
studyzy committed Nov 26, 2024
1 parent cad2439 commit d7b78d6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
11 changes: 10 additions & 1 deletion core/mapping/unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package mapping

import (
"encoding"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -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
}

Expand Down
20 changes: 20 additions & 0 deletions rest/httpx/requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httpx

import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit d7b78d6

Please sign in to comment.