-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
63 lines (54 loc) · 1.23 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
package domain
import (
"encoding/json"
"github.com/pkg/errors"
)
// State is an enum representing the state of a game.
type State int
const (
// Play indicates that gameplay is in progress,
Play State = iota + 1
// Win indicates that the game is complete and the client has won.
Win
// Lose indicates that the game is complete and the client has lost.
Lose
)
var (
stateToString = map[State]string{
Play: "play",
Win: "win",
Lose: "lose",
}
stringToState = map[string]State{}
)
func init() {
for k, v := range stateToString {
stringToState[v] = k
}
}
// String returns the string representation of the enum (play,win.lose)
func (s State) String() string {
return stateToString[s]
}
// UnmarshalJSON unmarshals JSON into an instance of the State enum.
func (s *State) UnmarshalJSON(b []byte) error {
var data string
err := json.Unmarshal(b, &data)
if err != nil {
return err
}
val, ok := stringToState[data]
if !ok {
return errors.New("Invalid state value")
}
*s = val
return nil
}
// MarshalJSON marshals an instance of State enum into JSON.
func (s *State) MarshalJSON() ([]byte, error) {
val, ok := stateToString[*s]
if !ok {
return nil, errors.New("Invalid state value")
}
return json.Marshal(val)
}