go-mqtt is a mqtt golang client that implements the mqttv3 and mqttv5 protocols
- basic client
- packet reading and writing
- publish qos 0
- subscribe and unsubscribe
- re-connector
- mqttv3 check
- qos 1 and 2
- prefix tree based message router
- event hook
get package:
go get github.com/lynnplus/go-mqtt
connect to mqtt broker
package main
import (
"github.com/lynnplus/go-mqtt"
"github.com/lynnplus/go-mqtt/packets"
)
func main() {
client := mqtt.NewClient(&mqtt.ConnDialer{
Address: "tcp://127.0.0.1:1883",
}, mqtt.ClientConfig{})
pkt := packets.NewConnect("client_id", "username", []byte("password"))
ack, err := client.Connect(context.Background(), pkt)
if err != nil {
panic(err)
}
if ack.ReasonCode != 0 {
panic(packets.NewReasonCodeError(ack.ReasonCode, ""))
}
//do something
_ = client.Disconnect()
}
The package provides two connection methods, synchronous and asynchronous. When asynchronous, the response result can only be obtained in the callback.
Asynchronous call connection:
package main
func main() {
client := mqtt.NewClient(&mqtt.ConnDialer{
Address: "tcp://127.0.0.1:1883",
}, mqtt.ClientConfig{
OnConnected: func(c *mqtt.Client, ack *packets.Connack) {
fmt.Println(ack.ReasonCode)
},
})
pkt := packets.NewConnect("client_id", "username", []byte("password"))
err := client.StartConnect(context.Background(), pkt)
}
For a basic chat example please see: https://github.com/lynnplus/go-mqtt/blob/master/examples/chat/main.go
The package provides a dialer that implements tcp and tls by default. If the user needs other connection protocol support, such as websocket, the Dialer interface provided in the package can be implemented.
- scram : example
...
...