-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.go
86 lines (73 loc) · 1.57 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* Copyright (C) 2018 Aurélien Chabot <[email protected]>
*
* SPDX-License-Identifier: MIT
*/
package main
import (
"encoding/gob"
"fmt"
"log"
"os"
"path"
)
import "github.com/atrox/homedir"
const cachePath = "~/.cache/transmission-rss.gob"
// Cache handle a key value storage
type Cache struct {
path string
data map[string]string
}
// NewCache return a new Cache object
func NewCache() *Cache {
cache := Cache{}
path, err := homedir.Expand(cachePath)
if err != nil {
log.Fatal(err)
}
cache.path = path
err = readGob(cache.path, &cache.data)
if err != nil {
log.Println("Empty cache")
cache.data = make(map[string]string)
}
return &cache
}
// Get return the value associated with the key or an error if the
// cache doesn't contains the key
func (c *Cache) Get(key string) (string, error) {
v, ok := c.data[key]
if !ok {
return "", fmt.Errorf("no match found for key %s", key)
}
return v, nil
}
// Set set in the cache the given value with the given key
func (c *Cache) Set(key string, value string) {
c.data[key] = value
err := writeGob(c.path, c.data)
if err != nil {
log.Println(err)
}
}
func writeGob(filePath string, object interface{}) error {
os.Mkdir(path.Dir(filePath), 0744)
file, err := os.Create(filePath)
if err != nil {
log.Fatal(err)
}
encoder := gob.NewEncoder(file)
encoder.Encode(object)
file.Close()
return err
}
func readGob(filePath string, object interface{}) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
decoder := gob.NewDecoder(file)
err = decoder.Decode(object)
file.Close()
return err
}