Skip to content

Instantly share code, notes, and snippets.

@atotto
Created January 25, 2017 09:02
Show Gist options
  • Save atotto/6406c0e579c6cd8c920ba53ba952f0f5 to your computer and use it in GitHub Desktop.
Save atotto/6406c0e579c6cd8c920ba53ba952f0f5 to your computer and use it in GitHub Desktop.
github.com/eclipse/paho.mqtt.golang example
package mqtt_test
import (
"sync"
"testing"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func TestMqttPubSub(t *testing.T) {
const TOPIC = "mytopic/test"
opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883")
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
t.Fatal(token.Error())
}
var wg sync.WaitGroup
wg.Add(1)
if token := client.Subscribe(TOPIC, 0, func(client mqtt.Client, msg mqtt.Message) {
if string(msg.Payload()) != "mymessage" {
t.Fatalf("want mymessage, got %s", msg.Payload())
}
wg.Done()
}); token.Wait() && token.Error() != nil {
t.Fatal(token.Error())
}
if token := client.Publish(TOPIC, 0, false, "mymessage"); token.Wait() && token.Error() != nil {
t.Fatal(token.Error())
}
wg.Wait()
}
@atotto
Copy link
Author

atotto commented Jan 25, 2017

$ sudo docker run -it -p 1883:1883 -p 9001:9001 eclipse-mosquitto
$ go test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment