Example #1
0
func ConnectWebsocketSession(opts *DialOptions) (*WebsocketSession, error) {
	dialURL, err := url.Parse(opts.BaseURL)
	if err != nil {
		return nil, err
	}

	// will be used to set the origin header
	originalScheme := dialURL.Scheme

	if err := replaceSchemeWithWS(dialURL); err != nil {
		return nil, err
	}

	if err := addMissingPortAndSlash(dialURL); err != nil {
		return nil, err
	}

	serverID := threeDigits()
	sessionID := randomStringLength(20)

	// Add server_id and session_id to the path.
	dialURL.Path += serverID + "/" + sessionID + "/websocket"

	requestHeader := http.Header{}
	requestHeader.Add("Origin", originalScheme+"://"+dialURL.Host)

	ws := websocket.Dialer{
		ReadBufferSize:  opts.ReadBufferSize,
		WriteBufferSize: opts.WriteBufferSize,
	}

	// if the user passed a timeout, us a dial with a timeout
	if opts.Timeout != 0 {
		ws.NetDial = func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, opts.Timeout)
		}
		// this is used as Deadline inside gorillas dialer method
		ws.HandshakeTimeout = opts.Timeout
	}

	conn, _, err := ws.Dial(dialURL.String(), requestHeader)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	return session, nil
}