improvements at NewConn - now w opts, more flexible

master
Paulo Simão 2021-11-17 06:14:14 -03:00
parent 33db6dfaac
commit 6bd5a3a5ac
1 changed files with 60 additions and 54 deletions

View File

@ -20,11 +20,9 @@ func dbg(s string, p ...interface{}) {
} }
type MQConn struct { type MQConn struct {
opts *MQConnOpts opts *MQConnOpts
retry bool retry bool
chRetry chan *struct{} subs sync.Map
//chReady chan *struct{}
subs sync.Map
mtx sync.Mutex mtx sync.Mutex
conn *websocket.Conn conn *websocket.Conn
@ -189,64 +187,68 @@ func (c *MQConn) Loop() {
} }
func (c *MQConn) Init() error { func (c *MQConn) Init() error {
c.retry = true if c.retry {
doConn := func() error {
doConn := func() error { d := websocket.Dialer{
d := websocket.Dialer{ NetDial: nil,
NetDial: nil, NetDialContext: nil,
NetDialContext: nil, Proxy: nil,
Proxy: nil, TLSClientConfig: &tls.Config{
TLSClientConfig: &tls.Config{ InsecureSkipVerify: true,
InsecureSkipVerify: true, },
}, HandshakeTimeout: 0,
HandshakeTimeout: 0, ReadBufferSize: 0,
ReadBufferSize: 0, WriteBufferSize: 0,
WriteBufferSize: 0, WriteBufferPool: nil,
WriteBufferPool: nil, Subprotocols: nil,
Subprotocols: nil, EnableCompression: false,
EnableCompression: false, Jar: nil,
Jar: nil,
}
h := http.Header{}
if c.opts.Headers != nil {
for k, v := range c.opts.Headers {
h.Set(k, v)
} }
h := http.Header{}
if c.opts.Headers != nil {
for k, v := range c.opts.Headers {
h.Set(k, v)
}
}
con, _, err := d.Dial(c.opts.Url, h)
if err != nil {
return err
}
c.conn = con
con.SetCloseHandler(func(code int, text string) error {
c.conn = nil
return nil
})
return nil
} }
con, _, err := d.Dial(c.opts.Url, h)
err := doConn()
if err != nil { if err != nil {
return err return err
} }
c.conn = con
con.SetCloseHandler(func(code int, text string) error { c.subs.Range(func(key, value interface{}) bool {
c.conn = nil m := &types.Msg{
return nil Cmd: types.CMD_SUB,
Topic: key.(string),
}
err := c.Write(m)
if err != nil {
log.Printf("Error re-listening: %s", err.Error())
return false
}
return true
}) })
return nil
} }
err := doConn()
if err != nil {
return err
}
c.subs.Range(func(key, value interface{}) bool {
m := &types.Msg{
Cmd: types.CMD_SUB,
Topic: key.(string),
}
err := c.Write(m)
if err != nil {
log.Printf("Error re-listening: %s", err.Error())
return false
}
return true
})
return nil return nil
} }
func (c *MQConn) Close() error {
c.retry = false
return c.conn.Close()
}
type MQConnOpts struct { type MQConnOpts struct {
Url string Url string
@ -256,9 +258,13 @@ type MQConnOpts struct {
func New(o *MQConnOpts) (*MQConn, error) { func New(o *MQConnOpts) (*MQConn, error) {
ret := &MQConn{ ret := &MQConn{
opts: o, opts: o,
retry: true,
} }
err := ret.Init() err := ret.Init()
if err != nil {
return nil, err
}
go func() { go func() {
for ret.retry { for ret.retry {
ret.Loop() ret.Loop()