...

Source file src/github.com/gin-gonic/contrib/cache/inmemory.go

Documentation: github.com/gin-gonic/contrib/cache

     1  package cache
     2  
     3  import (
     4  	"github.com/robfig/go-cache"
     5  	"reflect"
     6  	"time"
     7  )
     8  
     9  type InMemoryStore struct {
    10  	cache.Cache
    11  }
    12  
    13  func NewInMemoryStore(defaultExpiration time.Duration) *InMemoryStore {
    14  	return &InMemoryStore{*cache.New(defaultExpiration, time.Minute)}
    15  }
    16  
    17  func (c *InMemoryStore) Get(key string, value interface{}) error {
    18  	val, found := c.Cache.Get(key)
    19  	if !found {
    20  		return ErrCacheMiss
    21  	}
    22  
    23  	v := reflect.ValueOf(value)
    24  	if v.Type().Kind() == reflect.Ptr && v.Elem().CanSet() {
    25  		v.Elem().Set(reflect.ValueOf(val))
    26  		return nil
    27  	}
    28  	return ErrNotStored
    29  }
    30  
    31  func (c *InMemoryStore) Set(key string, value interface{}, expires time.Duration) error {
    32  	// NOTE: go-cache understands the values of DEFAULT and FOREVER
    33  	c.Cache.Set(key, value, expires)
    34  	return nil
    35  }
    36  
    37  func (c *InMemoryStore) Add(key string, value interface{}, expires time.Duration) error {
    38  	err := c.Cache.Add(key, value, expires)
    39  	if err == cache.ErrKeyExists {
    40  		return ErrNotStored
    41  	}
    42  	return err
    43  }
    44  
    45  func (c *InMemoryStore) Replace(key string, value interface{}, expires time.Duration) error {
    46  	if err := c.Cache.Replace(key, value, expires); err != nil {
    47  		return ErrNotStored
    48  	}
    49  	return nil
    50  }
    51  
    52  func (c *InMemoryStore) Delete(key string) error {
    53  	if found := c.Cache.Delete(key); !found {
    54  		return ErrCacheMiss
    55  	}
    56  	return nil
    57  }
    58  
    59  func (c *InMemoryStore) Increment(key string, n uint64) (uint64, error) {
    60  	newValue, err := c.Cache.Increment(key, n)
    61  	if err == cache.ErrCacheMiss {
    62  		return 0, ErrCacheMiss
    63  	}
    64  	return newValue, err
    65  }
    66  
    67  func (c *InMemoryStore) Decrement(key string, n uint64) (uint64, error) {
    68  	newValue, err := c.Cache.Decrement(key, n)
    69  	if err == cache.ErrCacheMiss {
    70  		return 0, ErrCacheMiss
    71  	}
    72  	return newValue, err
    73  }
    74  
    75  func (c *InMemoryStore) Flush() error {
    76  	c.Cache.Flush()
    77  	return nil
    78  }
    79  

View as plain text