This commit is contained in:
2018-06-24 16:36:44 +02:00
parent 8ad4e70623
commit a4b74992c4
6 changed files with 127 additions and 12 deletions
+2 -5
View File
@@ -4,18 +4,15 @@ import (
"encoding/json"
"io/ioutil"
"os"
"reflect"
)
// Load will look for a given file. If it exists, it would unmarshal its
// contents into the given value. If the file does not exist, a supplied
// function would be called and its output would be written to a file.
func Load(val interface{}, filename string, fn func() interface{}) error {
func Load(val interface{}, filename string, fn func()) error {
_, err := os.Stat(filename)
if os.IsNotExist(err) {
out := fn()
reflect.ValueOf(val).Elem().Set(reflect.ValueOf(out))
fn()
body, err := json.Marshal(val)
if err != nil {
return err
+2 -2
View File
@@ -12,9 +12,9 @@ func TestFileCache(t *testing.T) {
var res int
var nCalled int
for i := 0; i < 10; i++ {
err := Load(&res, filename, func() interface{} {
err := Load(&res, filename, func() {
nCalled++
return exp
res = exp
})
if err != nil {
t.Fatalf("Error occurred while loading cache: %v", err)