-
Notifications
You must be signed in to change notification settings - Fork 0
/
deserialize_json.go
64 lines (56 loc) · 1.63 KB
/
deserialize_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
60
61
62
63
64
package serialization
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"github.com/relvox/iridescence_go/errors"
"github.com/relvox/iridescence_go/validation"
)
func UnmarshalJson[T any](data []byte) (T, error) {
var t T
err := json.Unmarshal(data, &t)
if err != nil {
return *new(T), fmt.Errorf("unmarshal json: %w", err)
}
if v, ok := any(t).(validation.Validable); ok {
return errors.WrapCommaError(t, v.Validate())("unmarshal json: validate")
}
return t, nil
}
func UnmarshalJsonFile[T any](path string) (T, error) {
bs, err := os.ReadFile(path)
if err != nil {
return *new(T), fmt.Errorf("unmarshal json file: read file '%s': %w", path, err)
}
return errors.WrapCommaError(UnmarshalJson[T](bs))("unmarshal json file '%s'", path)
}
func UnmarshalJsonFS[T any](f fs.FS, path string) (T, error) {
bs, err := fs.ReadFile(f, path)
if err != nil {
return *new(T), fmt.Errorf("unmarshal json fs file: read fs file '%s': %w", path, err)
}
return errors.WrapCommaError(UnmarshalJson[T](bs))("unmarshal json` fs file '%s'", path)
}
func MustUnmarshalJson[T any](data []byte) T {
var t T
err := json.Unmarshal(data, &t)
if err != nil {
panic(fmt.Errorf("must unmarshal json: %w", err))
}
return t
}
func MustUnmarshalJsonFile[T any](path string) T {
bs, err := os.ReadFile(path)
if err != nil {
panic(fmt.Errorf("unmarshal json file: read file '%s': %w", path, err))
}
return MustUnmarshalJson[T](bs)
}
func MustUnmarshalJsonFS[T any](f fs.FS, path string) T {
bs, err := fs.ReadFile(f, path)
if err != nil {
panic(fmt.Errorf("unmarshal json fs file: read fs file '%s': %w", path, err))
}
return MustUnmarshalJson[T](bs)
}