Get list of topics in kafka Golang
There are different library available in Golang to publish and subscribe topics in kafka. In this example, we are using sarama library to list all the available topic at kafka broker.
To get sarama library, run below command.
1 |
go get github.com/Shopify/sarama |
Code to list all topics.
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 |
package main import ( "fmt" "github.com/Shopify/sarama" ) func main() { config := sarama.NewConfig() config.Consumer.Return.Errors = true //kafka end point brokers := []string{"localhost:9093"} //get broker cluster, err := sarama.NewConsumer(brokers, config) if err != nil { panic(err) } defer func() { if err := cluster.Close(); err != nil { panic(err) } }() //get all topic from cluster topics, _ := cluster.Topics() for index := range topics { fmt.Println(topics[index]) } } |
Running above code produces below output on my machine. Because, I have two topics(Test – 1 and Test-2) available with my kafka broker.
1 2 |
Test-1 Test-2 |