Upload
mokelab
View
779
Download
1
Embed Size (px)
Citation preview
Go 1.7のContextをnet/httpで使ってみた
Go conference 2017@fkm / @mokelab
● スマホアプリを書いたり● レクチャーしたり● 情報発信したり
何やってるの?
● グッズもあるよ♪
何やってるの?
Contextとは?
リクエストのキャンセル用
インターフェース
は、@lestrratさんがきっと説明済み。。。
そのリクエストに関するデータを
保存できる
WithValue()
c := r.Context()c = context.WithValue( c, "name", // キー "moke", // 値)
いれる
c := r.Context()name := c.Value("name")// nameは// interface{} or nil
とってくる
// interface{}なので。。。name, ok := c.Value("name").(string)if !ok { // エラーレスポンス}
とってくる
現実の課題
func myHandler(w, r) { contentType := ... auth := ... accept := ... // メインの処理}
とあるHandler
func getUserHandler(w, r) { contentType := ... auth := ... accept := ... // メインの処理}
別のHandler
前処理
こんな風にしたい
Request
前処理メインの
処理
エラー
インターフェースが変わる(><)
Contextの出番
Request
前処理メインの
処理
インターフェースはそのまま
Context
ライブラリ書いてみた
イメージ
Request
メインの処理
Context
取得書き込み
リクエストに関する情報だけ
いれるべし
// GET /users/{id} 用handler := hop.Operations( hop.GetContentType, hop.GetPathString("id"),)(mainHandler)
コードは?
// getter関数で// 前処理の結果を取ってくるfunc mainHandler(w, r) { contentType := hop.ContentType(r.Context()) ... }
コードは?
handler := hop.Operations( hop.GetContentType, hop.GetPathString("id"),)(mainHandler)
何がいいの?
関数!
intとかstringとかいれると怒られるよ
$ golintmain.go:10:6: should not use basic type string as key in context.WithValue
WithValueのキー
別名をつければいいよ
type cKey stringconst keyID cKey = "id"
c = context.WithValue(c, keyID, "id1234")
WithValueのキー
素敵なContextライフを!