-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_stream.go
75 lines (63 loc) · 1.75 KB
/
client_stream.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
package wirenettransport
import (
"context"
"github.com/google/uuid"
"github.com/go-kit/kit/endpoint"
"github.com/mediabuyerbot/go-wirenet"
)
// StreamClient wraps a wirenet connection and provides a method
// that implements endpoint.Endpoint.
type StreamClient struct {
streamName string
wire wirenet.Wire
before []ClientRequestFunc
codec ClientCodec
}
// NewStreamClient constructs a usable StreamClient for a single remote endpoint.
func NewStreamClient(
wire wirenet.Wire,
streamName string,
codec ClientCodec,
options ...StreamClientOption,
) *StreamClient {
c := &StreamClient{
streamName: streamName,
wire: wire,
codec: codec,
before: []ClientRequestFunc{},
}
for _, option := range options {
option(c)
}
return c
}
// StreamClientOption sets an optional parameter for clients.
type StreamClientOption func(*StreamClient)
// StreamClientBefore sets the RequestFuncs that are applied to the outgoing request
// before it's invoked.
func StreamClientBefore(before ...ClientRequestFunc) StreamClientOption {
return func(c *StreamClient) { c.before = append(c.before, before...) }
}
// Endpoint returns a usable endpoint that will invoke the wirenet specified
// by the client.
func (c StreamClient) Endpoint() endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
for _, f := range c.before {
ctx = f(ctx)
}
sessionID, ok := ctx.Value(ContextKeySessionID{}).(uuid.UUID)
if !ok {
return nil, ErrSessionIDNotDefined
}
session, err := c.wire.Session(sessionID)
if err != nil {
return nil, err
}
stream, err := session.OpenStream(c.streamName)
if err != nil {
return nil, err
}
defer stream.Close()
return c.codec(ctx, request, stream)
}
}