-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
65 lines (53 loc) · 1.43 KB
/
state.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
65
package muse
import (
"bytes"
"compress/gzip"
"encoding/gob"
"fmt"
"os"
"reflect"
)
// PersistToFile save object state to file
func PersistToFile(name string, obj any) error {
var (
b bytes.Buffer
zw = gzip.NewWriter(&b)
objType = reflect.TypeOf(obj).Elem()
enc = gob.NewEncoder(zw)
err error
)
err = enc.Encode(obj)
if err != nil {
_ = zw.Close()
return fmt.Errorf("kratos failed to store state of %s to file %s: %w", objType, name, err)
}
err = zw.Close()
if err != nil {
return fmt.Errorf("kratos failed to store state of %s to file %s: %w", objType, name, err)
}
err = os.WriteFile(name, b.Bytes(), 0666)
if err != nil {
return fmt.Errorf("kratos failed to store state of %s to file %s: %w", objType, name, err)
}
return nil
}
// RestoreFromFile restore object state from file
func RestoreFromFile(name string, obj any) error {
objType := reflect.TypeOf(obj).Elem()
data, err := os.ReadFile(name)
if err != nil {
return fmt.Errorf("kratos failed to restore state of %s from file %s: %w", objType, name, err)
}
zr, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return fmt.Errorf("kratos failed to restore state of %s from file %s: %w", objType, name, err)
}
defer func() {
_ = zr.Close()
}()
err = gob.NewDecoder(zr).Decode(obj)
if err != nil {
return fmt.Errorf("kratos failed to restore state of %s from file %s: %w", objType.Name(), name, err)
}
return nil
}