无法使用 paho 库连接到 mosquitto 2.0

Cannot connect to mosquitto 2.0 with paho library

我似乎无法从 golang 的 paho 库(“github.com/eclipse/paho.golang/paho”)连接到 mosquitto 2.0 代理。谁能指出我方法的错误?

我从 paho chat example 获取了连接逻辑并尝试连接到我的本地主机服务器,但收到原因代码 135(未授权)。然后我尝试使用 mosquitto_pub 连接到 mosquitto 服务器并成功。我在这两种情况下都使用了相同的用户名和密码。 mosquitto 日志输出如下:

1608068903: New connection from 127.0.0.1:58794 on port 1883.
1608068903: Client <unknown> disconnected, not authorised.
1608069349: New connection from 127.0.0.1:58908 on port 1883.
1608069349: New client connected from 127.0.0.1:58908 as test (p5, c1, k60, u'username').

我使用的 mosquitto_pub 命令是:

snap run mosquitto.pub -h localhost -t hello -u username -P password -m hello -V mqttv5 -i test

golang代码为:

import (
    "context"
    "fmt"
    "github.com/eclipse/paho.golang/paho"
    log "github.com/sirupsen/logrus"
    "net"
)

func Test() {
    conn, err := net.Dial("tcp", "localhost:1883")
    if err != nil {
        log.Fatalf("Failed to connect to %s: %s", "localhost", err)
    }
    c := paho.NewClient(paho.ClientConfig{
        Router: paho.NewSingleHandlerRouter(func(m *paho.Publish) {
            log.Printf("%s : %s", m.Properties.User["chatname"], string(m.Payload))
        }),
        Conn: conn,
    })

    username := "username"
    password := "password"

    cp := &paho.Connect{
        KeepAlive:  30,
        ClientID:   "test",
        CleanStart: false,
        Username:   username,
        Password:   []byte(password),
    }
    ca, err := c.Connect(context.Background(), cp)
    if ca.ReasonCode != 0 {
        log.Fatalf("Failed to connect to %s : %d - %s", "localhost", ca.ReasonCode, ca.Properties.ReasonString)
    }
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Printf("Connected to %s\n", "localhost")

}

UsernameFlagPasswordFlag 添加到 paho.Connect 例如:

cp := &paho.Connect{
        KeepAlive:  30,
        ClientID:   "test",
        CleanStart: false,
        Username:   username,
        UsernameFlag: true,
        Password:   []byte(password),
        PasswordFlag: true,
    }

paho.golang 文档需要改进,但这已包含在 mqtt v5 spec 中。我已经用 Mosquitto 2.0.1 测试过并成功连接。