package reach import ( "sync" "time" "forge.cadoles.com/Pyxis/golang-socketio" "forge.cadoles.com/Pyxis/golang-socketio/transport" "github.com/pkg/errors" ) type handshake struct { PingInterval time.Duration `json:"pingInterval"` } // Client is a ReachView Websocket API client 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) { 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() conn.On(gosocketio.OnError, nil) 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 return } func (c *Client) logf(format string, args ...interface{}) { if c.opts.Logger == nil { return } c.opts.Logger.Printf(format, args...) } // NewClient returns a new ReachView Websocket API client func NewClient(opts ...OptionFunc) *Client { options := DefaultOptions() for _, o := range opts { o(options) } return &Client{ opts: options, } }