1

我正在使用从名为“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 调用“Get”函数。

我正在编码/解码的结构如下:

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”函数时尝试使用新的解码器和缓冲区时(正如我在对类似问题的回答中看到的那样),解码操作会导致以下错误:gob: unknown type id or corrupted data.

完整源代码参考此链接: https ://github.com/NicoNex/ladybug

4

0 回答 0