transport.go raw

   1  // Copyright 2014 The Go Authors. All rights reserved.
   2  // Use of this source code is governed by a BSD-style
   3  // license that can be found in the LICENSE file.
   4  
   5  package internal
   6  
   7  import (
   8  	"context"
   9  	"net/http"
  10  )
  11  
  12  // HTTPClient is the context key to use with [context.WithValue]
  13  // to associate an [*http.Client] value with a context.
  14  var HTTPClient ContextKey
  15  
  16  // ContextKey is just an empty struct. It exists so HTTPClient can be
  17  // an immutable public variable with a unique type. It's immutable
  18  // because nobody else can create a ContextKey, being unexported.
  19  type ContextKey struct{}
  20  
  21  func ContextClient(ctx context.Context) *http.Client {
  22  	if ctx != nil {
  23  		if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
  24  			return hc
  25  		}
  26  	}
  27  	return http.DefaultClient
  28  }
  29