Commits

Miki Tebeka committed 2a40436

memcache

  • Participants
  • Parent commits 0553c3f

Comments (0)

Files changed (1)

File shortie/shortie.go

 import (
 	"appengine"
 	"appengine/datastore"
+	"appengine/memcache"
 	"appengine/user"
 	"appengine/taskqueue"
 	"fmt"
 	defer func() {
 		if err != nil {
 			params.Error = err.String()
-			ctx.Errorf("%s", err)
+			ctx.Errorf("%v", err)
 		}
 		homeTemplate.Execute(w, params)
 	}()
 	ctx := appengine.NewContext(r)
 	path := r.URL.Path[1:]
 
-	url, err := getURL(ctx, path)
-	if err != nil {
-		http.NotFound(w, r)
+	var longURL string
+
+	// Try memcache first and if not get URL from datastore and updatge memcache
+	if item, err := memcache.Get(ctx, path); err == memcache.ErrCacheMiss {
+		url, err1 := getURL(ctx, path)
+		if err1 != nil {
+			http.NotFound(w, r)
+			return
+		}
+		longURL = url.Long
+
+		item1 := &memcache.Item{
+			Key:   path,
+			Value: []byte(longURL),
+		}
+
+		if err1 := memcache.Set(ctx, item1); err1 != nil {
+			ctx.Errorf("memcache setting error: %v", err1)
+		}
+	} else if err != nil {
+		ctx.Errorf("memcache error - %s", err)
+		http.Error(w, err.String(), http.StatusInternalServerError)
 		return
+	} else { // Found in memcache
+		longURL = string(item.Value)
 	}
 
 	// Offload hit counter update to a task
 		return
 	}
 
-	http.Redirect(w, r, url.Long, http.StatusTemporaryRedirect)
+	http.Redirect(w, r, longURL, http.StatusTemporaryRedirect)
 }
 
 // Format time, used by homeTemplate