1
0

context.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // +build go1.7
  2. package newrelic
  3. import (
  4. "context"
  5. "net/http"
  6. "github.com/newrelic/go-agent/internal"
  7. )
  8. // NewContext returns a new Context that carries the provided transcation.
  9. func NewContext(ctx context.Context, txn Transaction) context.Context {
  10. return context.WithValue(ctx, internal.TransactionContextKey, txn)
  11. }
  12. // FromContext returns the Transaction from the context if present, and nil
  13. // otherwise.
  14. func FromContext(ctx context.Context) Transaction {
  15. h, _ := ctx.Value(internal.TransactionContextKey).(Transaction)
  16. if nil != h {
  17. return h
  18. }
  19. // If we couldn't find a transaction using
  20. // internal.TransactionContextKey, try with
  21. // internal.GinTransactionContextKey. Unfortunately, gin.Context.Set
  22. // requires a string key, so we cannot use
  23. // internal.TransactionContextKey in nrgin.Middleware. We check for two
  24. // keys (rather than turning internal.TransactionContextKey into a
  25. // string key) because context.WithValue will cause golint to complain
  26. // if used with a string key.
  27. h, _ = ctx.Value(internal.GinTransactionContextKey).(Transaction)
  28. return h
  29. }
  30. // RequestWithTransactionContext adds the transaction to the request's context.
  31. func RequestWithTransactionContext(req *http.Request, txn Transaction) *http.Request {
  32. ctx := req.Context()
  33. ctx = NewContext(ctx, txn)
  34. return req.WithContext(ctx)
  35. }
  36. func transactionFromRequestContext(req *http.Request) Transaction {
  37. var txn Transaction
  38. if nil != req {
  39. txn = FromContext(req.Context())
  40. }
  41. return txn
  42. }