Skip to content

Instantly share code, notes, and snippets.

@t1minator
Forked from atotto/mqtt_test.go
Created April 20, 2021 16:02
Show Gist options
  • Save t1minator/587ce74543967298a6d2c2a46084bc41 to your computer and use it in GitHub Desktop.
Save t1minator/587ce74543967298a6d2c2a46084bc41 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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment