forked from libp2p/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
46 lines (37 loc) · 921 Bytes
/
pubsub.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
package main
import (
"context"
"fmt"
"os"
"github.com/gogo/protobuf/proto"
pubsub "github.com/libp2p/go-libp2p-pubsub"
peer "github.com/chiangmaioneluv/go-libp2p/core/peer"
)
const pubsubTopic = "/libp2p/example/chat/1.0.0"
func pubsubMessageHandler(id peer.ID, msg *SendMessage) {
fmt.Printf("%s: %s\n", id.ShortString(), msg.Data)
}
func pubsubUpdateHandler(id peer.ID, msg *UpdatePeer) {
}
func pubsubHandler(ctx context.Context, sub *pubsub.Subscription) {
defer sub.Cancel()
for {
msg, err := sub.Next(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
req := &Request{}
err = proto.Unmarshal(msg.Data, req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
switch *req.Type {
case Request_SEND_MESSAGE:
pubsubMessageHandler(msg.GetFrom(), req.SendMessage)
case Request_UPDATE_PEER:
pubsubUpdateHandler(msg.GetFrom(), req.UpdatePeer)
}
}
}