Get list of topics in kafka Golang

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.

go get github.com/Shopify/sarama

Code to list all topics.

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.

Test-1
Test-2

 

Leave a Reply

Your email address will not be published. Required fields are marked *