Skip to main content

Paho MQTT Client with Golang

Mong Kok, Hongkong

Github Repository

In this example we provide example code for TCP, Websocket, TLS, and Websockets protocols to connect to the MQTT Broker. For more documentation on the use of the go paho-mqtt client, see the Go Client - documentation


go version

go version go1.16.6 windows/amd64


  • v1.3.5
  • v1.4.2
  • v0.0.0-20210805182204-aaa1db679c0d
go get
go get
go get


Add your broker data to .main.go:

var Host     = flag.String("host", "", "server hostname or IP")
var Port     = flag.Int("port", 8885, "server port")
var Action   = flag.String("action", "pubsub", "pub/sub/pubsub action")
var Protocol = flag.String("protocol", "ws", "mqtt/mqtts/ws/wss")
var Topic    = flag.String("topic", "cameras/go", "publish/subscribe topic")
var Username = flag.String("username", "admin", "mqtt broker username")
var Password = flag.String("password", "instar", "mqtt broker password")
var Qos      = flag.Int("qos", 1, "MQTT QOS")
var Tls      = flag.Bool("tls", false, "Enable TLS/SSL")
var CaCert   = flag.String("cacert", "./", "tls certificate")

In the example above I am using this Mosquitto broker with active Websocket interface.

go run main.go

Go Paho MQTT Client


You can also override the default values by adding those parameters to the run command:

go run main.go -host "" -port 8885 -protocol 'ws' -action 'pubsub' -topic 'cameras/go' -qos 1 -username 'admin' -password 'instar' -tls false -cacert './'