prysm-pulse/sharding/p2p/feed_example_test.go
Preston Van Loon b4702f9966 Typo
Former-commit-id: f40d1c783e9196c769c6dd5132de2175edfda64e [formerly b67787261f69ede4c8a6763cc31832d0005011ad]
Former-commit-id: 041b9dcf7a86f3966ce85dfdfe048aa9973e46bb
2018-06-12 23:02:07 -04:00

43 lines
908 B
Go

package p2p
import "fmt"
// Feeds can be use to subscribe to any type of message.
func ExampleServer_Feed() {
s, err := NewServer()
if err != nil {
panic(err)
}
// Let's wait for a puzzle from our peers then try to solve it.
type Puzzle struct {
Challenge string
Answer string
}
feed, err := s.Feed(Puzzle{})
if err != nil {
// This shouldn't happen, but we should handle it anyway.
panic(err)
}
ch := make(chan Message, 5) // Small buffer size. I don't expect many puzzles.
sub := feed.Subscribe(ch)
// Always close these resources.
defer sub.Unsubscribe()
defer close(ch)
// Wait until we have a puzzle to solve.
msg := <-ch
puzzle := msg.Data.(Puzzle)
fmt.Printf("Received puzzle %s from peer %v\n", puzzle, msg.Peer)
if puzzle.Answer == "fourteen" {
fmt.Println("I solved the puzzle!")
} else {
fmt.Println("The answer isn't \"fourteen\"... giving up")
}
}