-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_stream.go
72 lines (61 loc) · 1.87 KB
/
server_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
package wirenettransport
import (
"context"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/transport"
"github.com/mediabuyerbot/go-wirenet"
)
// StreamServer wraps an endpoint and implements wirenet.Handler.
type StreamServer struct {
e endpoint.Endpoint
codec ServerCodec
errorHandler transport.ErrorHandler
before []ServerRequestFunc
}
// NewStreamServer constructs a new server, which implements wraps the provided
// endpoint and implements the Handler interface.
func NewStreamServer(
e endpoint.Endpoint,
codec ServerCodec,
options ...StreamServerOption,
) *StreamServer {
s := &StreamServer{
e: e,
codec: codec,
errorHandler: transport.NewLogErrorHandler(log.NewNopLogger()),
}
for _, option := range options {
option(s)
}
return s
}
// StreamServerOption sets an optional parameter for servers.
type StreamServerOption func(*StreamServer)
// StreamServerErrorHandler is used to handle non-terminal errors. By default,
//non-terminal errors are ignored. This is intended as a diagnostic measure.
func StreamServerErrorHandler(errorHandler transport.ErrorHandler) StreamServerOption {
return func(s *StreamServer) { s.errorHandler = errorHandler }
}
// StreamServerBefore functions are executed on the stream request object before the
// request is decoded.
func StreamServerBefore(before ...ServerRequestFunc) StreamServerOption {
return func(s *StreamServer) { s.before = append(s.before, before...) }
}
// Handle implements the Handler interface.
func (s StreamServer) Handle(ctx context.Context, stream wirenet.Stream) {
defer stream.Close()
for _, f := range s.before {
ctx = f(ctx)
}
request, err := s.codec(ctx, stream)
if err != nil {
s.errorHandler.Handle(ctx, err)
return
}
_, err = s.e(ctx, request)
if err != nil {
s.errorHandler.Handle(ctx, err)
return
}
}