Add debug flag
This commit is contained in:
parent
956d93782b
commit
ed864deeaf
33
pubsub.go
33
pubsub.go
|
@ -9,6 +9,7 @@ import (
|
|||
"errors"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"log"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -47,6 +48,8 @@ type TwitchPubSub struct {
|
|||
wsConn *websocket.Conn
|
||||
wsMutex sync.RWMutex
|
||||
|
||||
debug bool
|
||||
|
||||
// Event handlers
|
||||
handlersMu sync.RWMutex
|
||||
handlers map[string][]*eventHandlerInstance
|
||||
|
@ -67,13 +70,24 @@ func NewTwitchPubSub() *TwitchPubSub {
|
|||
return t
|
||||
}
|
||||
|
||||
func (t *TwitchPubSub) EnableDebug() {
|
||||
t.debug = true
|
||||
}
|
||||
|
||||
func (t *TwitchPubSub) Open() error {
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
|
||||
if t.debug {
|
||||
log.Println("Opening connection to", TwitchUrl)
|
||||
}
|
||||
|
||||
c, _, err := websocket.DefaultDialer.Dial(TwitchUrl, nil)
|
||||
|
||||
if err != nil {
|
||||
if t.debug {
|
||||
log.Println("error opening connection:", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -120,12 +134,20 @@ func (t *TwitchPubSub) reconnect() error {
|
|||
wait := time.Duration(1)
|
||||
|
||||
for {
|
||||
if t.debug {
|
||||
log.Println("Reconnecting")
|
||||
}
|
||||
|
||||
err := t.Open()
|
||||
|
||||
if err == nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if t.debug {
|
||||
log.Println("Unable to reconnect")
|
||||
}
|
||||
|
||||
<-time.After(wait * time.Second)
|
||||
wait *= 2
|
||||
|
||||
|
@ -147,6 +169,10 @@ func (t *TwitchPubSub) Listen(topics []string) error {
|
|||
}
|
||||
|
||||
func (t *TwitchPubSub) listen(topics []string) error {
|
||||
if t.debug {
|
||||
log.Println("Attempting to listen to topics", topics)
|
||||
}
|
||||
|
||||
nonce := strings.Replace(uuid.New().String(), "-", "", -1)
|
||||
|
||||
t.wsMutex.Lock()
|
||||
|
@ -215,6 +241,10 @@ func (t *TwitchPubSub) reader(wsConn *websocket.Conn, listening <-chan interface
|
|||
sameConnection := t.wsConn == wsConn
|
||||
t.RUnlock()
|
||||
|
||||
if t.debug {
|
||||
log.Println("Unexpected error", err, "- attempting to reconnect")
|
||||
}
|
||||
|
||||
if sameConnection {
|
||||
t.Close()
|
||||
t.reconnect()
|
||||
|
@ -264,6 +294,9 @@ func (t *TwitchPubSub) pinger(wsConn *websocket.Conn, listening <-chan interface
|
|||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
if t.debug {
|
||||
log.Println("Sending ping")
|
||||
}
|
||||
t.wsMutex.Lock()
|
||||
err := wsConn.WriteJSON(&twitchMessage{Type: Ping})
|
||||
t.wsMutex.Unlock()
|
||||
|
|
Loading…
Reference in New Issue