序列化 反序列化
为了 获得的数据能是我们想要的数据 类型需要对数据进行 序列化 和反序列化
序列化
在redis 存值的时候需要否则 有 slice 的可能就无法解析
func Serialization(value interface{
}) ([]byte, error) {
if bytes, ok := value.([]byte); ok {
return bytes, nil
}
switch v := reflect.ValueOf(value); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return []byte(strconv.FormatInt(v.Int(), 10)), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return []byte(strconv.FormatUint(v.Uint(), 10)), nil
case reflect.Map:
}
k, err := json.Marshal(value)
return k, err
}
反序列化
获取redis 中想要的数据类型 slice map struct 等
func Deserialization(byt []byte, ptr interface{
}) (err error) {
if bytes, ok := ptr.(*[]byte); ok {
*bytes = byt
return
}
if v := reflect.ValueOf(ptr); v.Kind() == reflect.Ptr {
switch p := v.Elem(); p.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var i int64
i, err = strconv.ParseInt(string(byt), 10, 64)
if err != nil {
fmt.Printf("Deserialization: failed to parse int '%s': %s", string(byt), err)
} else {
p.SetInt(i)
}
return
case reflect.Uint, reflect.Uint8, reflect.Uint16,