Add a GetByKey method to Store

Without the ability to retrieve underlying items by key (instead of
the object passed to KeyFunc) it is impossible to build wrappers
around cache.Store that want to make decisions about keys, because
they would need to reconstruct the object passed to Get.

This allows retrieval by key, and makes sure Get(obj) uses it.
This commit is contained in:
Clayton Coleman
2015-02-01 14:55:45 -05:00
parent e335e2d3e2
commit 3ca23163ae
3 changed files with 25 additions and 10 deletions

View File

@@ -86,13 +86,18 @@ func (f *FIFO) List() []interface{} {
// Get returns the requested item, or sets exists=false.
func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {
id, err := f.keyFunc(obj)
key, err := f.keyFunc(obj)
if err != nil {
return nil, false, fmt.Errorf("couldn't create key for object: %v", err)
}
return f.GetByKey(key)
}
// GetByKey returns the requested item, or sets exists=false.
func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
item, exists = f.items[id]
item, exists = f.items[key]
return item, exists, nil
}