-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (103 loc) · 2.09 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Copyright (c) 2016, M Bogus.
// This source file is part of the AMQP-ECHO open source project
// Licensed under Apache License v2.0
// See LICENSE file for license information
package main
import (
"flag"
"log"
"time"
"github.com/streadway/amqp"
)
var (
uriParam string
queueNameParam string
delayParam int
)
func init() {
flag.StringVar(&uriParam, "uri", "", "RabbitMQ broker URI")
flag.StringVar(&queueNameParam, "queue", "", "RabbitMQ queue")
flag.IntVar(&delayParam, "delay", 30, "delay in consuming of messages")
}
func main() {
flag.Parse()
forever := make(chan struct{})
log.SetFlags(0)
for {
select {
case <-forever:
return
case <-time.After(time.Duration(delayParam) * time.Second):
err := listen(uriParam, queueNameParam)
if err != nil {
log.Print(err)
}
}
}
}
func listen(uri string, queue string) error {
connErr := make(chan *amqp.Error)
forever := make(chan struct{})
var err error
go func() {
e := <-connErr
err = e
close(forever)
}()
conn, err := amqp.Dial(uri)
if err != nil {
return err
}
defer conn.Close()
conn.NotifyClose(connErr)
ch, err := conn.Channel()
if err != nil {
return err
}
defer ch.Close()
q, err := ch.QueueDeclare(
queue, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return err
}
go func() {
for d := range msgs {
log.Printf("Received a message: '%s'", d.Body)
if d.ReplyTo != "" {
if e := ch.Publish(
"", // exchange
d.ReplyTo, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: d.ContentType,
Body: d.Body,
}); err != nil {
err = e
}
}
d.Ack(false)
conn.Close()
return
}
}()
log.Printf(" [*] Waiting for messages on '%s'.", q.Name)
<-forever
log.Printf(" [*] Exiting waiting.")
return err
}