/
producer.go
58 lines (46 loc) · 1.11 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
package producer
import (
"log"
"os"
"path/filepath"
"runtime"
"fmt"
ckafka "github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/joho/godotenv"
)
func InitProducer() {
_, b, _, _ := runtime.Caller(0)
basepath := filepath.Dir(b)
err := godotenv.Load(basepath + "/../.env")
if err != nil {
log.Fatalf("Error loading .env files")
}
configMap := &ckafka.ConfigMap{
"bootstrap.servers": os.Getenv("kafkaBootstrapServers"),
}
producer, err := ckafka.NewProducer(configMap)
if err != nil {
panic(err)
}
topic := os.Getenv("kafkaTopic")
msg := "Message chellange-two"
deliveryChan := make(chan ckafka.Event)
message := &ckafka.Message{
TopicPartition: ckafka.TopicPartition{Topic: &topic, Partition: ckafka.PartitionAny},
Value: []byte(msg),
}
err = producer.Produce(message, deliveryChan)
if err != nil {
panic(err)
}
for e := range deliveryChan {
switch ev := e.(type) {
case *ckafka.Message:
if ev.TopicPartition.Error != nil {
fmt.Println("Delivery failed:", ev.TopicPartition)
} else {
fmt.Println("Delivered message:", ev.TopicPartition)
}
}
}
}