-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
87 lines (73 loc) · 1.5 KB
/
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
76
77
78
79
80
81
82
83
84
85
86
87
// Package stream encapsulates streams within streams
package stream
import (
"context"
"sync"
"github.com/dreamlu/go-micro/v2/client"
"github.com/dreamlu/go-micro/v2/codec"
"github.com/dreamlu/go-micro/v2/metadata"
"github.com/dreamlu/go-micro/v2/server"
)
type Stream interface {
Context() context.Context
SendMsg(interface{}) error
RecvMsg(interface{}) error
Close() error
}
type stream struct {
Stream
sync.RWMutex
err error
request *request
}
type request struct {
client.Request
context context.Context
}
func (r *request) Codec() codec.Reader {
return r.Request.Codec().(codec.Reader)
}
func (r *request) Header() map[string]string {
md, _ := metadata.FromContext(r.context)
return md
}
func (r *request) Read() ([]byte, error) {
return nil, nil
}
func (s *stream) Request() server.Request {
return s.request
}
func (s *stream) Send(v interface{}) error {
err := s.Stream.SendMsg(v)
if err != nil {
s.Lock()
s.err = err
s.Unlock()
}
return err
}
func (s *stream) Recv(v interface{}) error {
err := s.Stream.RecvMsg(v)
if err != nil {
s.Lock()
s.err = err
s.Unlock()
}
return err
}
func (s *stream) Error() error {
s.RLock()
defer s.RUnlock()
return s.err
}
// New returns a new encapsulated stream
// Proto stream within a server.Stream
func New(service, endpoint string, req interface{}, s Stream) server.Stream {
return &stream{
Stream: s,
request: &request{
context: s.Context(),
Request: client.DefaultClient.NewRequest(service, endpoint, req),
},
}
}