Skip to content

Instantly share code, notes, and snippets.

@fabiocolacio
Created February 20, 2020 04:38
Show Gist options
  • Save fabiocolacio/921be29786cb057f8a208473b04f039c to your computer and use it in GitHub Desktop.
Save fabiocolacio/921be29786cb057f8a208473b04f039c to your computer and use it in GitHub Desktop.
Golang Mqtt
package main
import (
// Install with `go get github.com/eclipse/paho.mqtt.golang
mqtt "github.com/eclipse/paho.mqtt.golang"
"os"
"time"
"fmt"
)
func main() {
defaultHandler := func(c mqtt.Client, m mqtt.Message) {
fmt.Println(m)
}
opts := mqtt.NewClientOptions()
opts.AddBroker("tcp://bastc.local:1883")
opts.SetClientID("go thingy")
opts.SetDefaultPublishHandler(defaultHandler)
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
handleQuit := func(c mqtt.Client, m mqtt.Message) {
os.Exit(0)
}
if token := client.Subscribe("quit", 0, handleQuit); token.Wait() && token.Error() != nil {
panic(token.Error())
}
for {
fmt.Println("Publishing \"hello\" to \"hello\"")
if token := client.Publish("hello", 0, false, "hello"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
}
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment