-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemfile.go
86 lines (71 loc) · 1.32 KB
/
memfile.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
package sdk
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
)
var MFileNotFound error = fmt.Errorf("file not found in memory")
var files map[string]*file
var mux sync.Mutex
type file struct {
mtime time.Time
content []byte
}
func init() {
files = make(map[string]*file)
}
func mlock() {
mux.Lock()
}
func munlock() {
mux.Unlock()
}
func mfileDownloadRequired(filename string) bool {
required := false
file, found := files[filename]
if !found {
required = true
} else {
mtime := file.mtime
now := time.Now()
diff := now.Sub(mtime)
if int(diff.Seconds()) >= UPDATE_INTERVAL {
required = true
}
}
return required
}
func downloadMfile(filename string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// read the file from response
responseContent, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
// Create the file
files[filename] = &file{
mtime: time.Now(),
content: responseContent,
}
return err
}
func parseMfile(filename string) (map[string]*Properties, error) {
items := make(map[string]*Properties)
file, found := files[filename]
if !found {
return nil, MFileNotFound
}
err := json.Unmarshal(file.content, &items)
if err != nil {
return nil, err
}
return items, nil
}