-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipe_test.go
96 lines (85 loc) · 1.57 KB
/
pipe_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
86
87
88
89
90
91
92
93
94
95
96
package vnet_test
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"runtime"
"testing"
"github.com/powerpuffpenguin/vnet"
)
func TestPipe(t *testing.T) {
var (
// listen pipe
p = vnet.ListenPipe()
l net.Listener = p
d vnet.Dialer = p
)
// run client
ch := make(chan error, 2)
go runClient(
&http.Client{
Transport: &http.Transport{
// http client by vnet.Dialer
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.DialContext(ctx, network, addr)
},
},
},
ch,
)
// run server
go runServer(l, ch)
for i := 0; i < 2; i++ {
e := <-ch
if e != nil {
t.Fatal(e)
}
}
}
func runClient(client *http.Client, ch chan<- error) {
// get /info
resp, e := client.Get(`http://pipe/info`)
if e != nil {
ch <- e
return
}
b, e := ioutil.ReadAll(resp.Body)
if e != nil {
ch <- e
return
}
fmt.Printf("/info resp: %s\n", b)
// get /exit
resp, e = client.Get(`http://pipe/exit`)
if e != nil {
ch <- e
return
}
b, e = ioutil.ReadAll(resp.Body)
if e != nil {
ch <- e
return
}
fmt.Printf("/exit resp: %s\n", b)
ch <- nil
}
func runServer(l net.Listener, ch chan<- error) {
mux := http.NewServeMux()
mux.HandleFunc(`/info`, func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte(`pipe listener`))
})
mux.HandleFunc(`/exit`, func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte(`success`))
runtime.Gosched()
l.Close()
})
e := http.Serve(l, mux)
if e != nil && !errors.Is(e, vnet.ErrListenerClosed) {
ch <- e
} else {
ch <- nil
}
}