CloudAMQP with MQTT and Go Getting started

Currently the most mature client library for Go is

Below is a simple example where we every second will publish the current time on the currentTime topic.

We will also setup a subscriber that subscribes to all topics and the prints the payload and topic.

CloudAMQP MQTT URL Structure mqtt://cloudamqp_username:cloudamqp_password@hostname:port

package main

import (

func main() {
    go func(topic string) {
        opts := createClientOptions("sub", os.Getenv("CLOUDAMQP_MQTT_URL"))
        client := mqtt.NewClient(opts)

        t, _ := mqtt.NewTopicFilter(topic, 0)
        client.StartSubscription(func(client *mqtt.MqttClient, msg mqtt.Message) {
            fmt.Println("Topic=", msg.Topic(), "Payload=", string(msg.Payload()))
        }, t)

    timer := time.NewTicker(1 * time.Second)
    opts := createClientOptions("pub", os.Getenv("CLOUDAMQP_MQTT_URL"))
    client := mqtt.NewClient(opts)

    for t := range timer.C {
        client.Publish(0, "currentTime", t.String())

func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
    uri, _ := url.Parse(raw)
    opts := mqtt.NewClientOptions()
    opts.AddBroker(fmt.Sprintf("tcp://%s", uri.Host))
    password, _ := uri.User.Password()

    return opts