orion/reach/client.go

91 lines
1.8 KiB
Go

package reach
import (
"sync"
"forge.cadoles.com/Pyxis/golang-socketio"
"forge.cadoles.com/Pyxis/golang-socketio/transport"
"github.com/pkg/errors"
)
type client struct {
opts *Options
conn *gosocketio.Client
}
// Connect connects the client to the ReachView endpoint
// This method is not safe to call by different coroutines
func (c *client) Connect() error {
var err error
var wg sync.WaitGroup
wg.Add(1)
transport := &transport.WebsocketTransport{
PingInterval: c.opts.PingInterval,
PingTimeout: c.opts.PingTimeout,
ReceiveTimeout: c.opts.ReceiveTimeout,
SendTimeout: c.opts.SendTimeout,
BufferSize: c.opts.BufferSize,
}
c.logf("connecting to '%s'", c.opts.Endpoint)
conn, err := gosocketio.Dial(c.opts.Endpoint, transport)
if err != nil {
return errors.Wrap(err, "error while connecting to endpoint")
}
c.conn = conn
err = conn.On(gosocketio.OnConnection, func(h *gosocketio.Channel) {
conn.Off(gosocketio.OnError)
c.logf("connected with sid '%s'", h.Id())
err = c.sendBrowserConnected()
wg.Done()
})
if err != nil {
return errors.Wrap(err, "error while attaching to connection event")
}
err = conn.On(gosocketio.OnError, func(h *gosocketio.Channel) {
c.logf("error")
err = errors.Errorf("an unknown error occured")
c.conn = nil
wg.Done()
})
if err != nil {
return errors.Wrap(err, "error while attaching to error event")
}
wg.Wait()
return err
}
// Close closes the current connection to the ReachView endpoint
func (c *client) Close() {
if c.conn == nil {
return
}
c.conn.Close()
c.conn = nil
}
func (c *client) logf(format string, args ...interface{}) {
if c.opts.Logger == nil {
return
}
c.opts.Logger.Printf(format, args...)
}
func newClient(opts ...OptionFunc) *client {
options := DefaultOptions()
for _, o := range opts {
o(options)
}
return &client{
opts: options,
}
}