55 lines
1.5 KiB
Go
Raw Normal View History

2024-01-03 20:09:47 +09:00
package sockets
2024-01-03 18:40:45 +09:00
import (
"context"
"net"
"syscall/js"
2024-01-03 21:20:07 +09:00
"time"
2024-01-03 20:55:26 +09:00
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
2024-01-03 21:20:07 +09:00
"github.com/syumai/workers/internal/jsutil"
2024-01-03 18:40:45 +09:00
)
2024-01-03 20:39:49 +09:00
type SecureTransport string
const (
2024-01-03 21:20:07 +09:00
// 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()".
2024-01-03 20:39:49 +09:00
SecureTransportStartTLS SecureTransport = "starttls"
)
2024-01-03 18:40:45 +09:00
type SocketOptions struct {
2024-01-03 20:39:49 +09:00
SecureTransport SecureTransport `json:"secureTransport"`
AllowHalfOpen bool `json:"allowHalfOpen"`
2024-01-03 18:40:45 +09:00
}
2024-01-03 21:20:07 +09:00
const defaultDeadline = 999999 * time.Hour
2024-01-03 20:36:31 +09:00
func Connect(ctx context.Context, addr string, opts *SocketOptions) (net.Conn, error) {
2024-01-03 18:40:45 +09:00
connect, err := cfruntimecontext.GetRuntimeContextValue(ctx, "connect")
if err != nil {
return nil, err
}
optionsObj := jsutil.NewObject()
2024-01-03 20:36:31 +09:00
if opts != nil {
if opts.AllowHalfOpen {
2024-01-03 18:40:45 +09:00
optionsObj.Set("allowHalfOpen", true)
}
2024-01-03 20:36:31 +09:00
if opts.SecureTransport != "" {
2024-01-03 22:25:41 +09:00
optionsObj.Set("secureTransport", string(opts.SecureTransport))
2024-01-03 18:40:45 +09:00
}
}
sockVal, err := jsutil.TryCatch(js.FuncOf(func(_ js.Value, args []js.Value) any {
return connect.Invoke(addr, optionsObj)
}))
if err != nil {
return nil, err
}
2024-01-03 21:20:07 +09:00
deadline := time.Now().Add(defaultDeadline)
return newSocket(ctx, sockVal, deadline, deadline), nil
2024-01-03 18:40:45 +09:00
}