如何解决使用Gob解码时缓冲区错误中的额外数据-Golang
我正在用gob解码从称为“ bitcask”的键/值数据库中获取的几个对象。 当我尝试将它们全部解码时,我从gob解码器中收到“缓冲区中的额外数据”错误,但仅针对数据库中添加的第一个元素,并且仅在我已至少获取它们一次之后。
我在做什么错了?
// Just the nest of all the bugs.
type Nest struct {
buf bytes.Buffer
dec *gob.Decoder
enc *gob.Encoder
db *bitcask.Bitcask
sync.Mutex
}
// Saves the bug into the nest.
func (n *Nest) Put(id int64,b Bug) error {
n.Lock()
defer n.Unlock()
if err := n.enc.Encode(b); err != nil {
return err
}
defer n.buf.Reset()
return n.db.Put(itosl(id),n.buf.Bytes())
}
// Retrieves a bug from the nest.
func (n *Nest) Get(id int64) (Bug,error) {
var bg Bug
b,err := n.db.Get(itosl(id))
if err != nil {
return bg,err
}
n.Lock()
defer n.Unlock()
if _,err = n.buf.Write(b); err != nil {
return bg,err
}
defer n.buf.Reset()
return bg,n.dec.Decode(&bg) // error extra data in buffer
}
注意:每次调用API端点时,都会为数据库中的每个ID调用“获取”功能。
我正在编码/解码的结构如下:
type Comment struct {
Date int64 `json:"date"`
Text string `json:"text"`
Author string `json:"author"`
}
type Bug struct {
Id int64 `json:"id"`
Body string `json:"body"`
Open bool `json:"open"`
Tags []string `json:"tags"`
Date int64 `json:"date"`
Comments []Comment `json:"comments"`
Author string `json:"author"`
}
另外,当我尝试使用新的解码器并在每次调用“ Get”函数时进行缓冲(正如我在类似问题的答案中所看到的),解码操作会导致以下错误:{{1} }。
有关完整的源代码,请参考此链接: https://github.com/NicoNex/ladybug
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。