-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
59 lines (47 loc) · 920 Bytes
/
json.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
package configkit
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
type jsonRW[TData any] struct {
}
func newJsonRW[TData any]() StructReaderWriter[TData] {
return &jsonRW[TData]{}
}
func (jrw *jsonRW[TData]) Read(path string) (*TData, error) {
var (
bytes []byte
model = new(TData)
err error
)
if !filepath.IsLocal(path) {
return nil, fmt.Errorf("given path is out of project root '%s'", path)
}
path = filepath.Join("./", filepath.Clean(path))
bytes, err = os.ReadFile(path)
if err != nil {
return nil, err
}
err = json.Unmarshal(bytes, model)
if err != nil {
return nil, err
}
return model, nil
}
func (jrw *jsonRW[TData]) Write(path string, configStruct TData) error {
var (
bytes []byte
err error
)
bytes, err = json.Marshal(configStruct)
if err != nil {
return err
}
err = os.WriteFile(path, bytes, 0600)
if err != nil {
return err
}
return nil
}