LoginSignup
0
0

More than 3 years have passed since last update.

[Go言語] ContextのWithValueのkeyについて

Last updated at Posted at 2020-04-28

ContextのWithValueでのワーニング

ContextのWithValueで以下のようにstringを使おうとすると、should not use basic type string as key in context.WithValueのwarningが出てしまいます。

ctx = context.WithValue(ctx, "user", user)

調べてみたところ、WithValueを使っている場所で好き勝手にkeyを設定すると、key名が被ってしまう可能性があるのというエラーのようでした。とても親切ですね。

解決策

utilを作成して、そこでWithValueの処理を一括して行うように修正をしました。
ポイントは以下の4点になります

  1. typeでvalueKeyを宣言する
  2. constで必要なvalueKeyを宣言する
  3. WithValueの関数の引数をvalueKeyにする
package ctxutil

import "context"

const (
    // ポイント②
    LayoutKey valueKey = iota
    UserKey
)

// ポイント①
type valueKey int

// ポイント③
func WithValue(parent context.Context, key valueKey, v interface{}) context.Context {
    return context.WithValue(parent, key, v)
}

呼び出し

呼び出しは以下のように書けます。

ctx = ctxutil.WithValue(ctx, ctxutil.UserKey, user)

以上です!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0