I'm trying to use "appengine/memcache" to store data in the cache, memcache.Item's Value field is []byte
how do I convert a struct to []byte for storing it ?
for example:
type Link struct {
Files []string
}
The most straightforward but pretty inefficient method to convert a struct into a byte slice is to marshal it to JSON/YAML or any other markup language format.
A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
See the memcache.Codec type, this can be used to convert memcache items. The appengine/memcache package has two codecs already prepared, memcache.Gob and memcache.JSON. You use these codecs instead of the direct call to store and retrieve items from the cache, for example like this for a gob encoded item:
item := &memcache.Item{
Key: myCacheKey,
Object: &myLinkVar,
}
err := memcache.Gob.Set(context, item)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With