Merge pull request #2588 from mo3et/fix/gateway

feat: implement no gob encoder.
pull/2783/head
Monet Lee 2 months ago committed by GitHub
commit 9b94063d60
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -15,9 +15,6 @@
package msggateway
import (
"bytes"
"encoding/gob"
"github.com/openimsdk/tools/errs"
)
@ -33,19 +30,17 @@ func NewGobEncoder() *GobEncoder {
}
func (g *GobEncoder) Encode(data any) ([]byte, error) {
buff := bytes.Buffer{}
enc := gob.NewEncoder(&buff)
if err := enc.Encode(data); err != nil {
return nil, errs.WrapMsg(err, "GobEncoder.Encode failed", "action", "encode")
if b, ok := data.([]byte); ok {
return b, nil
}
return buff.Bytes(), nil
return nil, errs.New("Encoder.Encode failed", "action", "encode")
}
func (g *GobEncoder) Decode(encodeData []byte, decodeData any) error {
buff := bytes.NewBuffer(encodeData)
dec := gob.NewDecoder(buff)
if err := dec.Decode(decodeData); err != nil {
return errs.WrapMsg(err, "GobEncoder.Decode failed", "action", "decode")
if b, ok := decodeData.(*[]byte); ok {
*b = encodeData
return nil
}
return nil
return errs.New("Encoder.Decode failed", "action", "decode")
}

@ -0,0 +1,48 @@
package msggateway
import (
"testing"
)
func TestGobEncoder_Encode(t *testing.T) {
encoder := NewGobEncoder()
// 测试用例1: 编码 []byte 数据
inputData := []byte("test data")
encodedData, err := encoder.Encode(inputData)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if string(encodedData) != string(inputData) {
t.Fatalf("expected encoded data to be '%s', got '%s'", inputData, encodedData)
}
// 测试用例2: 编码非 []byte 数据
nonByteData := "string data"
_, err = encoder.Encode(nonByteData)
if err == nil {
t.Fatalf("expected an error when encoding non-byte data, got none")
}
}
func TestGobEncoder_Decode(t *testing.T) {
encoder := NewGobEncoder()
// 测试用例1: 解码到 []byte 数据
encodedData := []byte("test data")
var decodedData []byte
err := encoder.Decode(encodedData, &decodedData)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if string(decodedData) != string(encodedData) {
t.Fatalf("expected decoded data to be '%s', got '%s'", encodedData, decodedData)
}
// 测试用例2: 解码到非 []byte 数据
var nonByteData string
err = encoder.Decode(encodedData, &nonByteData)
if err == nil {
t.Fatalf("expected an error when decoding to non-byte data, got none")
}
}
Loading…
Cancel
Save