1 Star 1 Fork 0

妙音 / oils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
get.go 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
妙音 提交于 2022-03-13 16:21 . style: lint
package level
import (
"bytes"
"encoding/gob"
"errors"
"reflect"
"github.com/syndtr/goleveldb/leveldb"
"google.golang.org/protobuf/proto"
)
// Get 读取数据.
func (p *Service) Get(key []byte, obj interface{}) bool {
data, err := p.DB.Get(key, nil)
if errors.Is(leveldb.ErrNotFound, err) {
return false
}
if err != nil {
panic(err)
}
if err := Bytes2Interface(data, obj); err != nil {
panic(err)
}
return true
}
// Bytes2Interface 字节码转换到接口.
func Bytes2Interface(data []byte, obj interface{}) error {
value := reflect.ValueOf(obj)
if value.Kind() != reflect.Ptr {
return ErrNotPtr
}
// protobuf
if m, ok := value.Interface().(proto.Message); ok {
return proto.Unmarshal(data, m)
}
// 加载器
if m, ok := value.Interface().(Loader); ok {
return m.Load(data)
}
// []byte
e := reflect.TypeOf(obj).Elem()
if e.Kind() == reflect.Slice && e.Elem().Kind() == reflect.Uint8 {
value.Elem().Set(reflect.ValueOf(data))
return nil
}
// god
decoder := gob.NewDecoder(bytes.NewBuffer(data))
return decoder.Decode(obj)
}
1
https://gitee.com/xuender/oils.git
git@gitee.com:xuender/oils.git
xuender
oils
oils
v1.1.23

搜索帮助