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 user |
| 6 |
| 7 import ( |
| 8 "golang.org/x/net/context" |
| 9 ) |
| 10 |
| 11 type key int |
| 12 |
| 13 var serviceKey key |
| 14 |
| 15 // Factory is the function signature for factory methods compatible with |
| 16 // SetFactory. |
| 17 type Factory func(context.Context) Interface |
| 18 |
| 19 // Get pulls the user service implementation from context or nil if it |
| 20 // wasn't set. |
| 21 func Get(c context.Context) Interface { |
| 22 if f, ok := c.Value(serviceKey).(Factory); ok && f != nil { |
| 23 return f(c) |
| 24 } |
| 25 return nil |
| 26 } |
| 27 |
| 28 // SetFactory sets the function to produce user.Interface instances, |
| 29 // as returned by the Get method. |
| 30 func SetFactory(c context.Context, f Factory) context.Context { |
| 31 return context.WithValue(c, serviceKey, f) |
| 32 } |
| 33 |
| 34 // Set sets the user service in this context. Useful for testing with a quick |
| 35 // mock. This is just a shorthand SetFactory invocation to set a factory which |
| 36 // always returns the same object. |
| 37 func Set(c context.Context, u Interface) context.Context { |
| 38 return SetFactory(c, func(context.Context) Interface { return u }) |
| 39 } |
OLD | NEW |