From d4fd2467d691a69a0ba75348086424b9fb33a297 Mon Sep 17 00:00:00 2001 From: bndw Date: Sat, 7 Feb 2026 15:20:57 -0800 Subject: wip --- examples/basic/main.go | 103 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 examples/basic/main.go (limited to 'examples') 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 @@ +package main + +import ( + "context" + "fmt" + "os" + "time" + + "northwest.io/nostr" +) + +// Example_basic demonstrates basic usage of the nostr library. +func main() { + // Generate a new key pair + key, err := nostr.GenerateKey() + if err != nil { + fmt.Printf("Failed to generate key: %v\n", err) + os.Exit(1) + } + + fmt.Printf("Public key (hex): %s...\n", key.Public()[:16]) + fmt.Printf("Public key (npub): %s...\n", key.Npub()[:20]) + + // Create an event + event := &nostr.Event{ + Kind: nostr.KindTextNote, + Tags: nostr.Tags{{"t", "test"}}, + Content: "Hello from nostr-go!", + } + + // Sign the event + if err := key.Sign(event); err != nil { + fmt.Printf("Failed to sign event: %v\n", err) + os.Exit(1) + } + + // Verify the signature + if event.Verify() { + fmt.Println("Event signature verified!") + } + + // Create a filter to match our event + filter := nostr.Filter{ + Kinds: []int{nostr.KindTextNote}, + Authors: []string{key.Public()[:8]}, // Prefix matching + } + + if filter.Matches(event) { + fmt.Println("Filter matches the event!") + } + + fmt.Println("connecting to relay...") + ExampleRelay() +} + +// ExampleRelay demonstrates connecting to a relay (requires network). +// This is a documentation example - run with: go test -v -run ExampleRelay +func ExampleRelay() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Connect to a public relay + relay, err := nostr.Connect(ctx, "wss://relay.damus.io") + if err != nil { + fmt.Printf("Failed to connect: %v\n", err) + return + } + defer relay.Close() + + fmt.Println("Connected to relay!") + + // Subscribe to recent text notes + since := time.Now().Add(-1 * time.Hour).Unix() + sub, err := relay.Subscribe(ctx, "my-sub", nostr.Filter{ + Kinds: []int{nostr.KindTextNote}, + Since: &since, + Limit: 5, + }) + if err != nil { + fmt.Printf("Failed to subscribe: %v\n", err) + os.Exit(1) + } + + // Listen for events in the background + go relay.Listen(ctx) + + // Collect events until EOSE + eventCount := 0 + for { + select { + case event := <-sub.Events: + eventCount++ + fmt.Printf("Received event from %s...\n", event) + case <-sub.EOSE: + fmt.Printf("Received %d events before EOSE\n", eventCount) + sub.Close(ctx) + return + case <-ctx.Done(): + fmt.Println("Timeout") + return + } + } +} -- cgit v1.2.3