-1

我想知道是否可以直接在源代码中(例如在函数中)使用 gob 编码数据。原因是通过不必访问磁盘来获取 gob 文件来提高性能。我知道 memcached、redis 和朋友。我不需要 TTL 或任何其他花哨的功能。只是在内存中映射。数据将在“设置”/构建过程中被编码并转储到源代码中,以便在运行时只需要“解码”它。

Go 应用程序基本上将用作小型只读嵌入式数据库。我可以使用 json 来做到这一点(基本上用原始 json 声明一个 var),但我想会有性能损失,所以我想知道 gob 是否有可能。

我尝试了不同的东西,但我不能让它工作,因为基本上我不知道如何定义 gob var (byte, [bytes] ?? ) 并且解码器似乎期待一个 io.Reader 所以在消费之前在这一天里,我决定至少问问你们这些家伙是否可以这样做。

悲惨的尝试:

var test string
test = "hello"

p := new(bytes.Buffer)
e := gob.NewEncoder(p)
e.Encode(test)
ers := ioutil.WriteFile("test.gob", p.Bytes(), 0600)
if ers != nil {
    panic(ers)
}

现在我想把 test.gob 添加到一个函数中。如我所见, test.gob 的源代码如下^H^L^@^Ehello

var test string

var b bytes.Buffer

b = byte("^H^L^@^Ehello")

de := gob.NewDecoder(b.Bytes())

er := de.Decode(&test)
if er != nil {
    fmt.Printf("cannot decode")
    panic(er)
}

fmt.Fprintf(w, test)
4

2 回答 2

5

将数据存储在字节片中。它是原始数据,这就是您从文件中读取它的方式。

您的 gob 文件中的字符串不是“^H^L^@^Ehello”!这就是您的编辑器显示不可打印字符的方式。

b = byte("^H^L^@^Ehello")
// This isn't the string equivalent of hello, 
// and you want a []byte, not byte. 
// It should look like 

b = []byte("\b\f\x00\x05hello")
// However, you already declared b as bytes.Buffer, 
// so this assignment isn't valid anyway.


de := gob.NewDecoder(b.Bytes())
// b.Bytes() returns a []byte, you want to read the buffer itself.

这是一个工作示例http://play.golang.org/p/6pvt2ctwUq

func main() {
    buff := &bytes.Buffer{}
    enc := gob.NewEncoder(buff)
    enc.Encode("hello")

    fmt.Printf("Encoded: %q\n", buff.Bytes())

    // now if you wanted it directly in your source
    encoded := []byte("\b\f\x00\x05hello")
    // or []byte{0x8, 0xc, 0x0, 0x5, 0x68, 0x65, 0x6c, 0x6c, 0x6f}

    de := gob.NewDecoder(bytes.NewReader(encoded))

    var test string
    er := de.Decode(&test)
    if er != nil {
        fmt.Println("cannot decode", er)
        return
    }

    fmt.Println("Decoded:", test)
}
于 2014-03-08T14:07:21.900 回答
1

例如,

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "io"
)

func writeGOB(data []byte) (io.Reader, error) {
    buf := new(bytes.Buffer)
    err := gob.NewEncoder(buf).Encode(data)
    return buf, err
}

func readGOB(r io.Reader) ([]byte, error) {
    var data []byte
    err := gob.NewDecoder(r).Decode(&data)
    return data, err
}

func main() {
    var in = []byte("hello")
    fmt.Println(string(in))
    r, err := writeGOB(in)
    if err != nil {
        fmt.Println(err)
        return
    }
    out, err := readGOB(r)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(out))
}

输出:

hello
hello
于 2014-03-08T14:34:44.847 回答