-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
streaming_rpc.go
72 lines (62 loc) · 1.89 KB
/
streaming_rpc.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
package structs
import (
"fmt"
"io"
"sync"
)
// StreamingRpcHeader is the first struct serialized after entering the
// streaming RPC mode. The header is used to dispatch to the correct method.
type StreamingRpcHeader struct {
// Method is the name of the method to invoke.
Method string
}
// StreamingRpcAck is used to acknowledge receiving the StreamingRpcHeader and
// routing to the requested handler.
type StreamingRpcAck struct {
// Error is used to return whether an error occurred establishing the
// streaming RPC. This error occurs before entering the RPC handler.
Error string
}
// StreamingRpcHandler defines the handler for a streaming RPC.
type StreamingRpcHandler func(conn io.ReadWriteCloser)
// StreamingRpcRegistry is used to add and retrieve handlers
type StreamingRpcRegistry struct {
registry map[string]StreamingRpcHandler
}
// NewStreamingRpcRegistry creates a new registry. All registrations of
// handlers should be done before retrieving handlers.
func NewStreamingRpcRegistry() *StreamingRpcRegistry {
return &StreamingRpcRegistry{
registry: make(map[string]StreamingRpcHandler),
}
}
// Register registers a new handler for the given method name
func (s *StreamingRpcRegistry) Register(method string, handler StreamingRpcHandler) {
s.registry[method] = handler
}
// GetHandler returns a handler for the given method or an error if it doesn't exist.
func (s *StreamingRpcRegistry) GetHandler(method string) (StreamingRpcHandler, error) {
h, ok := s.registry[method]
if !ok {
return nil, fmt.Errorf("%s: %q", ErrUnknownMethod, method)
}
return h, nil
}
// Bridge is used to just link two connections together and copy traffic
func Bridge(a, b io.ReadWriteCloser) {
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
_, _ = io.Copy(a, b)
a.Close()
b.Close()
}()
go func() {
defer wg.Done()
_, _ = io.Copy(b, a)
a.Close()
b.Close()
}()
wg.Wait()
}