CloudAMQP with MQTT and Go Getting started

Currently the most mature client library for Go is org.eclipse.paho.mqtt.golang.

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 (
    "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
    "net/url"
    "fmt"
    "time"
    "os"
)

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


        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)
    client.Start()

    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))
    opts.SetUsername(uri.User.Username())
    password, _ := uri.User.Password()
    opts.SetPassword(password)
    opts.SetClientId(clientId)

    return opts
}