Created
October 18, 2018 08:30
-
-
Save iamacarpet/d49fdd3a788bae5b7d854d03fc578c0e to your computer and use it in GitHub Desktop.
App Engine Go 1.11 memcache proof
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
runtime: go111 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"time" | |
"github.com/gorilla/mux" | |
"google.golang.org/appengine" | |
"google.golang.org/appengine/log" | |
"google.golang.org/appengine/memcache" | |
) | |
func main() { | |
r := mux.NewRouter() | |
// Frontend pages. | |
r.HandleFunc("/", indexHandler) | |
http.Handle("/", r) | |
appengine.Main() | |
} | |
func indexHandler(w http.ResponseWriter, r *http.Request) { | |
ctx := appengine.NewContext(r) | |
data := map[string]string{ | |
"alpha": "beta", | |
} | |
myCodec := memcache.Codec{json.Marshal, json.Unmarshal} | |
retData := map[string]string{} | |
if _, err := myCodec.Get(ctx, "go111-test", &retData); err == nil { | |
http.Error(w, fmt.Sprintf("From Cache: %#v", retData), 200) | |
return | |
} else { | |
cacheItem := &memcache.Item{ | |
Key: "go111-test", | |
Object: data, | |
Expiration: time.Hour, | |
} | |
if err := myCodec.Set(ctx, cacheItem); err != nil { | |
log.Errorf(ctx, "GetSettingsValue: Cache Save Error (%s): %s", "go111-test", err) | |
} | |
http.Error(w, fmt.Sprintf("Set Cache: %#v", data), 200) | |
return | |
} | |
http.Error(w, "Permission Denied", 403) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment