cache.go 669 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package service
  2. import (
  3. "time"
  4. )
  5. // Cache simple cache
  6. type Cache struct {
  7. d int64 // duration seconds
  8. mc map[string]interface{} // map cache
  9. snap time.Time
  10. }
  11. // NewCache new cache
  12. func NewCache(d int64) *Cache {
  13. c := &Cache{
  14. d: d,
  15. mc: make(map[string]interface{}),
  16. snap: time.Now(),
  17. }
  18. return c
  19. }
  20. // Get ...
  21. func (c *Cache) Get(key string) (val interface{}) {
  22. c.check()
  23. return c.mc[key]
  24. }
  25. // Set ...
  26. func (c *Cache) Set(key string, val interface{}) {
  27. c.check()
  28. c.mc[key] = val
  29. }
  30. func (c *Cache) check() {
  31. if int64(time.Since(c.snap).Seconds()) > c.d {
  32. c.mc = make(map[string]interface{})
  33. c.snap = time.Now()
  34. }
  35. }