diff --git a/examples/subscribe/main.go b/examples/subscribe/main.go index ff70bcd..5ea0799 100644 --- a/examples/subscribe/main.go +++ b/examples/subscribe/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" eclair "github.com/edobtc/go-eclair" @@ -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") } } } diff --git a/subscribe.go b/subscribe.go index e84727f..11c032a 100644 --- a/subscribe.go +++ b/subscribe.go @@ -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" @@ -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 + } + }() } }()