github.com/newrelic/go-agent@v3.26.0+incompatible/context.go (about)

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