Azure Service Bus Topic Subscription (Golang)

There are a lot of great resources to consume messages from Azure Service Bus service. The majority of these resources focus only on simple Queue subscription.

The example code uses Azure Service Bus module.

Here’s the code using a topic & subscription:

func main() {
ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    connString := os.Getenv("SERVICE_BUS_CONN_STRING")
    topicName := os.Getenv("SERVICE_BUS_TOPIC")
    subscriptionName := os.Getenv("SERVICE_BUS_SUB_NAME")

    servicebus.NamespaceWithConnectionString(connString),
    )
    if err != nil {
        panic(err)
    }

    // build the topic for sending priority messages
    tm := ns.NewTopicManager()
    fmt.Println("gateway/azure_iot_hub: setting up topic manager")
    te, err := tm.Get(ctx, topicName)
    if err != nil {
        panic(err)
    }

    topic, err := ns.NewTopic(te.Name)
    sub, err := topic.NewSubscription(subscriptionName)
    if err != nil {
        fmt.Println(err)
        return
    }

        var messageHandler servicebus.HandlerFunc = func(ctx context.Context, msg *servicebus.Message) error {
    fmt.Println(msg)

    return msg.Complete(ctx)
}

    err = sub.Receive(ctx, messageHandler)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer func() {
        _ = sub.Close(ctx)
    }()
}

Leave a Reply

Your email address will not be published.