/
localcache.go
74 lines (59 loc) · 1.39 KB
/
localcache.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Created by Pavel Konovalov pkonovalov@orxagrid.com
//
// localcache is a local cache library
//
package localcache
import (
"hash/crc32"
"os"
"path"
)
type LocalCache struct {
ChecksumIEEE uint32
PathToCache string
IsChanged bool
}
func New(pathToCache string) *LocalCache {
return &LocalCache{
PathToCache: pathToCache,
ChecksumIEEE: 0,
IsChanged: false,
}
}
// Save configuration to local cache file
func (s *LocalCache) Save(profileData []byte) error {
if _, err := os.Stat(s.PathToCache); err == nil {
checksumIEEE := crc32.ChecksumIEEE(profileData)
if s.ChecksumIEEE == 0 {
_, _ = s.Load()
}
if checksumIEEE == s.ChecksumIEEE {
return nil
} else {
s.ChecksumIEEE = checksumIEEE
s.IsChanged = true
}
}
dir, _ := path.Split(s.PathToCache)
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.Mkdir(dir, 0755)
if err != nil {
return err
}
}
return os.WriteFile(s.PathToCache, profileData, 0644)
}
// Load from local cache
func (s *LocalCache) Load() ([]byte, error) {
buf, err := os.ReadFile(s.PathToCache)
if err != nil {
s.ChecksumIEEE = 0
return buf, err
}
s.ChecksumIEEE = crc32.ChecksumIEEE(buf)
return buf, err
}