-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.go
68 lines (54 loc) · 1.09 KB
/
util.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
package bifrost
import (
"context"
"encoding/json"
"time"
"github.com/DE-labtory/bifrost/pb"
)
func RecvWithTimeout(timeout time.Duration, stream Stream) (*pb.Envelope, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
c := make(chan *pb.Envelope, 1)
errch := make(chan error, 1)
go func() {
envelope, err := stream.Recv()
if err != nil {
errch <- err
}
c <- envelope
}()
select {
case <-ctx.Done():
//timeoutted body
return nil, ctx.Err()
case err := <-errch:
return nil, err
case ok := <-c:
//okay body
return ok, nil
}
}
type KeyOpts struct {
PriKey Key
PubKey Key
}
func BuildResponsePeerInfo(ip string, pubKey Key, metaData map[string]string) (*pb.Envelope, error) {
b, err := pubKey.ToByte()
if err != nil {
return nil, err
}
pi := &PeerInfo{
IP: ip,
PubKeyBytes: b,
IsPrivate: pubKey.IsPrivate(),
MetaData: metaData,
}
payload, err := json.Marshal(pi)
if err != nil {
return nil, err
}
return &pb.Envelope{
Payload: payload,
Type: pb.Envelope_RESPONSE_PEERINFO,
}, nil
}