-
Notifications
You must be signed in to change notification settings - Fork 4
/
dial.go
82 lines (70 loc) · 1.87 KB
/
dial.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package ws
import (
"context"
"errors"
"fmt"
"net/http"
"google.golang.org/grpc/metadata"
"nhooyr.io/websocket"
)
// DialErrorResponse returns the HTTP response from the WebSocket handshake error, if any.
func DialErrorResponse(err error) (*http.Response, bool) {
var e *dialErr
if errors.As(err, &e) {
return e.res, true
}
return nil, false
}
func (o ClientOptions) dial(ctx context.Context) (context.Context, *websocket.Conn, error) {
if o.URL == "" {
return nil, nil, errors.New("missing websocket url")
}
header := metadata.Join(
metadata.MD(o.DialOptions.HTTPHeader),
fromOutgoingContext(o.DialContext),
fromOutgoingContext(ctx),
)
dialContext := o.DialContext
if dialContext == nil {
dialContext = ctx
}
// Dial service
ws, res, err := websocket.Dial(dialContext, o.URL, &websocket.DialOptions{
HTTPClient: o.DialOptions.HTTPClient,
HTTPHeader: http.Header(header),
Subprotocols: o.DialOptions.Subprotocols,
CompressionMode: o.DialOptions.CompressionMode,
CompressionThreshold: o.DialOptions.CompressionThreshold,
})
if err != nil {
if res != nil {
err = &dialErr{error: err, res: res}
}
return nil, nil, fmt.Errorf("error handshaking with websocket server: %w", err)
}
// Callback for handshake response
if o.Handshake != nil {
ctx, err = o.Handshake(ctx, res)
if err != nil {
_ = ws.Close(websocket.StatusNormalClosure, fmt.Sprintf(
"handshake response rejected: %v", err))
return nil, nil, err
}
}
return ctx, ws, nil
}
type dialErr struct {
error
res *http.Response
}
func (e *dialErr) Error() string {
return fmt.Sprintf("%s (%d): %v", e.res.Status, e.res.StatusCode, e.error)
}
func (e *dialErr) Unwrap() error { return e.error }
func fromOutgoingContext(ctx context.Context) metadata.MD {
if ctx == nil {
return nil
}
md, _ := metadata.FromOutgoingContext(ctx)
return md
}