-
Notifications
You must be signed in to change notification settings - Fork 0
/
settings.go
88 lines (68 loc) · 1.65 KB
/
settings.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package settings
import (
"crypto/aes"
"crypto/rand"
"encoding/binary"
"io"
"github.com/golang/glog"
"github.com/rokeller/bart/domain"
"google.golang.org/protobuf/proto"
)
type Settings struct {
salt []byte
}
// NewSettings generates new settings with a new salt etc.
func NewSettings() Settings {
salt := make([]byte, aes.BlockSize)
if _, err := rand.Read(salt); nil != err {
glog.Exitf("Failed to generate random salt: %v", err)
}
return Settings{
salt: salt,
}
}
func NewSettingsFromReader(r io.ReadCloser) (Settings, error) {
settingsSize := make([]byte, 4)
_, err := io.ReadFull(r, settingsSize)
if nil != err {
return Settings{}, err
}
dataSize := binary.LittleEndian.Uint32(settingsSize)
data := make([]byte, dataSize)
_, err = io.ReadFull(r, data)
if nil != err {
return Settings{}, err
}
settings := &domain.Settings{}
if err := proto.Unmarshal(data, settings); nil != err {
glog.Errorf("Failed to unmarshal settings: %v", err)
return Settings{}, err
}
return Settings{
salt: settings.Salt,
}, nil
}
func (s Settings) Salt() []byte {
return s.salt
}
func (s Settings) Write(w io.Writer) error {
settings := &domain.Settings{
Salt: s.salt,
}
data, err := proto.Marshal(settings)
if nil != err {
glog.Errorf("Failed to marshal settings: %v", err)
return err
}
settingsSize := make([]byte, 4)
binary.LittleEndian.PutUint32(settingsSize, uint32(len(data)))
if _, err := w.Write(settingsSize); nil != err {
glog.Errorf("Failed to write settings size: %v", err)
return err
}
if _, err := w.Write(data); nil != err {
glog.Errorf("Failed to write settings data: %v", err)
return err
}
return nil
}