2
0

added connect handler and GetURL method

This commit is contained in:
Lucas Löffel
2018-10-09 11:08:15 +02:00
parent 56a83509ae
commit bbc5af6a3c
+32 -12
View File
@@ -35,6 +35,8 @@ type RecConn struct {
HandshakeTimeout time.Duration HandshakeTimeout time.Duration
// NonVerbose suppress connecting/reconnecting messages. // NonVerbose suppress connecting/reconnecting messages.
NonVerbose bool NonVerbose bool
// ConnectHandler fires after the connection successfully establish.
ConnectHandler func(rc *RecConn) error
mu sync.Mutex mu sync.Mutex
url string url string
@@ -50,10 +52,7 @@ type RecConn struct {
// CloseAndReconnect will try to reconnect. // CloseAndReconnect will try to reconnect.
func (rc *RecConn) closeAndReconnect() { func (rc *RecConn) closeAndReconnect() {
rc.Close() rc.Close()
go func() { go rc.connect()
rc.connect()
}()
} }
// Close closes the underlying network connection without // Close closes the underlying network connection without
@@ -180,14 +179,17 @@ func (rc *RecConn) Dial(urlStr string, reqHeader http.Header) {
rc.dialer = websocket.DefaultDialer rc.dialer = websocket.DefaultDialer
rc.dialer.HandshakeTimeout = rc.HandshakeTimeout rc.dialer.HandshakeTimeout = rc.HandshakeTimeout
go func() { go rc.connect()
rc.connect()
}()
// wait on first attempt // wait on first attempt
time.Sleep(rc.HandshakeTimeout) time.Sleep(rc.HandshakeTimeout)
} }
// GetURL returns current connection url
func (rc *RecConn) GetURL() string {
return rc.url
}
func (rc *RecConn) connect() { func (rc *RecConn) connect() {
b := &backoff.Backoff{ b := &backoff.Backoff{
Min: rc.RecIntvlMin, Min: rc.RecIntvlMin,
@@ -214,12 +216,23 @@ func (rc *RecConn) connect() {
if !rc.NonVerbose { if !rc.NonVerbose {
log.Printf("Dial: connection was successfully established with %s\n", rc.url) log.Printf("Dial: connection was successfully established with %s\n", rc.url)
} }
break
} else { if rc.ConnectHandler == nil {
if !rc.NonVerbose { break
log.Println(err)
log.Println("Dial: will try again in", nextItvl, "seconds.")
} }
if err := rc.ConnectHandler(rc); err != nil {
log.Fatalf("Dial: connect handler failed with %s", err.Error())
}
log.Printf("Dial: connect handler was successfully established with %s\n", rc.url)
return
}
if !rc.NonVerbose {
log.Println(err)
log.Println("Dial: will try again in", nextItvl, "seconds.")
} }
time.Sleep(nextItvl) time.Sleep(nextItvl)
@@ -252,3 +265,10 @@ func (rc *RecConn) IsConnected() bool {
return rc.isConnected return rc.isConnected
} }
func (rc *RecConn) GetConnection() *RecConn {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc
}