fix: incorrect formatted data when save with msgpack

This commit is contained in:
Lykin 2024-01-27 15:12:44 +08:00
parent f09ee89a96
commit fd58357a04
1 changed files with 12 additions and 9 deletions

View File

@ -1,7 +1,6 @@
package convutil package convutil
import ( import (
"bytes"
"encoding/json" "encoding/json"
"github.com/vmihailenco/msgpack/v5" "github.com/vmihailenco/msgpack/v5"
) )
@ -9,11 +8,15 @@ import (
type MsgpackConvert struct{} type MsgpackConvert struct{}
func (MsgpackConvert) Encode(str string) (string, bool) { func (MsgpackConvert) Encode(str string) (string, bool) {
var err error var obj map[string]any
var buf bytes.Buffer if err := json.Unmarshal([]byte(str), &obj); err == nil {
enc := msgpack.NewEncoder(&buf) if b, err := msgpack.Marshal(obj); err == nil {
if err = enc.EncodeString(str); err == nil { return string(b), true
return buf.String(), true }
}
if b, err := msgpack.Marshal(str); err != nil {
return string(b), true
} }
return str, false return str, false
@ -25,9 +28,9 @@ func (MsgpackConvert) Decode(str string) (string, bool) {
return decodedStr, true return decodedStr, true
} }
var decodedObj map[string]any var obj map[string]any
if err := msgpack.Unmarshal([]byte(str), &decodedObj); err == nil { if err := msgpack.Unmarshal([]byte(str), &obj); err == nil {
if b, err := json.Marshal(decodedObj); err == nil { if b, err := json.Marshal(obj); err == nil {
return string(b), true return string(b), true
} }
} }