forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (51 loc) · 1.51 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
// 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 subject to use for publishing/subscribing.
const subject = "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.
f := func(m *nats.Msg) {
log.Println("Received a message:", string(m.Data))
wg.Done()
}
// Subscribe to receive messages for the specified subject.
sub, err := conn.Subscribe(subject, f)
if err != nil {
log.Println("Subscribing for specified subject:", err)
return
}
// Publish the message for the specified subject.
if err := conn.Publish(subject, []byte("Hello World")); err != nil {
log.Println("Publishing a message for specified subject:", 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()
}