-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
65 lines (53 loc) · 1.22 KB
/
producer.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
package main
import (
"bufio"
"fmt"
"log/slog"
"os"
"github.com/IBM/sarama"
"github.com/spf13/cobra"
)
func producerCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "producer",
Short: "producer",
Run: func(cmd *cobra.Command, args []string) {
},
}
cmd.AddCommand(producerConsoleCmd())
return cmd
}
func producerConsoleCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "console",
RunE: func(cmd *cobra.Command, args []string) error {
producer, err := newSyncProducer()
if err != nil {
return fmt.Errorf("newSyncProducer error: %w", err)
}
defer func() {
if err := producer.Close(); err != nil {
slog.Error("producer.Close failed", err)
}
}()
topic, err := cmd.Flags().GetString("topic")
if err != nil {
return fmt.Errorf("get topic flag error: %w", err)
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
msg := &sarama.ProducerMessage{
Topic: topic,
Value: sarama.StringEncoder(scanner.Text()),
}
_, _, err := producer.SendMessage(msg)
if err != nil {
slog.Error("producer.SendMessage failed", err)
}
}
return nil
},
}
cmd.Flags().StringP("topic", "t", "", "The topic to produce messages to.")
return cmd
}