我正在尝试使用“appengine/memcache”将数据存储在缓存中,memcache.Item的Value字段是[]byte
如何将struct转换为[]byte以进行存储?
例如:
type Link struct {
Files []string
}
我正在尝试使用“appengine/memcache”将数据存储在缓存中,memcache.Item的Value字段是[]byte
如何将struct转换为[]byte以进行存储?
例如:
type Link struct {
Files []string
}
查看memcache.Codec类型,它可以用于转换memcache项。appengine/memcache包已经准备了两个编解码器,memcache.Gob和memcache.JSON。您可以使用这些编解码器来代替直接调用存储和检索缓存中的项,例如对于gob编码的项:
item := &memcache.Item{
Key: myCacheKey,
Object: &myLinkVar,
}
err := memcache.Gob.Set(context, item)
encoding/gob
包可能是您最好的选择。encoding/json
包。encoding/json
,则可以读取来自Go以外的语言的值。encoding/gob
,则会获得更快的速度。gob#Encoder.Encode
:package main
import (
"bytes"
"encoding/gob"
"fmt"
)
type link struct {
Files []string
}
func main() {
s := link{
[]string{"south", "north"},
}
b := new(bytes.Buffer)
gob.NewEncoder(b).Encode(s)
// "\x1d\xff\x81\x03\x01\x01\x04link\x01\xff\x82\x00\x01\x01\x01\x05Files\x01\xff\x84\x00\x00\x00\x16\xff\x83\x02\x01\x01\b[]string\x01\xff\x84\x00\x01\f\x00\x00\x11\xff\x82\x01\x02\x05south\x05north\x00"
fmt.Printf("%q\n", b)
}
context
是什么? - Jordan Feldstein