context.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package context
  2. import (
  3. "golang.org/x/net/context"
  4. "github.com/docker/docker/pkg/version"
  5. )
  6. const (
  7. // RequestID is the unique ID for each http request
  8. RequestID = "request-id"
  9. // APIVersion is the client's requested API version
  10. APIVersion = "api-version"
  11. )
  12. // Context is just our own wrapper for the golang 'Context' - mainly
  13. // so we can add our over version of the funcs.
  14. type Context struct {
  15. context.Context
  16. }
  17. // Background creates a new Context based on golang's default one.
  18. func Background() Context {
  19. return Context{context.Background()}
  20. }
  21. // WithValue will return a Context that has this new key/value pair
  22. // associated with it. Just uses the golang version but then wraps it.
  23. func WithValue(ctx Context, key, value interface{}) Context {
  24. return Context{context.WithValue(ctx, key, value)}
  25. }
  26. // RequestID is a utility func to make it easier to get the
  27. // request ID associated with this Context/request.
  28. func (ctx Context) RequestID() string {
  29. val := ctx.Value(RequestID)
  30. if val == nil {
  31. return ""
  32. }
  33. id, ok := val.(string)
  34. if !ok {
  35. // Ideally we shouldn't panic but we also should never get here
  36. panic("Context RequestID isn't a string")
  37. }
  38. return id
  39. }
  40. // Version is a utility func to make it easier to get the
  41. // API version string associated with this Context/request.
  42. func (ctx Context) Version() version.Version {
  43. val := ctx.Value(APIVersion)
  44. if val == nil {
  45. return version.Version("")
  46. }
  47. ver, ok := val.(version.Version)
  48. if !ok {
  49. // Ideally we shouldn't panic but we also should never get here
  50. panic("Context APIVersion isn't a version.Version")
  51. }
  52. return ver
  53. }