1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 // DialError is an error that occurs while dialling a websocket server.
16 type DialError struct {
21 func (e *DialError) Error() string {
22 return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error()
25 // NewConfig creates a new WebSocket config for client connection.
26 func NewConfig(server, origin string) (config *Config, err error) {
28 config.Version = ProtocolVersionHybi13
29 config.Location, err = url.ParseRequestURI(server)
33 config.Origin, err = url.ParseRequestURI(origin)
37 config.Header = http.Header(make(map[string][]string))
41 // NewClient creates a new WebSocket client connection over rwc.
42 func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
43 br := bufio.NewReader(rwc)
44 bw := bufio.NewWriter(rwc)
45 err = hybiClientHandshake(config, br, bw)
49 buf := bufio.NewReadWriter(br, bw)
50 ws = newHybiClientConn(config, buf, rwc)
54 // Dial opens a new client connection to a WebSocket.
55 func Dial(url_, protocol, origin string) (ws *Conn, err error) {
56 config, err := NewConfig(url_, origin)
61 config.Protocol = []string{protocol}
63 return DialConfig(config)
66 var portMap = map[string]string{
71 func parseAuthority(location *url.URL) string {
72 if _, ok := portMap[location.Scheme]; ok {
73 if _, _, err := net.SplitHostPort(location.Host); err != nil {
74 return net.JoinHostPort(location.Host, portMap[location.Scheme])
80 // DialConfig opens a new client connection to a WebSocket with a config.
81 func DialConfig(config *Config) (ws *Conn, err error) {
83 if config.Location == nil {
84 return nil, &DialError{config, ErrBadWebSocketLocation}
86 if config.Origin == nil {
87 return nil, &DialError{config, ErrBadWebSocketOrigin}
89 dialer := config.Dialer
91 dialer = &net.Dialer{}
93 client, err = dialWithDialer(dialer, config)
97 ws, err = NewClient(config, client)
105 return nil, &DialError{config, err}