Heads up! This post was written 3 years ago. Some information might be outdated or may have changed since then.

MQTT is a lightweight, publish-subscribe network protocol that transports messages between devices. Golang has a very nice client which can be easily used for the purpose.

For example here is how to send data to my public free MQTT Broker - xMQTT

package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
)

func main() {
	var broker = "broker.xmqtt.net"
	var port = 8883

	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcps://%s:%d", broker, port))
	opts.OnConnect = func(client mqtt.Client) {
		log.Println("Connected")
	}
	client := mqtt.NewClient(opts)
	
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	
	for i := 0; i < 100; i++ {
		t := client.Publish("/random/test", 0, false, fmt.Sprintf("event_id %d", i))
		t.Wait()
	}
	
	client.Disconnect(5)
	log.Println("Events sent")
}

Back to all posts