-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
53 lines (43 loc) · 1.23 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
package main
import (
"log"
"time"
"github.com/amirhnajafiz/emqx/internal/config"
"github.com/amirhnajafiz/emqx/internal/emqx"
"github.com/amirhnajafiz/emqx/internal/model"
)
// defaultHandler is used to handle input messages from
// subscription channel.
func defaultHandler(channel chan *model.Message) {
go func() {
for {
msg := <-channel
log.Printf("received message from topic: `%s`\n\t%s\n", msg.Topic, string(msg.Payload))
}
}()
}
func main() {
// load configurations
cfg := config.Load()
// create a channel
channel := make(chan *model.Message)
// connect to emqx cluster
client, err := emqx.New(cfg.EMQX, channel)
if err != nil {
log.Fatalf("failed to connect to emqx cluster: %v", err)
}
// create a new handler
defaultHandler(channel)
// subscribe on a topic
if token := client.Subscribe(cfg.Topic); token.Wait() || token.Error() != nil {
log.Fatalf("failed to subscribe over `%s`: %v", cfg.Topic, token.Error())
}
// publish events in period
tk := time.NewTicker(time.Duration(cfg.Interval) * time.Millisecond)
for {
<-tk.C
if token := client.Publish(cfg.Message, cfg.Topic); token.Wait() || token.Error() != nil {
log.Printf("failed to publish over `%s`: %v", cfg.Topic, token.Error())
}
}
}