forked from Azure/azure-service-bus-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto_forward_example_test.go
94 lines (77 loc) · 1.96 KB
/
auto_forward_example_test.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
90
91
92
93
94
package servicebus_test
import (
"context"
"fmt"
"os"
"time"
"github.com/Azure/azure-service-bus-go"
)
type MessagePrinter struct{}
func (mp MessagePrinter) Handle(ctx context.Context, msg *servicebus.Message) error {
fmt.Println(string(msg.Data))
return msg.Complete(ctx)
}
func Example_autoForward() {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING")
if connStr == "" {
fmt.Println("FATAL: expected environment variable SERVICEBUS_CONNECTION_STRING not set")
return
}
// Create a client to communicate with a Service Bus Namespace.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println(err)
return
}
qm := ns.NewQueueManager()
target, err := ensureQueue(ctx, qm, "AutoForwardTargetQueue")
if err != nil {
fmt.Println(err)
return
}
source, err := ensureQueue(ctx, qm, "AutoForwardSourceQueue", servicebus.QueueEntityWithAutoForward(target))
if err != nil {
fmt.Println(err)
return
}
sourceQueue, err := ns.NewQueue(source.Name)
if err != nil {
fmt.Println(err)
return
}
defer func() {
_ = sourceQueue.Close(ctx)
}()
if err := sourceQueue.Send(ctx, servicebus.NewMessageFromString("forward me to target!")); err != nil {
fmt.Println(err)
return
}
targetQueue, err := ns.NewQueue(target.Name)
if err != nil {
fmt.Println(err)
return
}
defer func() {
_ = targetQueue.Close(ctx)
}()
if err := targetQueue.ReceiveOne(ctx, MessagePrinter{}); err != nil {
fmt.Println(err)
return
}
// Output:
// forward me to target!
}
func ensureQueue(ctx context.Context, qm *servicebus.QueueManager, name string, opts ...servicebus.QueueManagementOption) (*servicebus.QueueEntity, error) {
qe, err := qm.Get(ctx, name)
if err == nil {
_ = qm.Delete(ctx, name)
}
qe, err = qm.Put(ctx, name, opts...)
if err != nil {
fmt.Println(err)
return nil, err
}
return qe, nil
}