Skip to content

Commit

Permalink
fix: issue go-kratos#2782
Browse files Browse the repository at this point in the history
  • Loading branch information
shifengbin committed May 24, 2023
1 parent 96480c1 commit 650a009
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
21 changes: 20 additions & 1 deletion encoding/proto/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package proto

import (
"errors"
"google.golang.org/protobuf/proto"
"reflect"

"github.com/go-kratos/kratos/v2/encoding"
)
Expand All @@ -23,9 +25,26 @@ func (codec) Marshal(v interface{}) ([]byte, error) {
}

func (codec) Unmarshal(data []byte, v interface{}) error {
return proto.Unmarshal(data, v.(proto.Message))
pm, err := getProtoMessage(v)
if err != nil {
return err
}
return proto.Unmarshal(data, pm)
}

func (codec) Name() string {
return Name
}

func getProtoMessage(v interface{}) (proto.Message, error) {
if d, ok := v.(proto.Message); ok {
return d, nil
}
e := reflect.ValueOf(v)
if e.Kind() != reflect.Ptr {
return nil, errors.New("not proto message")
}

e = e.Elem()
return getProtoMessage(e.Interface())
}
58 changes: 58 additions & 0 deletions encoding/proto/proto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,61 @@ func TestCodec(t *testing.T) {
t.Errorf("Hobby should be %s, but got %s", res.Hobby, model.Hobby)
}
}

func TestCodec2(t *testing.T) {
c := new(codec)

model := testData.TestModel{
Id: 1,
Name: "kratos",
Hobby: []string{"study", "eat", "play"},
}

m, err := c.Marshal(&model)
if err != nil {
t.Errorf("Marshal() should be nil, but got %s", err)
}

var res testData.TestModel
rp := &res

err = c.Unmarshal(m, &rp)
if err != nil {
t.Errorf("Unmarshal() should be nil, but got %s", err)
}
if !reflect.DeepEqual(res.Id, model.Id) {
t.Errorf("ID should be %d, but got %d", res.Id, model.Id)
}
if !reflect.DeepEqual(res.Name, model.Name) {
t.Errorf("Name should be %s, but got %s", res.Name, model.Name)
}
if !reflect.DeepEqual(res.Hobby, model.Hobby) {
t.Errorf("Hobby should be %s, but got %s", res.Hobby, model.Hobby)
}
}

func Test_getProtoMessage(t *testing.T) {
p := &testData.TestModel{Id: 1}
type args struct {
v interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{name: "test1", args: args{v: &testData.TestModel{}}, wantErr: false},
{name: "test2", args: args{v: testData.TestModel{}}, wantErr: true},
{name: "test3", args: args{v: &p}, wantErr: false},
{name: "test4", args: args{v: 1}, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := getProtoMessage(tt.args.v)
if (err != nil) != tt.wantErr {
t.Errorf("getProtoMessage() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}

0 comments on commit 650a009

Please sign in to comment.