Thread-safe caching with maps
Caching is sometimes necessary to attain an acceptable performance. The idea is to reuse values that have been computed or retrieved before. A map is a natural choice for caching such values but, due to their nature, caches are usually shared among multiple goroutines and you must be careful when using them.
Simple cache
This is a simple cache with a get/put method to retrieve objects from the cache and put elements into it.
How to do it...
To cache values that are accessible with a key, use a structure with a map and mutex:
type ObjectCache struct {
   mutex sync.RWMutex
   values map[string]*Object
}
// Initialize and return a new instance of the cache
func NewObjectCache() *ObjectCache {
    return &ObjectCache{
        values: make(map[string]*Object),
    }
} Direct access to cache internals should be prevented to ensure...