fix readme code example

This commit is contained in:
shota3506 2023-05-07 14:28:54 +09:00 committed by fiatjaf_
parent 96f3d4c9a0
commit 6c186812c9

View File

@ -43,7 +43,8 @@ func main() {
### Subscribing to a single relay ### Subscribing to a single relay
``` go ``` go
relay, err := nostr.RelayConnect(context.Background(), "wss://nostr.zebedee.cloud") ctx := context.Background()
relay, err := nostr.RelayConnect(ctx, "wss://nostr.zebedee.cloud")
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -54,7 +55,7 @@ var filters nostr.Filters
if _, v, err := nip19.Decode(npub); err == nil { if _, v, err := nip19.Decode(npub); err == nil {
pub := v.(string) pub := v.(string)
filters = []nostr.Filter{{ filters = []nostr.Filter{{
Kinds: []int{1}, Kinds: []int{nostr.KindTextNote},
Authors: []string{pub}, Authors: []string{pub},
Limit: 1, Limit: 1,
}} }}
@ -62,18 +63,17 @@ if _, v, err := nip19.Decode(npub); err == nil {
panic(err) panic(err)
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
sub := relay.Subscribe(ctx, filters) defer cancel()
go func() { sub, err := relay.Subscribe(ctx, filters)
<-sub.EndOfStoredEvents if err != nil {
// handle end of stored events (EOSE, see NIP-15) panic(err)
}() }
for ev := range sub.Events { for ev := range sub.Events {
// handle returned event. // handle returned event.
// channel will stay open until the ctx is cancelled (in this case, by calling cancel()) // channel will stay open until the ctx is cancelled (in this case, context timeout)
fmt.Println(ev.ID) fmt.Println(ev.ID)
} }
``` ```
@ -87,7 +87,7 @@ pub, _ := nostr.GetPublicKey(sk)
ev := nostr.Event{ ev := nostr.Event{
PubKey: pub, PubKey: pub,
CreatedAt: nostr.Now(), CreatedAt: nostr.Now(),
Kind: 1, Kind: nostr.KindTextNote,
Tags: nil, Tags: nil,
Content: "Hello World!", Content: "Hello World!",
} }
@ -96,13 +96,20 @@ ev := nostr.Event{
ev.Sign(sk) ev.Sign(sk)
// publish the event to two relays // publish the event to two relays
ctx := context.Background()
for _, url := range []string{"wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net"} { for _, url := range []string{"wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net"} {
relay, e := nostr.RelayConnect(context.Background(), url) relay, err := nostr.RelayConnect(ctx, url)
if e != nil { if err != nil {
fmt.Println(e) fmt.Println(err)
continue continue
} }
fmt.Println("published to ", url, relay.Publish(context.Background(), ev)) _, err = relay.Publish(ctx, ev)
if err != nil {
fmt.Println(err)
continue
}
fmt.Printf("published to %s\n", url)
} }
``` ```