github.com/qiniu/go-sdk/v7@v7.27.0/auth/context.go (about)

     1  package auth
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  // MacContextKey 是用户的密钥信息
     8  // context.Context中的键值不应该使用普通的字符串, 有可能导致命名冲突
     9  type macContextKey struct{}
    10  
    11  // tokenTypeKey 是签名算法类型key
    12  type tokenTypeKey struct{}
    13  
    14  // WithCredentials 返回一个包含密钥信息的context
    15  func WithCredentials(ctx context.Context, cred *Credentials) context.Context {
    16  	if ctx == nil {
    17  		ctx = context.Background()
    18  	}
    19  	return context.WithValue(ctx, macContextKey{}, cred)
    20  }
    21  
    22  // WithCredentialsType 返回一个context, 保存了密钥信息和token类型
    23  func WithCredentialsType(ctx context.Context, cred *Credentials, t TokenType) context.Context {
    24  	ctx = WithCredentials(ctx, cred)
    25  	return context.WithValue(ctx, tokenTypeKey{}, t)
    26  }
    27  
    28  // CredentialsFromContext 从context获取密钥信息
    29  func CredentialsFromContext(ctx context.Context) (cred *Credentials, t TokenType, ok bool) {
    30  	cred, ok = ctx.Value(macContextKey{}).(*Credentials)
    31  	t, yes := ctx.Value(tokenTypeKey{}).(TokenType)
    32  	if !yes {
    33  		t = TokenQBox
    34  	}
    35  	return
    36  }