-
Notifications
You must be signed in to change notification settings - Fork 0
/
votepack.go
66 lines (55 loc) · 1.35 KB
/
votepack.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
package main
import (
"bigw-voting/util"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
// Votepack represents a JSON-encoded pack of the candidates + trustee votes
type Votepack struct {
Candidates []string
TrusteeVotes []string
}
// NewVotepackFromFile opens a file and loads the Votepack
func NewVotepackFromFile(filename string) *Votepack {
f, err := os.Open(filename)
if err != nil {
panic(fmt.Errorf("unable to open votepack: %v", err))
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
panic(fmt.Errorf("unable to read votepack: %v", err))
}
return NewVotepackFromJSON(b)
}
// NewVotepackFromJSON unmarshalls JSON into a Votepack
func NewVotepackFromJSON(marshalled []byte) *Votepack {
v := new(Votepack)
err := json.Unmarshal(marshalled, v)
if err != nil {
panic(fmt.Errorf("unable to parse votepack: %v", err))
}
return v
}
// Export returns the JSON representation of the Votepack
func (v *Votepack) Export() []byte {
b, err := json.Marshal(v)
if err != nil {
util.Errorf("error while exporting votepack: %v", err)
}
return b
}
// ExportToFile exports the Votepack to a file
func (v *Votepack) ExportToFile(filename string) {
f, err := os.Create(filename)
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.Write(v.Export())
if err != nil {
util.Errorf("error while exporting votepack to file: %v", err)
}
}