Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. package cli
  2.  
  3. import (
  4. "encoding/json"
  5. "os"
  6. "path/filepath"
  7. "time"
  8.  
  9. "github.com/b4b4r07/gist/cli/gist"
  10. )
  11.  
  12. var Filename = "cache.json"
  13.  
  14. type Cache struct {
  15. Ready bool
  16. Path string
  17. TTL time.Duration
  18. Use bool
  19. Updated time.Time
  20. }
  21.  
  22. func NewCache() *Cache {
  23. var (
  24. ready bool
  25. updated time.Time
  26. )
  27. path := filepath.Join(Conf.Gist.Dir, Filename)
  28. fi, err := os.Stat(path)
  29. if err == nil {
  30. ready = true
  31. updated = fi.ModTime()
  32. }
  33. return &Cache{
  34. Ready: ready,
  35. Path: path,
  36. TTL: Conf.Gist.CacheTTL * time.Minute,
  37. Use: Conf.Gist.UseCache,
  38. Updated: updated,
  39. }
  40. }
  41.  
  42. func (c *Cache) Clear() error {
  43. return os.Remove(c.Path)
  44. }
  45.  
  46. func (c *Cache) Cache(items gist.Items) error {
  47. f, err := os.Create(c.Path)
  48. if err != nil {
  49. return err
  50. }
  51. return json.NewEncoder(f).Encode(&items)
  52. }
  53.  
  54. func (c *Cache) Load() (items gist.Items, err error) {
  55. f, err := os.Open(c.Path)
  56. if err != nil {
  57. return
  58. }
  59. defer f.Close()
  60. err = json.NewDecoder(f).Decode(&items)
  61. c.pseudoRun()
  62. return
  63. }
  64.  
  65. func (c *Cache) Expired() bool {
  66. if c.TTL == 0 {
  67. // if TTL is not set or equals zero,
  68. // it's regard as not caching
  69. return false
  70. }
  71. if !c.Ready {
  72. // if cache doesn't exist,
  73. // it's regard as expired
  74. return true
  75. }
  76. ttl := c.Updated.Add(c.TTL)
  77. return ttl.Before(time.Now())
  78. }
  79.  
  80. func (c *Cache) Available() bool {
  81. return c.Use && c.Ready && !c.Expired()
  82. }
  83.  
  84. func (c *Cache) pseudoRun() {
  85. time.Sleep(150 * time.Millisecond)
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement