summaryrefslogtreecommitdiffstats
path: root/example_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'example_test.go')
-rw-r--r--example_test.go35
1 files changed, 10 insertions, 25 deletions
diff --git a/example_test.go b/example_test.go
index 90dae0f..6d10ced 100644
--- a/example_test.go
+++ b/example_test.go
@@ -53,8 +53,7 @@ func Example_basic() {
53// ExampleRelay demonstrates connecting to a relay (requires network). 53// ExampleRelay demonstrates connecting to a relay (requires network).
54// This is a documentation example - run with: go test -v -run ExampleRelay 54// This is a documentation example - run with: go test -v -run ExampleRelay
55func ExampleRelay() { 55func ExampleRelay() {
56 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 56 ctx := context.Background()
57 defer cancel()
58 57
59 // Connect to a public relay 58 // Connect to a public relay
60 relay, err := nostr.Connect(ctx, "wss://relay.damus.io") 59 relay, err := nostr.Connect(ctx, "wss://relay.damus.io")
@@ -66,35 +65,21 @@ func ExampleRelay() {
66 65
67 fmt.Println("Connected to relay!") 66 fmt.Println("Connected to relay!")
68 67
69 // Subscribe to recent text notes 68 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
69 defer cancel()
70
71 // Fetch recent text notes (closes on EOSE)
70 since := time.Now().Add(-1 * time.Hour).Unix() 72 since := time.Now().Add(-1 * time.Hour).Unix()
71 sub, err := relay.Subscribe(ctx, "my-sub", nostr.Filter{ 73 sub := relay.Fetch(ctx, nostr.Filter{
72 Kinds: []int{nostr.KindTextNote}, 74 Kinds: []int{nostr.KindTextNote},
73 Since: &since, 75 Since: &since,
74 Limit: 5, 76 Limit: 5,
75 }) 77 })
76 if err != nil {
77 fmt.Printf("Failed to subscribe: %v\n", err)
78 return
79 }
80
81 // Listen for events in the background
82 go relay.Listen(ctx)
83 78
84 // Collect events until EOSE
85 eventCount := 0 79 eventCount := 0
86 for { 80 for event := range sub.Events {
87 select { 81 eventCount++
88 case event := <-sub.Events: 82 fmt.Printf("Received event from %s...\n", event.PubKey[:8])
89 eventCount++
90 fmt.Printf("Received event from %s...\n", event.PubKey[:8])
91 case <-sub.EOSE:
92 fmt.Printf("Received %d events before EOSE\n", eventCount)
93 sub.Close(ctx)
94 return
95 case <-ctx.Done():
96 fmt.Println("Timeout")
97 return
98 }
99 } 83 }
84 fmt.Printf("Received %d events\n", eventCount)
100} 85}