-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonfile.go
63 lines (50 loc) · 1.37 KB
/
jsonfile.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
)
type jsonFile string
func newJsonFile(path string) (jsonFile, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
return jsonFile(path), fmt.Errorf("opening file %q: %v", path, err)
}
if err := f.Close(); err != nil {
return jsonFile(path), fmt.Errorf("closing file %q: %v", path, err)
}
return jsonFile(path), nil
}
func (jf jsonFile) read(data interface{}) error {
f, err := os.OpenFile(string(jf), os.O_RDONLY, 0644)
if err != nil {
return fmt.Errorf("opening file %q: %v", string(jf), err)
}
dec := json.NewDecoder(f)
if err := dec.Decode(data); err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("reading file %q: %v", string(jf), err)
}
return nil
}
func (jf jsonFile) write(data interface{}) error {
f, err := os.OpenFile(string(jf), os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("opening file %q: %v", string(jf), err)
}
buf := bytes.NewBuffer([]byte{})
enc := json.NewEncoder(buf)
enc.SetIndent("", "")
if err := enc.Encode(data); err != nil {
return fmt.Errorf("encoding json: %v", err)
}
if _, err := f.Write(buf.Bytes()); err != nil {
return fmt.Errorf("writing to %q: %v", string(jf), err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("closing file %q: %v", string(jf), err)
}
return nil
}