-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (58 loc) · 1.58 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
"github.com/centrifugal/centrifuge-go"
)
// eventHandler implements centrifuge.PublishHandler
type eventHandler struct{}
func (h *eventHandler) OnPublish(sub *centrifuge.Subscription, e centrifuge.PublishEvent) {
log.Printf("Someone says via channel %s: %s", sub.Channel(), string(e.Data))
}
var (
userID string
host string
port string
)
// subscribe creates a subscription to a channel.
func subscribe(client *centrifuge.Client, channel string, handler centrifuge.PublishHandler) error {
sub, err := client.NewSubscription(channel)
if err != nil {
return fmt.Errorf("new subscription: %w", err)
}
sub.OnPublish(handler)
if err = sub.Subscribe(); err != nil {
return fmt.Errorf("subscribe: %w", err)
}
return nil
}
func main() {
flag.StringVar(&userID, "user", "123", "user ID")
flag.StringVar(&host, "host", "localhost", "host of the server")
flag.StringVar(&port, "port", "8888", "port of the server")
flag.Parse()
url := fmt.Sprintf(
"ws://%s/v1/connection/websocket", net.JoinHostPort(host, port),
)
// Create a Centrifuge client.
client := centrifuge.NewJsonClient(url, centrifuge.DefaultConfig())
defer client.Close()
handler := &eventHandler{}
if err := subscribe(client, "broadcast", handler); err != nil {
log.Fatalln(err)
}
if err := subscribe(client, userID, handler); err != nil {
log.Fatalln(err)
}
if err := client.Connect(); err != nil {
log.Fatalln(err)
}
c := make(chan os.Signal, 2)
signal.Notify(c, []os.Signal{os.Interrupt, syscall.SIGTERM}...)
<-c
}