Skip to content

Commit

Permalink
fix: type mismatch when encoding to msgpack (#380)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiny-craft committed Nov 4, 2024
1 parent b0dfe34 commit ccb4bb8
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion backend/utils/convert/msgpack_convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ func (MsgpackConvert) Enable() bool {
return true
}

func (MsgpackConvert) Encode(str string) (string, bool) {
func (c MsgpackConvert) Encode(str string) (string, bool) {
var obj map[string]any
if err := json.Unmarshal([]byte(str), &obj); err == nil {
for k, v := range obj {
obj[k] = c.TryFloatToInt(v)
}
if b, err := msgpack.Marshal(obj); err == nil {
return string(b), true
}
Expand Down Expand Up @@ -43,3 +46,25 @@ func (MsgpackConvert) Decode(str string) (string, bool) {

return str, false
}

func (c MsgpackConvert) TryFloatToInt(input any) any {
switch val := input.(type) {
case map[string]any:
for k, v := range val {
val[k] = c.TryFloatToInt(v)
}
return val
case []any:
for i, v := range val {
val[i] = c.TryFloatToInt(v)
}
return val
case float64:
if val == float64(int(val)) {
return int(val)
}
return val
default:
return val
}
}

0 comments on commit ccb4bb8

Please sign in to comment.