github.com/evrenkutar/randevent@v0.0.0-20210506235643-7d1e39a375e1/cmd/emitter.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "github.com/brianvoe/gofakeit/v6" 6 "github.com/evrenkutar/randevent/pb/github.com/evrenkutar/randevent/pb" 7 "google.golang.org/protobuf/types/known/timestamppb" 8 "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" 9 "time" 10 ) 11 12 type Emitter struct { 13 tickChan chan time.Time 14 doneChan chan bool 15 kafkaProducer *kafka.Producer 16 } 17 18 func (e *Emitter) emit() { 19 go func() { 20 for e := range e.kafkaProducer.Events() { 21 switch ev := e.(type) { 22 case *kafka.Message: 23 if ev.TopicPartition.Error != nil { 24 fmt.Printf("Delivery failed: %v\n", ev.TopicPartition) 25 } else { 26 fmt.Printf("Delivered message to %v\n", ev.TopicPartition) 27 } 28 } 29 } 30 }() 31 for { 32 select { 33 case <-e.tickChan: 34 event := generateNewEvent() 35 topic := "testTopic" 36 e.kafkaProducer.Produce(&kafka.Message{ 37 TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, 38 Value: []byte(event), 39 }, nil) 40 case e.doneChan <- true: 41 return 42 } 43 } 44 45 } 46 47 func generateNewEvent() string { 48 p := pb.PersonCreated{ 49 Uuid: gofakeit.UUID(), 50 Firstname: gofakeit.Name(), 51 Lastname: gofakeit.LastName(), 52 CreatedAt: timestamppb.Now(), 53 } 54 return p.String() 55 }