LoginSignup
5
4

More than 5 years have passed since last update.

Goでnet/context.WithValueのKeyを他のパッケージと競合させない方法

Posted at

goにはnet/contextという便利なパッケージがあり
これはgoroutineのキャンセル処理などを実装するのに便利な構造をしています。

トークンなどの値を持たせることもできてその値を設定する方法はKey/Valueでやるのですが

ctx := context.WithValue("ip", "127.0.0.1")

という風にkeyを設定してしまうともしほかパッケージでもipというKeyがあれば競合を起こしてしまいます。

で、どうやって競合を起こさせないようにするかというと
keyになる変数のアドレスをkeyにします。

package ip

var ipKey string

func WithIP(ctx context.Context, ip string) context.Context {
  return context.WithValue(ctx, &ipKey, ip)
}

func FromContext(ctx context.Context) string {
  if v, ok := ctx.Value(&ipKey).(string); ok {
    return v
  }
  return ""
}
5
4
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
5
4