Guest User

Untitled

a guest
Apr 23rd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. package handlers
  2.  
  3. import (
  4. "context"
  5. "sync"
  6. "time"
  7. )
  8.  
  9. type key int
  10.  
  11. var pool *sync.Pool
  12.  
  13. const (
  14. TraceIDKey = key(1)
  15. OpKey = key(2)
  16. )
  17.  
  18. type hcontext struct {
  19. traceID []byte
  20. op string
  21. deadline time.Time
  22. cancel context.CancelFunc
  23. ctx context.Context
  24. mu sync.Mutex
  25. }
  26.  
  27. func NewContext(traceID []byte, op string, deadline time.Time) (context.Context, context.CancelFunc) {
  28. c := pool.Get().(*hcontext)
  29. if c == nil {
  30. c = &hcontext{
  31. mu: sync.Mutex{},
  32. }
  33. }
  34. c.traceID = traceID
  35. c.op = op
  36. c.deadline = deadline
  37. c.ctx = nil
  38. c.cancel = nil
  39. return c, func() {
  40. if c.cancel != nil {
  41. c.cancel()
  42. }
  43. pool.Put(c)
  44. }
  45. }
  46.  
  47. func (c *hcontext) Deadline() (time.Time, bool) {
  48. return c.deadline, true
  49. }
  50.  
  51. func (c *hcontext) Done() <-chan struct{} {
  52. return c.context().Done()
  53. }
  54.  
  55. func (c *hcontext) context() context.Context {
  56. c.mu.Lock()
  57. defer c.mu.Unlock()
  58. ctx := context.Background()
  59. ctx = context.WithValue(ctx, TraceIDKey, c.traceID)
  60. ctx = context.WithValue(ctx, OpKey, c.op)
  61. ctx, c.cancel = context.WithDeadline(ctx, c.deadline)
  62. c.ctx = ctx
  63. return ctx
  64. }
  65.  
  66. func (c *hcontext) Err() error {
  67. return c.context().Err()
  68. }
  69.  
  70. func (c *hcontext) Value(key interface{}) interface{} {
  71. switch key {
  72. case TraceIDKey:
  73. return c.traceID
  74. case OpKey:
  75. return c.op
  76. }
  77. return nil
  78. }
Add Comment
Please, Sign In to add comment