Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an object in memcache of GAE in Go

I want to store an object in GAE's memcache using Go. The gae documentation only shows how to store a []byte here: https://developers.google.com/appengine/docs/go/memcache/overview

Of course there are general ways to serialize an object into []byte, by which my task could be accomplished. But by reading the memcache reference, I found there is an "Object" in the memcache Item:

// Object is the Item's value for use with a Codec.
Object interface{}

That seems to be a built-in mechanic to store an object in memcache. However, the gae documentation did not provide a sample code.

Could anyone please show me an example? Thanks in advance

like image 559
Mingliang Avatar asked Nov 07 '12 06:11

Mingliang


1 Answers

OK, I just figured it out my self. The memcache pkg has two built-in Codec: gob and json. Just use one of them (or of course one can create his own Codec):

var in, out struct {I int;}

// Put in into memcache
in.I = 100 
item := &memcache.Item {
   Key: "TestKey",
   Object: in, 
}   
memcache.Gob.Set(c, item)  // error checking omitted for convenience

// retrieve the value
memcache.Gob.Get(c, "TestKey", &out)
fmt.Fprint(w, out)  // will print {100}

Thanks all

like image 191
Mingliang Avatar answered Sep 17 '22 01:09

Mingliang