I'm new to Go lang and I could use some suggestions on how to refactor the code. All I got to do is depending on the success or error from Sarama (Apache Kafka thing in go) I need to log and forward it further. So far my code looks like this
go func() {
for err := range producer.Errors() {
batchID := err.Msg.Metadata.(ackMeta).batchID # notice the struct here
statusChan := err.Msg.Metadata.(ackMeta).statusChan
statusChan <- false
close(statusChan)
logs.Debug(appName, "Signalled failure on statusChan for batch ", batchID)
logs.Error(appName, "Failed to publish data to analyzer for batchID: ", batchID, err)
}
}()
go func() {
for succ := range producer.Successes() {
batchID := succ.Metadata.(ackMeta).batchID # notice the struct here
statusChan := succ.Metadata.(ackMeta).statusChan
statusChan <- true
close(statusChan)
logs.Debug(appName, "Signalled success on statusChan for batch ", batchID)
logs.Debug(appName, "Successfully published data to analyzer:", succ.Topic, succ.Key, succ.Partition, succ.Offset, succ.Metadata)
}
I think I can do a better job and wrap the whole thing in a single function but so far I can't think of any other apart from using the switch case as shown here
func checkSuccessOrFailAck(msg interface{}) {
switch msgType := msg.(type) {
case producer.Errors:
batchID := msg.Msg.Metadata.(ackMeta).batchID
statusChan := msg.Msg.Metadata.(ackMeta).statusChan
statusChan <- false
close(statusChan)
logs.Debug(appName, "Signalled failure on statusChan for batch ", batchID)
logs.Error(appName, "Failed to publish data to analyzer for batchID: ", batchID, msg)
case producer.Successes:
batchID := msg.Metadata.(ackMeta).batchID
statusChan := msg.Metadata.(ackMeta).statusChan
statusChan <- true
close(statusChan)
logs.Debug(appName, "Signalled success on statusChan for batch ", batchID)
logs.Debug(appName, "Successfully published data to analyzer:", succ.Topic, succ.Key, succ.Partition, succ.Offset, succ.Metadata)
}
}
The types of messages are different and so is the way I extract the attributes from it. But I'm not happy with this approach as the statements are more than the previous one. Could there be a better way to think to write ?