context.go 1.0 KB

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