-
Notifications
You must be signed in to change notification settings - Fork 1
/
tls.go
80 lines (60 loc) · 1.27 KB
/
tls.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
package udp
import (
"crypto/tls"
"net"
"time"
"go.k6.io/k6/js/modules"
)
func init() {
modules.Register("k6/x/tls", new(TLS))
}
const maxPackageSize = 63 * 1024 // 63KiB
var newLine = []byte("\n")
type TLS struct{}
func (u *TLS) Connect(address string) (net.Conn, error) {
conn, err := tls.Dial("tcp", address, nil)
if err != nil {
return nil, err
}
return conn, nil
}
func (u *TLS) Writeln(conn net.Conn, data []byte) error {
return u.Write(conn, append(data, newLine...))
}
func (u *TLS) Write(conn net.Conn, data []byte) error {
for i := 0; i < len(data); i += maxPackageSize {
end := i + maxPackageSize
if end > len(data) {
end = len(data)
}
chunk := data[i:end]
_, err := conn.Write(chunk)
if err != nil {
return err
}
}
return nil
}
func (u *TLS) Read(conn net.Conn, size int, timeout_opt ...int) ([]byte, error) {
timeout_ms := 0
if len(timeout_opt) > 0 {
timeout_ms = timeout_opt[0]
}
err := conn.SetReadDeadline(time.Now().Add(time.Millisecond * time.Duration(timeout_ms)))
if err != nil {
return nil, err
}
buf := make([]byte, size)
_, err = conn.Read(buf)
if err != nil {
return nil, err
}
return buf, nil
}
func (u *TLS) Close(conn net.Conn) error {
err := conn.Close()
if err != nil {
return err
}
return nil
}