This repository has been archived on 2024-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
orion/reach/client.go

92 lines
1.9 KiB
Go
Raw Normal View History

2018-09-18 18:07:40 +02:00
package reach
import (
"sync"
"forge.cadoles.com/Pyxis/golang-socketio"
"forge.cadoles.com/Pyxis/golang-socketio/transport"
"github.com/pkg/errors"
)
type client struct {
2018-09-18 18:07:40 +02:00
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 {
2018-09-18 18:07:40 +02:00
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) {
2018-09-20 15:44:34 +02:00
conn.Off(gosocketio.OnError)
2018-09-18 18:07:40 +02:00
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() {
2018-09-18 18:07:40 +02:00
if c.conn == nil {
return
}
c.conn.Close()
c.conn = nil
return
}
func (c *client) logf(format string, args ...interface{}) {
2018-09-18 18:07:40 +02:00
if c.opts.Logger == nil {
return
}
c.opts.Logger.Printf(format, args...)
}
func newClient(opts ...OptionFunc) *client {
2018-09-18 18:07:40 +02:00
options := DefaultOptions()
for _, o := range opts {
o(options)
}
return &client{
2018-09-18 18:07:40 +02:00
opts: options,
}
}