Total Lines | 43 |
Duplicated Lines | 0 % |
Coverage | 31.25% |
Changes | 0 |
1 | package utils |
||
2 | |||
3 | import ( |
||
4 | "encoding/json" |
||
5 | "io/ioutil" |
||
6 | "path/filepath" |
||
7 | ) |
||
8 | |||
9 | // FileGetContents returns the content of the given file |
||
10 | func FileGetContents(filePath string) string { |
||
11 | 1 | fileText, err := ioutil.ReadFile(filePath) |
|
12 | |||
13 | 1 | if err != nil { |
|
14 | 1 | print("File reading error\n") |
|
15 | 1 | return "" |
|
16 | } |
||
17 | |||
18 | 1 | return string(fileText) |
|
19 | } |
||
20 | |||
21 | func getAbsPathToStorageFile(filename string) string { |
||
22 | dirPath, err := filepath.Abs("./storage") |
||
23 | HandleError(err, "Dir path error in getAbsPathToStorageFile function") |
||
24 | return dirPath + "/" + filename |
||
25 | } |
||
26 | |||
27 | // GetCached returns cache |
||
28 | func GetCached(fileName string) []string { |
||
29 | var oldSlice []string |
||
30 | |||
31 | oldContext := FileGetContents(getAbsPathToStorageFile(fileName)) |
||
32 | err := json.Unmarshal([]byte(oldContext), &oldSlice) |
||
33 | |||
34 | HandleError(err, "Unmarshal method returned error") |
||
35 | |||
36 | return oldSlice |
||
37 | } |
||
38 | |||
39 | // PutIntoCache insert given slice into a file in JSON |
||
40 | func PutIntoCache(items []string, fileName string) { |
||
41 | file, _ := json.MarshalIndent(items, "", " ") |
||
42 | err := ioutil.WriteFile(getAbsPathToStorageFile(fileName), file, 0644) |
||
43 | HandleError(err, "Can't write to a file storage/"+fileName) |
||
44 | } |
||
45 |