-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
83 lines (61 loc) · 1.43 KB
/
main.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
package main
import (
"encoding/json"
"log"
"slices"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type BroadcastRequest struct {
maelstrom.MessageBody
Message int `json:"message"`
}
type TopologyRequest struct {
maelstrom.MessageBody
Topology map[string][]string `json:"topology"`
}
type ReadResponse struct {
maelstrom.MessageBody
Messages []int `json:"messages"`
}
var node = maelstrom.NewNode()
func main() {
messages := []int{}
node.Handle("broadcast", func(msg maelstrom.Message) error {
var body BroadcastRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
if !slices.Contains(messages, body.Message) {
messages = append(messages, body.Message)
}
resBody := maelstrom.MessageBody{
Type: "broadcast_ok",
}
return node.Reply(msg, resBody)
})
node.Handle("broadcast_ok", func(msg maelstrom.Message) error {
return nil
})
node.Handle("read", func(msg maelstrom.Message) error {
resBody := ReadResponse{
MessageBody: maelstrom.MessageBody{
Type: "read_ok",
},
Messages: messages,
}
return node.Reply(msg, resBody)
})
node.Handle("topology", func(msg maelstrom.Message) error {
var body TopologyRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
resBody := maelstrom.MessageBody{
Type: "topology_ok",
}
return node.Reply(msg, resBody)
})
if err := node.Run(); err != nil {
log.Fatal(err)
}
}