// ConnectWebsocketSession dials the remote specified in the opts and // creates new websocket session. 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 := utils.RandomString(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 custom HTTP client and its transport // is of *http.Transport type - we're using its Dial field // for connecting to remote host if t, ok := opts.Client().Transport.(*http.Transport); ok { ws.NetDial = t.Dial } // if the user passed a timeout, use a dial with a timeout if opts.Timeout != 0 && ws.NetDial == nil { // If ws.NetDial is non-nil then gorilla does not // use ws.HandshakeTimeout for the deadlines. // // Instead we're going to set it ourselves. ws.NetDial = (&net.Dialer{ Timeout: opts.Timeout, Deadline: time.Now().Add(opts.Timeout), }).Dial } conn, _, err := ws.Dial(dialURL.String(), requestHeader) if err != nil { return nil, err } session := NewWebsocketSession(conn) session.id = sessionID return session, nil }
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 }