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 memcache |
| 6 |
| 7 import ( |
| 8 "golang.org/x/net/context" |
| 9 ) |
| 10 |
| 11 type key int |
| 12 |
| 13 var ( |
| 14 memcacheKey key |
| 15 memcacheFilterKey key = 1 |
| 16 ) |
| 17 |
| 18 // Factory is the function signature for factory methods compatible with |
| 19 // SetFactory. |
| 20 type Factory func(context.Context) Interface |
| 21 |
| 22 // Filter is the function signature for a filter MC implementation. It |
| 23 // gets the current MC implementation, and returns a new MC implementation |
| 24 // backed by the one passed in. |
| 25 type Filter func(context.Context, Interface) Interface |
| 26 |
| 27 // GetUnfiltered gets gets the Interface implementation from context without |
| 28 // any of the filters applied. |
| 29 func GetUnfiltered(c context.Context) Interface { |
| 30 if f, ok := c.Value(memcacheKey).(Factory); ok && f != nil { |
| 31 return f(c) |
| 32 } |
| 33 return nil |
| 34 } |
| 35 |
| 36 // Get gets the current memcache implementation from the context. |
| 37 func Get(c context.Context) Interface { |
| 38 ret := GetUnfiltered(c) |
| 39 if ret == nil { |
| 40 return nil |
| 41 } |
| 42 for _, f := range getCurFilters(c) { |
| 43 ret = f(c, ret) |
| 44 } |
| 45 return ret |
| 46 } |
| 47 |
| 48 // SetFactory sets the function to produce Interface instances, as returned by |
| 49 // the Get method. |
| 50 func SetFactory(c context.Context, mcf Factory) context.Context { |
| 51 return context.WithValue(c, memcacheKey, mcf) |
| 52 } |
| 53 |
| 54 // Set sets the current Interface object in the context. Useful for testing |
| 55 // with a quick mock. This is just a shorthand SetFactory invocation to set |
| 56 // a factory which always returns the same object. |
| 57 func Set(c context.Context, mc Interface) context.Context { |
| 58 return SetFactory(c, func(context.Context) Interface { return mc }) |
| 59 } |
| 60 |
| 61 func getCurFilters(c context.Context) []Filter { |
| 62 curFiltsI := c.Value(memcacheFilterKey) |
| 63 if curFiltsI != nil { |
| 64 return curFiltsI.([]Filter) |
| 65 } |
| 66 return nil |
| 67 } |
| 68 |
| 69 // AddFilters adds Interface filters to the context. |
| 70 func AddFilters(c context.Context, filts ...Filter) context.Context { |
| 71 if len(filts) == 0 { |
| 72 return c |
| 73 } |
| 74 cur := getCurFilters(c) |
| 75 newFilts := make([]Filter, 0, len(cur)+len(filts)) |
| 76 newFilts = append(newFilts, getCurFilters(c)...) |
| 77 newFilts = append(newFilts, filts...) |
| 78 return context.WithValue(c, memcacheFilterKey, newFilts) |
| 79 } |
OLD | NEW |