...

Source file src/github.com/okta/okta-jwt-verifier-golang/utils/cache.go

Documentation: github.com/okta/okta-jwt-verifier-golang/utils

     1  package utils
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  
     7  	"github.com/patrickmn/go-cache"
     8  )
     9  
    10  // Cacher is a read-only cache interface.
    11  //
    12  // Get returns the value associated with the given key.
    13  type Cacher interface {
    14  	Get(string) (interface{}, error)
    15  }
    16  
    17  type defaultCache struct {
    18  	cache  *cache.Cache
    19  	lookup func(string) (interface{}, error)
    20  	mutex  *sync.Mutex
    21  }
    22  
    23  func (c *defaultCache) Get(key string) (interface{}, error) {
    24  	c.mutex.Lock()
    25  	defer c.mutex.Unlock()
    26  
    27  	if value, found := c.cache.Get(key); found {
    28  		return value, nil
    29  	}
    30  
    31  	value, err := c.lookup(key)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	c.cache.SetDefault(key, value)
    37  	return value, nil
    38  }
    39  
    40  // defaultCache implements the Cacher interface
    41  var _ Cacher = (*defaultCache)(nil)
    42  
    43  // NewDefaultCache returns cache with a 5 minute expiration.
    44  func NewDefaultCache(lookup func(string) (interface{}, error)) (Cacher, error) {
    45  	return &defaultCache{
    46  		cache:  cache.New(5*time.Minute, 10*time.Minute),
    47  		lookup: lookup,
    48  		mutex:  &sync.Mutex{},
    49  	}, nil
    50  }
    51  

View as plain text