userid.go 580 B

1234567891011121314151617181920
  1. package userid
  2. import "context"
  3. type contextKey struct{}
  4. // NewContext returns a new context with the given user ID added to the
  5. // context.
  6. // TODO(hs): this doesn't seem to be used / set currently; implement
  7. // when/where it makes sense.
  8. func NewContext(ctx context.Context, userID string) context.Context {
  9. return context.WithValue(ctx, contextKey{}, userID)
  10. }
  11. // FromContext returns the user ID from the context if it exists
  12. // and is not empty.
  13. func FromContext(ctx context.Context) (string, bool) {
  14. v, ok := ctx.Value(contextKey{}).(string)
  15. return v, ok && v != ""
  16. }