Use transport factory function

This commit is contained in:
Wichert Akkerman 2019-10-11 07:19:55 +02:00 committed by Mickaël Rémond
parent 8db608ccc1
commit 06a76160c8
3 changed files with 11 additions and 3 deletions

View file

@ -143,7 +143,7 @@ func NewClient(config Config, r *Router) (c *Client, err error) {
c.config.ConnectTimeout = 15 // 15 second as default c.config.ConnectTimeout = 15 // 15 second as default
} }
c.transport = &XMPPTransport{Config: config.TransportConfiguration} c.transport = NewTransport(config.TransportConfiguration)
return return
} }

View file

@ -67,7 +67,7 @@ func (c *Component) Connect() error {
} }
func (c *Component) Resume(sm SMState) error { func (c *Component) Resume(sm SMState) error {
var err error var err error
c.transport = &XMPPTransport{Config: c.ComponentOptions.TransportConfiguration} c.transport = NewTransport(c.ComponentOptions.TransportConfiguration)
if err = c.transport.Connect(); err != nil { if err = c.transport.Connect(); err != nil {
return err return err
} }

View file

@ -3,6 +3,7 @@ package xmpp
import ( import (
"crypto/tls" "crypto/tls"
"errors" "errors"
"strings"
) )
var TLSNotSupported = errors.New("Transport does not support StartTLS") var TLSNotSupported = errors.New("Transport does not support StartTLS")
@ -29,7 +30,14 @@ type Transport interface {
Close() error Close() error
} }
// NewTransport creates a new Transport instance.
// The type of transport is determined by the address in the configuration:
// - if the address is a URL with the `ws` or `wss` scheme WebsocketTransport is used
// - in all other cases a XMPPTransport is used
// For XMPPTransport it is mandatory for the address to have a port specified.
func NewTransport(config TransportConfiguration) Transport { func NewTransport(config TransportConfiguration) Transport {
return &XMPPTransport{Config: config} if strings.HasPrefix(config.Address, "ws:") || strings.HasPrefix(config.Address, "wss:") {
return &WebsocketTransport{Config: config}
}
return &XMPPTransport{Config: config}
} }