forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
67 lines (53 loc) · 1.56 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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show to connect and publish/subscribe for messages.
// Message are received asynchronously using a handler function.
package main
import (
"log"
"sync"
"github.com/nats-io/nats"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
func main() {
// Declare the key to use for publishing/subscribing.
const key = "test"
// Connect to the local nats server.
conn, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Println("Unable to connect to NATS")
return
}
// Used to wait for the message to be received.
var wg sync.WaitGroup
wg.Add(1)
// Function is called when new messages are received.
// NOTE: This is bad. Not receiving a value of type Msg.
f := func(m *nats.Msg) {
log.Println("Received a message:", string(m.Data))
wg.Done()
}
// Subscribe to receive messages for the specified key.
sub, err := conn.Subscribe(key, f)
if err != nil {
log.Println("Subscribing for specified key:", err)
return
}
// Publish the string into the message bus under the
// specified key.
if err := conn.Publish(key, []byte("Hello World")); err != nil {
log.Println("Publishing a message for specified key:", err)
return
}
// Wait to be told the message was received.
wg.Wait()
// Unsubscribe from receiving these messages.
if err := sub.Unsubscribe(); err != nil {
log.Println("Error unsubscribing from the bus:", err)
return
}
// Close the connection to the NATS server.
conn.Close()
}