直接在源代码中使用gobs,是否可能?

The*_*hat -1 performance go gob

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

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

我尝试了不同的东西,但我不能让它工作,因为基本上我不知道如何定义gob var(字节,[字节] ??)和解码器似乎期望一个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)
}
Run Code Online (Sandbox Code Playgroud)

现在我想将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)
Run Code Online (Sandbox Code Playgroud)

Jim*_*imB 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.
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例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)
}
Run Code Online (Sandbox Code Playgroud)

  • 只需将[]字节文字写入源代码即可.我之前使用过这个软件包来自动化它:https://github.com/jteeuwen/go-bindata (3认同)