-
Notifications
You must be signed in to change notification settings - Fork 9
/
example_test.go
131 lines (107 loc) · 2.09 KB
/
example_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package fatchan
import (
"fmt"
"net"
"sync"
)
func ExampleTransport() {
var wg sync.WaitGroup
// Set up the fake network
cconn, sconn := net.Pipe()
accept := func() net.Conn { return sconn }
dial := func() net.Conn { return cconn }
// Types
type Request struct {
Input string
Output chan map[rune]int
}
// Server
wg.Add(1)
go func() {
defer wg.Done()
// Listen for clients
conn := accept()
xport := New(conn, nil)
// Connect the channel
requests := make(chan Request)
xport.ToChan(requests)
// Answer a request
req := <-requests
reply := make(map[rune]int)
for _, r := range req.Input {
reply[r]++
}
req.Output <- reply
}()
// Client
wg.Add(1)
go func() {
defer wg.Done()
// Dial the server
conn := dial()
xport := New(conn, nil)
// Connect the channel
requests := make(chan Request)
xport.FromChan(requests)
// Send a request
reply := make(chan map[rune]int)
requests <- Request{
Input: "on top of spaghetti",
Output: reply,
}
cnt := <-reply
for r := rune(0); r < 256; r++ {
if cnt[r] > 0 {
fmt.Printf("Found %q %d times\n", r, cnt[r])
}
}
}()
wg.Wait()
// Output:
// Found ' ' 3 times
// Found 'a' 1 times
// Found 'e' 1 times
// Found 'f' 1 times
// Found 'g' 1 times
// Found 'h' 1 times
// Found 'i' 1 times
// Found 'n' 1 times
// Found 'o' 3 times
// Found 'p' 2 times
// Found 's' 1 times
// Found 't' 3 times
}
func ExampleTransport_FromChan(conn net.Conn) {
type Request struct {
Input string
Output chan string
}
// Create the transport
xport := New(conn, nil)
// Register the channel
out := make(chan Request)
xport.FromChan(out)
// Send the request
in := make(chan string)
out <- Request{
Input: "testing",
Output: in,
}
// Get the response
fmt.Println(<-in)
}
func ExampleTransport_ToChan(conn net.Conn) {
type Request struct {
Input string
Output chan string
}
// Create the transport
xport := New(conn, nil)
// Register the channel
in := make(chan Request)
xport.ToChan(in)
// Recieve a request
req := <-in
// Send the response
req.Output <- req.Input
}