How to implement mqtt with SSL/TLS certs in Go?

Solution for How to implement mqtt with SSL/TLS certs in Go?
is Given Below:

I’m trying to make a script in Go that will send a message to a mqtt broker with SSL / TLS certificates. I created these certificates with openSSL and tested mqtt communication with mosquitto_sub and mosquitto_pub commands and this works fine, but when I try to send a message with the Go script I get the following error:

network Error : read tcp 192.168.1.243:59454->192.168.1.171:8883: read: connection reset by peer

And in the log of the mosquitto broker, the following message appears:

1627682906: New connection from 192.168.1.243 on port 8883.
1627682906: OpenSSL Error: error:1408F10B:SSL routines:ssl3_get_record:wrong version number
1627682906: Socket error on client , disconnecting.
1627682906: New connection from 192.168.1.243 on port 8883.
1627682906: OpenSSL Error: error:1408F10B:SSL routines:ssl3_get_record:wrong version number
1627682906: Socket error on client , disconnecting.

The code I’m using is the following:

package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "log"

    MQTT "github.com/eclipse/paho.mqtt.golang" // mqtt
)

func main() {
    broker := "192.168.1.171"
    port := "8883"
    topic := "sensor/temperature"

    opts := MQTT.NewClientOptions()
    opts.AddBroker(fmt.Sprintf("tcp://%s:%s", broker, port))
    opts.SetClientID("Device")
    opts.SetUsername("")
    opts.SetPassword("")
    tlsConfig := NewTlsConfig()
    opts.SetTLSConfig(tlsConfig)

    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        log.Println("1. ", token.Error())
    }

    token := client.Publish(topic, 0, false, "36.2")
    token.Wait()

    client.Disconnect(250)
}

func NewTlsConfig() *tls.Config {
    certpool := x509.NewCertPool()
    ca, err := ioutil.ReadFile("/home/pi/server.crt")
    if err != nil {
        log.Fatalln(err.Error())
    }
    certpool.AppendCertsFromPEM(ca)
    return &tls.Config{
        RootCAs: certpool,
    }
}

Am I have any bugs in the code or is there some other way to implement mqtt communication with SSL certificates in Go?

The first issue I noticed is (this may be the only issue or there may be others):

opts.AddBroker(fmt.Sprintf("tcp://%s:%s", broker, port))

Using the url scheme tcp (or mqtt) indicates that you wish to establish an unencrypted connection (the certificate you provide will be ignored). To request MQTT over TLS use one of ssl, tls, mqtts, mqtt+ssl or tcps. For example the demo (which I suspect your code is based on) uses:

opts.AddBroker("ssl://iot.eclipse.org:8883")