-
Notifications
You must be signed in to change notification settings - Fork 34
/
persist.go
54 lines (46 loc) · 1.08 KB
/
persist.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
// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package index
import (
"encoding/json"
"io"
"os"
)
// PersistStore is a type which defines a simple persistence store.
type PersistStore string
// NewPersistStore creates a new PersistStore. By default PersistStore uses
// JSON to persist data.
func NewPersistStore(path string, data interface{}) (PersistStore, error) {
f, err := os.Open(path)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
f, err = os.Create(path)
if err != nil {
return "", err
}
}
defer f.Close()
dec := json.NewDecoder(f)
err = dec.Decode(data)
if err != nil && err != io.EOF {
return "", err
}
return PersistStore(path), nil
}
// Persist writes the data to the underlying data store, overwriting any previous data.
func (p PersistStore) Persist(data interface{}) error {
f, err := os.Create(string(p))
if err != nil {
return err
}
defer f.Close()
b, err := json.Marshal(data)
if err != nil {
return err
}
_, err = f.Write(b)
return err
}