context.go 459 B

12345678910111213141516171819202122232425
  1. package protocol
  2. import (
  3. "context"
  4. )
  5. type key int
  6. const (
  7. userKey key = iota
  8. )
  9. // ContextWithUser returns a context combined with a User.
  10. func ContextWithUser(ctx context.Context, user *User) context.Context {
  11. return context.WithValue(ctx, userKey, user)
  12. }
  13. // UserFromContext extracts a User from the given context, if any.
  14. func UserFromContext(ctx context.Context) *User {
  15. v := ctx.Value(userKey)
  16. if v == nil {
  17. return nil
  18. }
  19. return v.(*User)
  20. }