context.go 791 B

12345678910111213141516171819202122232425262728293031
  1. // +build go1.7
  2. package newrelic
  3. import (
  4. "context"
  5. "net/http"
  6. )
  7. type contextKeyType struct{}
  8. var contextKey = contextKeyType(struct{}{})
  9. // NewContext returns a new Context that carries the provided transcation.
  10. func NewContext(ctx context.Context, txn Transaction) context.Context {
  11. return context.WithValue(ctx, contextKey, txn)
  12. }
  13. // FromContext returns the Transaction from the context if present, and nil
  14. // otherwise.
  15. func FromContext(ctx context.Context) Transaction {
  16. h, _ := ctx.Value(contextKey).(Transaction)
  17. return h
  18. }
  19. // RequestWithTransactionContext adds the transaction to the request's context.
  20. func RequestWithTransactionContext(req *http.Request, txn Transaction) *http.Request {
  21. ctx := req.Context()
  22. ctx = NewContext(ctx, txn)
  23. return req.WithContext(ctx)
  24. }