Skip to content

Instantly share code, notes, and snippets.

@andrewarrow
Created February 22, 2023 20:33
Show Gist options
  • Save andrewarrow/e55640675ddb4bf3126ebe8ad9ef696b to your computer and use it in GitHub Desktop.
Save andrewarrow/e55640675ddb4bf3126ebe8ad9ef696b to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"log"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
func main() {
list := []int{}
n := maelstrom.NewNode()
n.Handle("broadcast", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
list = append(list, int(body["message"].(float64)))
for _, node := range n.NodeIDs() {
if node == n.ID() {
continue
}
n.Send(node, body)
}
body = map[string]any{}
body["type"] = "broadcast_ok"
return n.Reply(msg, body)
})
n.Handle("read", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
body["type"] = "read_ok"
body["messages"] = list
return n.Reply(msg, body)
})
n.Handle("topology", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
body = map[string]any{}
body["type"] = "topology_ok"
return n.Reply(msg, body)
})
if err := n.Run(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment