2024-01-27 14:36:14 +08:00
|
|
|
package convutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/vmihailenco/msgpack/v5"
|
|
|
|
)
|
|
|
|
|
|
|
|
type MsgpackConvert struct{}
|
|
|
|
|
2024-02-20 10:55:46 +08:00
|
|
|
func (MsgpackConvert) Enable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2024-11-04 14:26:17 +08:00
|
|
|
func (c MsgpackConvert) Encode(str string) (string, bool) {
|
2024-01-27 15:12:44 +08:00
|
|
|
var obj map[string]any
|
|
|
|
if err := json.Unmarshal([]byte(str), &obj); err == nil {
|
2024-11-04 14:26:17 +08:00
|
|
|
for k, v := range obj {
|
|
|
|
obj[k] = c.TryFloatToInt(v)
|
|
|
|
}
|
2024-01-27 15:12:44 +08:00
|
|
|
if b, err := msgpack.Marshal(obj); err == nil {
|
|
|
|
return string(b), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if b, err := msgpack.Marshal(str); err != nil {
|
|
|
|
return string(b), true
|
2024-01-27 14:36:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return str, false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (MsgpackConvert) Decode(str string) (string, bool) {
|
|
|
|
var decodedStr string
|
|
|
|
if err := msgpack.Unmarshal([]byte(str), &decodedStr); err == nil {
|
|
|
|
return decodedStr, true
|
|
|
|
}
|
|
|
|
|
2024-01-27 15:12:44 +08:00
|
|
|
var obj map[string]any
|
|
|
|
if err := msgpack.Unmarshal([]byte(str), &obj); err == nil {
|
|
|
|
if b, err := json.Marshal(obj); err == nil {
|
2024-02-20 10:55:46 +08:00
|
|
|
if len(b) >= 10 {
|
|
|
|
return string(b), true
|
|
|
|
}
|
2024-01-27 14:36:14 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return str, false
|
|
|
|
}
|
2024-11-04 14:26:17 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|