forked from Azure/azure-service-bus-go
/
main.go
89 lines (75 loc) · 1.81 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/Azure/azure-service-bus-go"
)
func main() {
// Connect
connStr := mustGetenv("SERVICEBUS_CONNECTION_STRING")
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
queueName := "helloworld"
q, err := getQueue(ns, queueName)
if err != nil {
fmt.Printf("failed to build a new queue named %q\n", queueName)
os.Exit(1)
}
exit := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
listenHandle, err := q.Receive(ctx, func(ctx context.Context, message *servicebus.Message) servicebus.DispositionAction {
text := string(message.Data)
if text == "exit\n" {
fmt.Println("Oh snap!! Someone told me to exit!")
exit <- *new(struct{})
} else {
fmt.Println(string(message.Data))
}
return message.Complete()
})
defer listenHandle.Close(context.Background())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("I am listening...")
select {
case <-exit:
fmt.Println("closing after 2 seconds")
select {
case <-time.After(2 * time.Second):
listenHandle.Close(context.Background())
return
}
}
}
func getQueue(ns *servicebus.Namespace, queueName string) (*servicebus.Queue, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
qm := ns.NewQueueManager()
qe, err := qm.Get(ctx, queueName)
if err != nil {
return nil, err
}
if qe == nil {
_, err := qm.Put(ctx, queueName)
if err != nil {
return nil, err
}
}
q, err := ns.NewQueue(ctx, queueName)
return q, err
}
func mustGetenv(key string) string {
v := os.Getenv(key)
if v == "" {
panic("Environment variable '" + key + "' required for integration tests.")
}
return v
}