Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 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 golang.org/x/net/context's |
| 13 | // WithValue function 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 | var appengineClientHook func(context.Context) *http.Client |
| 22 | |
| 23 | func ContextClient(ctx context.Context) *http.Client { |
| 24 | if ctx != nil { |
| 25 | if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { |
| 26 | return hc |
| 27 | } |
| 28 | } |
| 29 | if appengineClientHook != nil { |
| 30 | return appengineClientHook(ctx) |
| 31 | } |
| 32 | return http.DefaultClient |
| 33 | } |