package reach import ( "sync" "forge.cadoles.com/Pyxis/golang-socketio" "forge.cadoles.com/Pyxis/golang-socketio/transport" "github.com/mitchellh/mapstructure" "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) fetch(requestEvent string, requestData interface{}, responseEvent string, res interface{}) error { var err error var wg sync.WaitGroup wg.Add(1) err = c.conn.On(responseEvent, func(_ *gosocketio.Channel, data interface{}) { err = mapstructure.Decode(data, res) c.conn.Off(responseEvent) wg.Done() }) if err != nil { return errors.Wrapf(err, "error while binding to '%s' event", responseEvent) } c.logf("sending '%s' event", requestEvent) if err = c.conn.Emit(requestEvent, requestData); err != nil { return errors.Wrapf(err, "error while emitting '%s' event", requestEvent) } c.logf("'%s' event sent", requestEvent) wg.Wait() return err } 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, } }