forked from syumai/workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.go
54 lines (47 loc) · 1.48 KB
/
connect.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
package sockets
import (
"context"
jsutil2 "github.com/tinyredglasses/workers/jsutil"
"net"
"syscall/js"
"time"
"github.com/tinyredglasses/workers/cloudflare/internal/cfruntimecontext"
)
type SecureTransport string
const (
// SecureTransportOn indicates "Use TLS".
SecureTransportOn SecureTransport = "on"
// SecureTransportOff indicates "Do not use TLS".
SecureTransportOff SecureTransport = "off"
// SecureTransportStartTLS indicates "Do not use TLS initially, but allow the socket to be upgraded
// to use TLS by calling *Socket.StartTLS()".
SecureTransportStartTLS SecureTransport = "starttls"
)
type SocketOptions struct {
SecureTransport SecureTransport `json:"secureTransport"`
AllowHalfOpen bool `json:"allowHalfOpen"`
}
const defaultDeadline = 999999 * time.Hour
func Connect(ctx context.Context, addr string, opts *SocketOptions) (net.Conn, error) {
connect, err := cfruntimecontext.GetRuntimeContextValue(ctx, "connect")
if err != nil {
return nil, err
}
optionsObj := jsutil2.NewObject()
if opts != nil {
if opts.AllowHalfOpen {
optionsObj.Set("allowHalfOpen", true)
}
if opts.SecureTransport != "" {
optionsObj.Set("secureTransport", string(opts.SecureTransport))
}
}
sockVal, err := jsutil2.TryCatch(js.FuncOf(func(_ js.Value, args []js.Value) any {
return connect.Invoke(addr, optionsObj)
}))
if err != nil {
return nil, err
}
deadline := time.Now().Add(defaultDeadline)
return newSocket(ctx, sockVal, deadline, deadline), nil
}