func handler(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) // [START intro_2] // Create an Item item := &memcache.Item{ Key: "lyric", Value: []byte("Oh, give me a home"), } // Add the item to the memcache, if the key does not already exist if err := memcache.Add(ctx, item); err == memcache.ErrNotStored { log.Infof(ctx, "item with key %q already exists", item.Key) } else if err != nil { log.Errorf(ctx, "error adding item: %v", err) } // Change the Value of the item item.Value = []byte("Where the buffalo roam") // Set the item, unconditionally if err := memcache.Set(ctx, item); err != nil { log.Errorf(ctx, "error setting item: %v", err) } // Get the item from the memcache if item, err := memcache.Get(ctx, "lyric"); err == memcache.ErrCacheMiss { log.Infof(ctx, "item not in the cache") } else if err != nil { log.Errorf(ctx, "error getting item: %v", err) } else { log.Infof(ctx, "the lyric is %q", item.Value) } // [END intro_2] }
func index(res http.ResponseWriter, req *http.Request) { if req.URL.Path != "/" { http.NotFound(res, req) return } // set cookie id, _ := uuid.NewV4() cookie := &http.Cookie{ Name: "session-id", Value: id.String(), // Secure: true, HttpOnly: true, } http.SetCookie(res, cookie) // set memcache ctx := appengine.NewContext(req) item1 := memcache.Item{ Key: id.String(), Value: []byte("McLeod"), } memcache.Set(ctx, &item1) fmt.Fprint(res, "EVERYTHING SET ID:"+id.String()) }
func logout(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { ctx := appengine.NewContext(req) cookie, err := req.Cookie("session") // cookie is not set if err != nil { http.Redirect(res, req, "/", 302) return } // clear memcache sd := memcache.Item{ Key: cookie.Value, Value: []byte(""), Expiration: time.Duration(1 * time.Microsecond), } memcache.Set(ctx, &sd) // clear the cookie cookie.MaxAge = -1 http.SetCookie(res, cookie) // redirect http.Redirect(res, req, "/", 302) }
func getResources(w http.ResponseWriter, r *http.Request) *appError { //omitted code to get top, filter et cetera from the Request c := appengine.NewContext(r) h := fnv.New64a() h.Write([]byte("rap_query" + top + filter + orderby + skip)) cacheKey := h.Sum64() cv, err := memcache.Get(c, fmt.Sprint(cacheKey)) if err == nil { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Write(cv.Value) return nil } //omitting code that get resources from DataStore //cache this result with it's query as the key memcache.Set(c, &memcache.Item{ Key: fmt.Sprint(cacheKey), Value: result, }) //return the json version w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Write(result) return nil }
func index(res http.ResponseWriter, req *http.Request) { html := `` //Build Cookie id, _ := uuid.NewV4() cookie := &http.Cookie{ Name: "my-cookie", Value: id.String(), HttpOnly: true, } http.SetCookie(res, cookie) //Store memcache ctx := appengine.NewContext(req) item := memcache.Item{ Key: id.String(), Value: []byte("Matthew"), } memcache.Set(ctx, &item) //Get uuid from cookie cookieGet, _ := req.Cookie("my-cookie") if cookieGet != nil { html += `UUID from cookie: ` + cookieGet.Value + `<br>` } //Get uuid and value from memcache ctx = appengine.NewContext(req) item0, _ := memcache.Get(ctx, id.String()) if item0 != nil { html += `Value from Memcache using uuid: ` + string(item0.Value) + `<br>` } res.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(res, html) }
func createSession(res http.ResponseWriter, req *http.Request, user User) { ctx := appengine.NewContext(req) // SET COOKIE id, _ := uuid.NewV4() cookie := &http.Cookie{ Name: "session", Value: id.String(), Path: "/", // twenty minute session: MaxAge: 60 * 20, // UNCOMMENT WHEN DEPLOYED: // Secure: true, // HttpOnly: true, } http.SetCookie(res, cookie) // SET MEMCACHE session data (sd) json, err := json.Marshal(user) if err != nil { log.Errorf(ctx, "error marshalling during user creation: %v", err) http.Error(res, err.Error(), 500) return } sd := memcache.Item{ Key: id.String(), Value: json, } memcache.Set(ctx, &sd) }
func TestHook(t *testing.T) { body := `{"bucket": "dummy", "name": "path/obj"}` cacheKey := storage.CacheKey("dummy", "path/obj") req, _ := testInstance.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body)) ctx := appengine.NewContext(req) item := &memcache.Item{Key: cacheKey, Value: []byte("ignored")} if err := memcache.Set(ctx, item); err != nil { t.Fatal(err) } // must remove cached item res := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK) } if _, err := memcache.Get(ctx, cacheKey); err != memcache.ErrCacheMiss { t.Fatalf("memcache.Get(%q): %v; want ErrCacheMiss", cacheKey, err) } // cache misses must not respond with an error code req, _ = testInstance.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body)) res = httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK) } }
func (c cachingCloser) Close() error { go memcache.Set(c.ctx, &memcache.Item{ Key: c.key, Value: c.buf.Bytes(), }) return c.rc.Close() }
func (fi *FileInfo) createThumb(buffer *bytes.Buffer, c context.Context) { if imageTypes.MatchString(fi.Type) { src, _, err := image.Decode(bytes.NewReader(buffer.Bytes())) check(err) filter := gift.New(gift.ResizeToFit( THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT, gift.LanczosResampling, )) dst := image.NewNRGBA(filter.Bounds(src.Bounds())) filter.Draw(dst, src) buffer.Reset() bWriter := bufio.NewWriter(buffer) switch fi.Type { case "image/jpeg", "image/pjpeg": err = jpeg.Encode(bWriter, dst, nil) case "image/gif": err = gif.Encode(bWriter, dst, nil) default: err = png.Encode(bWriter, dst) } check(err) bWriter.Flush() thumbnailKey := fi.Key + thumbSuffix + filepath.Ext(fi.Name) item := &memcache.Item{ Key: thumbnailKey, Value: buffer.Bytes(), } err = memcache.Set(c, item) check(err) fi.ThumbnailKey = thumbnailKey } }
func handleIndex(res http.ResponseWriter, req *http.Request) { cookie, _ := req.Cookie("sessionid") if cookie == nil { id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "sessionid", Value: id.String(), } http.SetCookie(res, cookie) } ctx := appengine.NewContext(req) item, _ := memcache.Get(ctx, cookie.Value) if item == nil { m := map[string]string{ "email": "*****@*****.**", } bs, _ := json.Marshal(m) item = &memcache.Item{ Key: cookie.Value, Value: bs, } memcache.Set(ctx, item) } var m map[string]string json.Unmarshal(item.Value, &m) fmt.Fprintln(res, m) }
// Save will persist the passenger to Datastore and send it to Memcache. func (p *Passenger) Save(ctx context.Context) (*datastore.Key, error) { now := time.Now() key, err := p.AccessToken.SaveWithParent(ctx, p.UserKey) if err != nil { return nil, err } buf := new(bytes.Buffer) if err = gob.NewEncoder(buf).Encode(p); err != nil { return nil, err } item := &memcache.Item{ Key: key.Encode(), Value: buf.Bytes(), Expiration: p.AccessToken.Expiry.Sub(now) + 10*time.Second, } if err = memcache.Set(ctx, item); err != nil { return nil, err } return key, nil }
func getUser(req *http.Request, name string) model { ctx := appengine.NewContext(req) //Dank Memcache item, _ := memcache.Get(ctx, name) var m model if item != nil { err := json.Unmarshal(item.Value, &m) if err != nil { fmt.Printf("error unmarhsalling: %v", err) return model{} } } //Datastore var m2 model key := datastore.NewKey(ctx, "Users", name, 0, nil) err := datastore.Get(ctx, key, &m2) if err == datastore.ErrNoSuchEntity { return model{} } else if err != nil { return model{} } //Reset Dank Memecache bs := marshalModel(m2) item1 := memcache.Item{ Key: m2.Name, Value: bs, } memcache.Set(ctx, &item1) return m2 }
// PrimaryPublicCertificates returns primary's PublicCertificates. func PrimaryPublicCertificates(c context.Context, primaryURL string) (*PublicCertificates, error) { cacheKey := fmt.Sprintf("pub_certs:%s", primaryURL) var pubCerts []byte setCache := false item, err := memcache.Get(c, cacheKey) if err != nil { setCache = true if err != memcache.ErrCacheMiss { log.Warningf(c, "failed to get cert from cache: %v", err) } pubCerts, err = downloadCert(urlfetch.Client(c), primaryURL) if err != nil { log.Errorf(c, "failed to download cert: %v", err) return nil, err } } else { pubCerts = item.Value } pc := &PublicCertificates{} if err = json.Unmarshal(pubCerts, pc); err != nil { log.Errorf(c, "failed to unmarshal cert: %v %v", string(pubCerts), err) return nil, err } if setCache { err = memcache.Set(c, &memcache.Item{ Key: cacheKey, Value: pubCerts, Expiration: time.Hour, }) if err != nil { log.Warningf(c, "failed to set cert to cache: %v", err) } } return pc, nil }
// return a message based on its id func handleMessage(res http.ResponseWriter, req *http.Request) { ctx := appengine.NewContext(req) // get key from URL key := strings.SplitN(req.URL.Path, "/", 3)[2] // get item from memcache item, err := memcache.Get(ctx, key) if err != nil { http.NotFound(res, req) return } var secretKey [32]byte bs, err := hex.DecodeString(req.FormValue("secret")) if err != nil || len(bs) != 32 { http.NotFound(res, req) return } copy(secretKey[:], bs) msg, err := decrypt(string(item.Value), secretKey) if err != nil { http.NotFound(res, req) return } // if this is the first time the message is viewed if item.Flags == 0 { item.Expiration = 30 * time.Second item.Flags = 1 memcache.Set(ctx, item) } res.Write([]byte(msg)) }
func storeMemc(bs []byte, id string, req *http.Request) { ctx := appengine.NewContext(req) item1 := memcache.Item{ Key: id, Value: bs, } memcache.Set(ctx, &item1) }
// htmlCacheWrite saves bytes for given key. // Failures are ignored. func htmlCacheWrite(c context.Context, key string, data []byte, duration time.Duration) { cacheItem := &memcache.Item{ Key: key, Value: data, Expiration: duration, } _ = memcache.Set(c, cacheItem) }
func (mc *gaeMemcache) set(c context.Context, key string, data []byte, exp time.Duration) error { item := &memcache.Item{ Key: key, Value: data, Expiration: exp, } return memcache.Set(c, item) }
func memcacheStore(con *Context, key string, value []byte) error { i := &memcache.Item{ Key: key, Value: value, } err := memcache.Set(con.C, i) return err }
func putCache(req *http.Request, audio []byte) { c := appengine.NewContext(req) if err := memcache.Set(c, &memcache.Item{ Key: cacheKey(req), Value: audio, }); err != nil { c.Errorf("putCache: %v", err) } }
// Saves the userName given on memcache func saveUser(userName string, req *http.Request) { ctx := appengine.NewContext(req) user := memcache.Item{ Key: userName, Value: []byte(""), // The user name is important for us only. } err := memcache.Set(ctx, &user) logError(err) }
// Set saves a response to the cache as key. func (c *Cache) Set(key string, resp []byte) { item := &memcache.Item{ Key: cacheKey(key), Value: resp, } if err := memcache.Set(c.Context, item); err != nil { log.Errorf(c.Context, "error caching response: %v", err) } }
// cachedCerts fetches public certificates info from DefaultCertURI and // caches it for the duration specified in Age header of a response. func cachedCerts(c context.Context) (*certsList, error) { namespacedContext, err := appengine.Namespace(c, certNamespace) if err != nil { return nil, err } var certs *certsList _, err = memcache.JSON.Get(namespacedContext, DefaultCertURI, &certs) if err == nil { return certs, nil } // Cache miss or server error. // If any error other than cache miss, it's proably not a good time // to use memcache. var cacheResults = err == memcache.ErrCacheMiss if !cacheResults { log.Debugf(c, "%s", err.Error()) } log.Debugf(c, "Fetching provider certs from: %s", DefaultCertURI) resp, err := newHTTPClient(c).Get(DefaultCertURI) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, errors.New("Could not reach Cert URI or bad response.") } certBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } err = json.Unmarshal(certBytes, &certs) if err != nil { return nil, err } if cacheResults { expiration := certExpirationTime(resp.Header) if expiration > 0 { item := &memcache.Item{ Key: DefaultCertURI, Value: certBytes, Expiration: expiration, } err = memcache.Set(namespacedContext, item) if err != nil { log.Errorf(c, "Error adding Certs to memcache: %v", err) } } } return certs, nil }
func savePostsToCache(c context.Context, posts []reddit.Post, key string) error { encoded, err := json.Marshal(posts) if err != nil { return err } item := &memcache.Item{ Key: key, Value: encoded, } err = memcache.Set(c, item) return err }
func signout(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) o, _ := r.Cookie("session") sd := memcache.Item{ Key: o.Value, Value: []byte(""), Expiration: time.Duration(1 * time.Microsecond), } memcache.Set(c, &sd) o.MaxAge = -1 http.SetCookie(w, o) http.Redirect(w, r, "/", 302) }
func index(res http.ResponseWriter, req *http.Request) { _, error := req.Cookie("cook-o-matic") if error != nil { id := cookienidcreation(res, req) ctx := appengine.NewContext(req) item1 := memcache.Item{ Key: id, Value: []byte("Myke"), } memcache.Set(ctx, &item1) } }
// Stores any given interface using the key into memcache. func Store(key string, value interface{}, req *http.Request) error { ctx := appengine.NewContext(req) bs, err := json.Marshal(value) if err != nil { return err } item := memcache.Item{ Key: key, Value: bs, } err = memcache.Set(ctx, &item) return err }
func TestBasicAPICalls(t *testing.T) { // Only run the test if APPENGINE_DEV_APPSERVER is explicitly set. if os.Getenv("APPENGINE_DEV_APPSERVER") == "" { t.Skip("APPENGINE_DEV_APPSERVER not set") } resetEnv := internal.SetTestEnv() defer resetEnv() inst, err := NewInstance(nil) if err != nil { t.Fatalf("NewInstance: %v", err) } defer inst.Close() req, err := inst.NewRequest("GET", "http://example.com/page", nil) if err != nil { t.Fatalf("NewRequest: %v", err) } ctx := appengine.NewContext(req) it := &memcache.Item{ Key: "some-key", Value: []byte("some-value"), } err = memcache.Set(ctx, it) if err != nil { t.Fatalf("Set err: %v", err) } it, err = memcache.Get(ctx, "some-key") if err != nil { t.Fatalf("Get err: %v; want no error", err) } if g, w := string(it.Value), "some-value"; g != w { t.Errorf("retrieved Item.Value = %q, want %q", g, w) } type Entity struct{ Value string } e := &Entity{Value: "foo"} k := datastore.NewIncompleteKey(ctx, "Entity", nil) k, err = datastore.Put(ctx, k, e) if err != nil { t.Fatalf("datastore.Put: %v", err) } e = new(Entity) if err := datastore.Get(ctx, k, e); err != nil { t.Fatalf("datastore.Get: %v", err) } if g, w := e.Value, "foo"; g != w { t.Errorf("retrieved Entity.Value = %q, want %q", g, w) } }
func createUser(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { ctx := appengine.NewContext(req) NewUser := User{ Email: req.FormValue("email"), UserName: req.FormValue("userName"), Password: req.FormValue("password"), } key := datastore.NewKey(ctx, "Users", NewUser.UserName, 0, nil) key, err := datastore.Put(ctx, key, &NewUser) // this is the only error checking I added; any others on this page needed? if err != nil { log.Errorf(ctx, "error adding todo: %v", err) http.Error(res, err.Error(), 500) return } // SET COOKIE id, _ := uuid.NewV4() cookie := &http.Cookie{ Name: "session", Value: id.String(), Path: "/", // UNCOMMENT WHEN DEPLOYED: // Secure: true, // HttpOnly: true, } http.SetCookie(res, cookie) // SET MEMCACHE session data (sd) json, err := json.Marshal(NewUser) if err != nil { log.Errorf(ctx, "error marshalling during user creation: %v", err) http.Error(res, err.Error(), 500) return } sd := memcache.Item{ Key: id.String(), Value: json, } memcache.Set(ctx, &sd) // TEST memcache item, _ := memcache.Get(ctx, cookie.Value) if item != nil { log.Infof(ctx, "%s", string(item.Value)) } // redirect http.Redirect(res, req, "/", 302) }
func updateCache(ctx context.Context, key datastore.Key, item TodoItem) { var result = itemToJson(item) switch (*result).(type) { case Blob: blob := ([]byte)((*result).(Blob)) item := memcache.Item{ Key: key.String(), Value: blob, } memcache.Set(ctx, &item) // ignore errors... worst that can happen is we get a cache miss later default: break } }
func setMemCache(res http.ResponseWriter, req *http.Request, value string) { ctx := appengine.NewContext(req) item1 := memcache.Item{ Key: "Test", Value: []byte(value), } memcache.Set(ctx, &item1) item, _ := memcache.Get(ctx, "Test") if item != nil { fmt.Fprintln(res, string(item.Value)) } }