OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 // Package urlfetch provides a way for an application to get http.RoundTripper |
| 6 // that can make outbound HTTP requests. If used for https:// protocol, will |
| 7 // always validate SSL certificates. |
| 8 package urlfetch |
| 9 |
| 10 import ( |
| 11 "errors" |
| 12 "net/http" |
| 13 |
| 14 "golang.org/x/net/context" |
| 15 ) |
| 16 |
| 17 type key int |
| 18 |
| 19 var serviceKey key |
| 20 |
| 21 // Factory is the function signature for factory methods compatible with |
| 22 // SetFactory. |
| 23 type Factory func(context.Context) http.RoundTripper |
| 24 |
| 25 // Get pulls http.RoundTripper implementation from context or panics if it |
| 26 // wasn't set. Use SetFactory(...) or Set(...) in unit tests to mock |
| 27 // the round tripper. |
| 28 func Get(c context.Context) http.RoundTripper { |
| 29 if f, ok := c.Value(serviceKey).(Factory); ok && f != nil { |
| 30 return f(c) |
| 31 } |
| 32 panic(errors.New("no http.RoundTripper is set in context")) |
| 33 } |
| 34 |
| 35 // SetFactory sets the function to produce http.RoundTripper instances, |
| 36 // as returned by the Get method. |
| 37 func SetFactory(c context.Context, f Factory) context.Context { |
| 38 return context.WithValue(c, serviceKey, f) |
| 39 } |
| 40 |
| 41 // Set sets the current http.RoundTripper object in the context. Useful for |
| 42 // testing with a quick mock. This is just a shorthand SetFactory invocation |
| 43 // to set a factory which always returns the same object. |
| 44 func Set(c context.Context, r http.RoundTripper) context.Context { |
| 45 return SetFactory(c, func(context.Context) http.RoundTripper { return r
}) |
| 46 } |
OLD | NEW |