forked from selency/amqp-publish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (88 loc) · 2.07 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
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/streadway/amqp"
)
var (
uri string
exchange string
routingKey string
body string
inputFilePath string
)
func validateFlags() error {
if uri == "" {
return errors.New("uri cannot be blank")
}
if exchange == "" && routingKey == "" {
return errors.New("exchange and routing-key cannot both be blank")
}
if body == "" && inputFilePath == "" {
return errors.New("body and input-file cannot both be blank")
}
return nil
}
func init() {
flag.StringVar(&uri, "uri", "", "AMQP URI amqp://<user>:<password>@<host>:<port>/[vhost]")
flag.StringVar(&exchange, "exchange", "", "Exchange name")
flag.StringVar(&routingKey, "routing-key", "", `Routing key. Use queue
name with blank exchange to publish directly to queue.`)
flag.StringVar(&body, "body", "", "Message body")
flag.StringVar(&inputFilePath, "input-file", "", "Input file path")
flag.Parse()
err := validateFlags()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func getMessages() ([]string, error) {
messages := []string{}
if inputFilePath != "" {
b, err := ioutil.ReadFile(inputFilePath)
if err != nil {
return messages, errors.New("failed to read input file")
}
lines := strings.Split(string(b), "\n")
for _, l := range lines {
if l == "" {
continue
}
messages = append(messages, l)
}
} else {
messages = append(messages, body)
}
return messages, nil
}
func main() {
connection, err := amqp.Dial(uri)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer connection.Close()
channel, _ := connection.Channel()
messages, err := getMessages()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
log.Printf("%d messages to publish", len(messages))
for _, m := range messages {
channel.Publish(exchange, routingKey, false, false, amqp.Publishing{
Headers: amqp.Table{},
ContentType: "text/plain",
ContentEncoding: "",
Body: []byte(m),
DeliveryMode: amqp.Transient,
Priority: 0,
})
}
}