1
0

ctx.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. gcontext "golang.org/x/net/context"
  6. )
  7. type apiKey int
  8. const (
  9. originTypeKey apiKey = iota
  10. userKey
  11. )
  12. // OriginType indicates where the gRPC request actually came from.
  13. //
  14. // e.g. Is it from REST gateway? Or somewhere else?
  15. type OriginType int
  16. // Known origins
  17. const (
  18. OriginTypeUnknown OriginType = iota
  19. OriginTypeREST
  20. )
  21. // NewOriginTypeContext creates a new ctx from the OriginType.
  22. func NewOriginTypeContext(ctx gcontext.Context, originType OriginType) context.Context {
  23. return context.WithValue(ctx, originTypeKey, originType)
  24. }
  25. // GetOriginTypeFromContext returns the OriginType from context.
  26. func GetOriginTypeFromContext(ctx gcontext.Context) OriginType {
  27. originType, ok := ctx.Value(originTypeKey).(OriginType)
  28. if !ok {
  29. return OriginTypeUnknown
  30. }
  31. return originType
  32. }
  33. // NewUsernameContext creates a new ctx from username and returns it.
  34. func NewUsernameContext(ctx gcontext.Context, username string) context.Context {
  35. return context.WithValue(ctx, userKey, username)
  36. }
  37. // GetUsernameFromContext returns the Username from context.
  38. func GetUsernameFromContext(ctx gcontext.Context) (string, error) {
  39. username, ok := ctx.Value(userKey).(string)
  40. if !ok {
  41. return "", fmt.Errorf("cannot get context value")
  42. }
  43. return username, nil
  44. }