無料で使えるし、最近Google Compute Engineを使って面白かったので、Google App Engineを使って、少しコードを書いてみた。
Google App EngineのSDKがしっかりできていて、memcacheの開発もデバックもやりやすかった。
以下のようなコマンドをうつと、postの内容をコピーして、以下のコマンドでペーストできる
echo "test" | curl --data-binary @- --url http://toolbox-1080.appspot.com/copy/#{your key}
cat main.go | curl --data-binary @- --url http://toolbox-1080.appspot.com/copy/#{your key}
curl -s http://toolbox-1080.appspot.com/paste/#{your key}
書いたコード
package gaesample
import (
"fmt"
"strings"
"bytes"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"appengine"
"appengine/memcache"
)
func init() {
http.Handle("/", goji.DefaultMux)
goji.Get("/", handler)
goji.Post("/copy/:key", handler2)
goji.Get("/paste/:key", handler3)
}
func handler(c web.C, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", "Hello World")
}
func handler2(c web.C, w http.ResponseWriter, r *http.Request) {
ac := appengine.NewContext(r)
bufbody := new(bytes.Buffer)
bufbody.ReadFrom(r.Body)
body := bufbody.String()
set_key(ac, c.URLParams["key"], body)
}
func handler3(c web.C, w http.ResponseWriter, r *http.Request) {
ac := appengine.NewContext(r)
fmt.Fprintf(w, "%s", get_key(ac, c.URLParams["key"]))
}
func key(k string) string {
s := []string{k, "clipboard"}
return strings.Join(s, "_")
}
func set_key(c appengine.Context, k string, v string) {
item := &memcache.Item{
Key: key(k),
Value: []byte(v),
}
if err := memcache.Add(c, item); err == memcache.ErrNotStored {
if err := memcache.Set(c, item); err != nil {
c.Errorf("error setting item: %v", err)
}
} else if err != nil {
c.Errorf("error adding item: %v", err)
}
c.Infof("the value is %q", item.Value)
}
func get_key(c appengine.Context, k string) string {
if item, err := memcache.Get(c, key(k)); err == memcache.ErrCacheMiss {
c.Infof("item not in the cache")
return ""
} else if err != nil {
c.Errorf("error getting item: %v", err)
return ""
} else {
c.Infof("the value is %q", item.Value)
return string(item.Value)
}
}
memcacheの保存期間
- デフォルトでは、できるだけ長い期間キーを保存するようになっている
- もしメモリが圧迫されている場合は、新しい値が追加されたときに、最も最近使われていない値から削除される。
- 時間でも日付でも保存期間を設定できる
参考にしたサイト
「Google App EngineでGoのウェブアプリケーションをまず動かしてみる」を見ながら、App Engineのインストールとルーティングの設定を行った
http://qiita.com/taizo/items/845fcfc58cfd0b30020a
「golang環境設定」を見てgoライブラリのインストール
http://qiita.com/yanap/items/536b94425b20b1bfc46e
「Memcache Go API」
https://cloud.google.com/appengine/docs/go/memcache/
「Using Users Service」を見て、 App Engine Contextを理解
https://cloud.google.com/appengine/docs/go/gettingstarted/usingusers
メモ
Golangの変数とか関数とか[基礎]
http://qiita.com/mackiso/items/e435e154e3376a68dcca
「golang cast byte to string」
http://stackoverflow.com/questions/14230145/what-is-the-best-way-to-convert-byte-array-to-string
golang で最近お気に入りの WAF「Goji」Add Starmkt - Gojiの実装の参考に
http://mattn.kaoriya.net/software/lang/go/20141021134209.htm