summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/basic/main.go103
1 files changed, 103 insertions, 0 deletions
diff --git a/examples/basic/main.go b/examples/basic/main.go
new file mode 100644
index 0000000..0c99dd9
--- /dev/null
+++ b/examples/basic/main.go
@@ -0,0 +1,103 @@
1package main
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "time"
8
9 "northwest.io/nostr"
10)
11
12// Example_basic demonstrates basic usage of the nostr library.
13func main() {
14 // Generate a new key pair
15 key, err := nostr.GenerateKey()
16 if err != nil {
17 fmt.Printf("Failed to generate key: %v\n", err)
18 os.Exit(1)
19 }
20
21 fmt.Printf("Public key (hex): %s...\n", key.Public()[:16])
22 fmt.Printf("Public key (npub): %s...\n", key.Npub()[:20])
23
24 // Create an event
25 event := &nostr.Event{
26 Kind: nostr.KindTextNote,
27 Tags: nostr.Tags{{"t", "test"}},
28 Content: "Hello from nostr-go!",
29 }
30
31 // Sign the event
32 if err := key.Sign(event); err != nil {
33 fmt.Printf("Failed to sign event: %v\n", err)
34 os.Exit(1)
35 }
36
37 // Verify the signature
38 if event.Verify() {
39 fmt.Println("Event signature verified!")
40 }
41
42 // Create a filter to match our event
43 filter := nostr.Filter{
44 Kinds: []int{nostr.KindTextNote},
45 Authors: []string{key.Public()[:8]}, // Prefix matching
46 }
47
48 if filter.Matches(event) {
49 fmt.Println("Filter matches the event!")
50 }
51
52 fmt.Println("connecting to relay...")
53 ExampleRelay()
54}
55
56// ExampleRelay demonstrates connecting to a relay (requires network).
57// This is a documentation example - run with: go test -v -run ExampleRelay
58func ExampleRelay() {
59 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
60 defer cancel()
61
62 // Connect to a public relay
63 relay, err := nostr.Connect(ctx, "wss://relay.damus.io")
64 if err != nil {
65 fmt.Printf("Failed to connect: %v\n", err)
66 return
67 }
68 defer relay.Close()
69
70 fmt.Println("Connected to relay!")
71
72 // Subscribe to recent text notes
73 since := time.Now().Add(-1 * time.Hour).Unix()
74 sub, err := relay.Subscribe(ctx, "my-sub", nostr.Filter{
75 Kinds: []int{nostr.KindTextNote},
76 Since: &since,
77 Limit: 5,
78 })
79 if err != nil {
80 fmt.Printf("Failed to subscribe: %v\n", err)
81 os.Exit(1)
82 }
83
84 // Listen for events in the background
85 go relay.Listen(ctx)
86
87 // Collect events until EOSE
88 eventCount := 0
89 for {
90 select {
91 case event := <-sub.Events:
92 eventCount++
93 fmt.Printf("Received event from %s...\n", event)
94 case <-sub.EOSE:
95 fmt.Printf("Received %d events before EOSE\n", eventCount)
96 sub.Close(ctx)
97 return
98 case <-ctx.Done():
99 fmt.Println("Timeout")
100 return
101 }
102 }
103}