Skip to content

Commit

Permalink
update example to output json, handle reconnection in subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
ramin committed Apr 26, 2024
1 parent 47da279 commit 7a82632
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 25 deletions.
16 changes: 13 additions & 3 deletions examples/subscribe/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/json"
"fmt"

eclair "github.com/edobtc/go-eclair"
Expand All @@ -18,16 +19,25 @@ func main() {
}

for message := range channel {
fmt.Println(message)
// handle messages here
data, err := json.Marshal(message)
if err != nil {
fmt.Println(err)
return
}

// output nicely for demostation purposes
fmt.Println(string(data))

switch message.Type {
case eclair.ChannelOpenedEvent:
fmt.Println("channel opened")
// handle channel opened event
case eclair.ChannelClosedEvent:
// handle channel closed event
fmt.Println("channel closed")
case eclair.PaymentReceivedEvent:
// handle channel closed event
// handle channel closed even
fmt.Println("payment received")
}
}
}
55 changes: 33 additions & 22 deletions subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ package eclair
import (
"fmt"
"net/url"
"time"

"github.com/gorilla/websocket"
)

const (
recoveryInterval = 5 * time.Second
)

func (c *Client) websocketURL() string {
u, _ := url.Parse(c.BaseURL)
u.Scheme = "ws"
Expand All @@ -20,34 +25,40 @@ func (c *Client) Subscribe() (<-chan (Message), error) {
go func() {
defer close(ch)

conn, _, err := websocket.DefaultDialer.Dial(
c.websocketURL(),
c.settings.AuthHeaders(),
)

if err != nil {
err = fmt.Errorf("error connecting to WebSocket: %v", err)
fmt.Println(err)
return
}
defer conn.Close()

for {
_, msg, err := conn.ReadMessage()
if err != nil {
err = fmt.Errorf("error reading from WebSocket: %v", err)
fmt.Println(err)
return
}
conn, _, err := websocket.DefaultDialer.Dial(
c.websocketURL(),
c.settings.AuthHeaders(),
)

event, err := UnmarshalEvent(msg)
if err != nil {
err = fmt.Errorf("error unmarshaling event: %v", err)
err = fmt.Errorf("error connecting to WebSocket: %v", err)
fmt.Println(err)
return
time.Sleep(recoveryInterval)
continue
}

ch <- *event
func() {
defer conn.Close()

for {
_, msg, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
fmt.Printf("error reading from WebSocket: %v\n", err)
}
return // Exit the inner function to reconnect
}

event, err := UnmarshalEvent(msg)
if err != nil {
fmt.Printf("error unmarshaling event: %v\n", err)
continue
}

ch <- *event
}
}()
}
}()

Expand Down

0 comments on commit 7a82632

Please sign in to comment.