Created
April 6, 2017 12:29
-
-
Save timakin/5c79adbf6d439f4104f7654b83e10a82 to your computer and use it in GitHub Desktop.
App structについて⑵
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
// ⑵構造体の要素として、context使わなきゃいけない要素は持てるのか | |
// appengineを使う場合、context.Contextの拡張の、appengine/contextをセットして、 | |
// Log表示やDBへの接続等を行いますが、そういった要素はどう管理するべきか、 | |
// というかそもそも共通の構造体みたいなものに持てないのでは?...という質問でした。 | |
// (これはappengine特有かもしれないので、摑みどころがなければ、スルーしていただいて結構です。) | |
// 以下実際のappengineのコード例(リクエストハンドラ直下)です。 | |
import "google.golang.org/appengine/datastore" | |
func handle(w http.ResponseWriter, r *http.Request) { | |
// ctxをラップする | |
ctx := appengine.NewContext(r) | |
// redisのkeyみたいなものを作成して、 | |
k := datastore.NewKey(ctx, "Entity", "stringID", 0, nil) | |
e := new(Entity) | |
// 以下のように、データへのアクセスをしますが、 | |
// ここではcontextが必要です。 | |
if err := datastore.Get(ctx, k, e); err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
old := e.Value | |
e.Value = r.URL.Path | |
if _, err := datastore.Put(ctx, k, e); err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
w.Header().Set("Content-Type", "text/plain; charset=utf-8") | |
fmt.Fprintf(w, "old=%q\nnew=%q\n", old, e.Value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment