forked from awoodbeck/gnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_echo_test.go
85 lines (71 loc) · 1.48 KB
/
tls_echo_test.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
83
84
85
package ch11
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"io"
"io/ioutil"
"strings"
"testing"
"time"
)
func TestEchoServerTLS(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
serverAddress := "localhost:34443"
maxIdle := time.Second
server := NewTLSServer(ctx, serverAddress, maxIdle, nil)
done := make(chan struct{})
go func() {
err := server.ListenAndServeTLS("cert.pem", "key.pem")
if err != nil && !strings.Contains(err.Error(),
"use of closed network connection") {
t.Error(err)
return
}
done <- struct{}{}
}()
server.Ready()
cert, err := ioutil.ReadFile("cert.pem")
if err != nil {
t.Fatal(err)
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM(cert); !ok {
t.Fatal("failed to append certificate to pool")
}
tlsConfig := &tls.Config{
CurvePreferences: []tls.CurveID{tls.CurveP256},
MinVersion: tls.VersionTLS12,
RootCAs: certPool,
}
conn, err := tls.Dial("tcp", serverAddress, tlsConfig)
if err != nil {
t.Fatal(err)
}
hello := []byte("hello")
_, err = conn.Write(hello)
if err != nil {
t.Fatal(err)
}
b := make([]byte, 1024)
n, err := conn.Read(b)
if err != nil {
t.Fatal(err)
}
if actual := b[:n]; !bytes.Equal(hello, actual) {
t.Fatalf("expected %q; actual %q", hello, actual)
}
time.Sleep(2 * maxIdle)
_, err = conn.Read(b)
if err != io.EOF {
t.Fatal(err)
}
err = conn.Close()
if err != nil {
t.Fatal(err)
}
cancel()
<-done
}