title: Paho MQTT golang for multiple modules?
body: <p>I am writing a microservice in golang for a mqtt module. This module will be used by different function at the same time. I am using Grpc as a transport layer.
  I have made a connect function which is this..</p>
  <pre><code>func Connect() { //it would be Connect(payload1 struct,topic string)
  
      deviceID := flag.String(&quot;device&quot;, &quot;handler-1&quot;, &quot;GCP Device-Id&quot;)
      bridge := struct {
          host *string
          port *string
      }{
          flag.String(&quot;mqtt_host&quot;, &quot;&quot;, &quot;MQTT Bridge Host&quot;),
          flag.String(&quot;mqtt_port&quot;, &quot;&quot;, &quot;MQTT Bridge Port&quot;),
      }
      projectID := flag.String(&quot;project&quot;, &quot;&quot;, &quot;GCP Project ID&quot;)
      registryID := flag.String(&quot;registry&quot;, &quot;&quot;, &quot;Cloud IoT Registry ID (short form)&quot;)
      region := flag.String(&quot;region&quot;, &quot;&quot;, &quot;GCP Region&quot;)
      certsCA := flag.String(&quot;ca_certs&quot;, &quot;&quot;, &quot;Download https://pki.google.com/roots.pem&quot;)
      privateKey := flag.String(&quot;private_key&quot;, &quot;&quot;, &quot;Path to private key file&quot;)
  
      server := fmt.Sprintf(&quot;ssl://%v:%v&quot;, *bridge.host, *bridge.port)
      topic := struct {
          config    string
          telemetry string
      }{
          config:    fmt.Sprintf(&quot;/devices/%v/config&quot;, *deviceID),
          telemetry: fmt.Sprintf(&quot;/devices/%v/events/topic&quot;, *deviceID),
      }
      qos := flag.Int(&quot;qos&quot;, 0, &quot;The QoS to subscribe to messages at&quot;)
      clientid := fmt.Sprintf(&quot;projects/%v/locations/%v/registries/%v/devices/%v&quot;,
          *projectID,
          *region,
          *registryID,
          *deviceID,
      )
      log.Println(&quot;[main] Loading Google's roots&quot;)
      certpool := x509.NewCertPool()
      pemCerts, err := ioutil.ReadFile(*certsCA)
      if err == nil {
          certpool.AppendCertsFromPEM(pemCerts)
      }
  
      log.Println(&quot;[main] Creating TLS Config&quot;)
      config := &amp;tls.Config{
          RootCAs:            certpool,
          ClientAuth:         tls.NoClientCert,
          ClientCAs:          nil,
          InsecureSkipVerify: true,
          Certificates:       []tls.Certificate{},
          MinVersion:         tls.VersionTLS12,
      }
  
      flag.Parse()
  
      connOpts := MQTT.NewClientOptions().
          AddBroker(server).
          SetClientID(clientid).
          SetAutoReconnect(true).
          SetPingTimeout(10 * time.Second).
          SetKeepAlive(10 * time.Second).
          SetDefaultPublishHandler(onMessageReceived).
          SetConnectionLostHandler(connLostHandler).
          SetReconnectingHandler(reconnHandler).
          SetTLSConfig(config)
      connOpts.SetUsername(&quot;unused&quot;)
      ///JWT Generation Starts from Here
      token := jwt.New(jwt.SigningMethodES256)
      token.Claims = jwt.StandardClaims{
          Audience:  *projectID,
          IssuedAt:  time.Now().Unix(),
          ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
      }
      //Reading key file
      log.Println(&quot;[main] Load Private Key&quot;)
      keyBytes, err := ioutil.ReadFile(*privateKey)
      if err != nil {
          log.Fatal(err)
      }
      //Parsing key from file
      log.Println(&quot;[main] Parse Private Key&quot;)
      key, err := jwt.ParseECPrivateKeyFromPEM(keyBytes)
      if err != nil {
          log.Fatal(err)
      }
      //Signing JWT with private key
      log.Println(&quot;[main] Sign String&quot;)
      tokenString, err := token.SignedString(key)
      if err != nil {
          log.Fatal(err)
      }
      //JWT Generation Ends here
  
      connOpts.SetPassword(tokenString)
      connOpts.OnConnect = func(c MQTT.Client) {
          if token := c.Subscribe(topic.config, byte(*qos), nil); token.Wait() &amp;&amp; token.Error() != nil {
              log.Fatal(token.Error())
          }
      }
  
      client := MQTT.NewClient(connOpts)
      if token := client.Connect(); token.Wait() &amp;&amp; token.Error() != nil {
          fmt.Printf(&quot;Not Connected..Retrying...  %s\n&quot;, server)
      } else {
          fmt.Printf(&quot;Connected to %s\n&quot;, server)
      }
  
  }
  </code></pre>
  <p>i am calling this function in go routine in my main.go</p>
  <pre><code>func main() {
      fmt.Println(&quot;Server started at port 5005&quot;)
      lis, err := net.Listen(&quot;tcp&quot;, &quot;0.0.0.0:5005&quot;)
      if err != nil {
          log.Fatalf(&quot;Failed to listen: %v&quot;, err)
      }
      //Creating keepAlive channel for mqttt subscribe
      keepAlive := make(chan os.Signal)
      defer close(keepAlive)
      go func() {
          //checking for internet connection
          for !IsOnline() {
              fmt.Println(&quot;No Internet Connection..Retrying&quot;)
              //looking for internet connection after every 8 seconds
              time.Sleep(8 * time.Second)
          }
          fmt.Println(&quot;Internet connected...connecting to mqtt broker&quot;)
          repositories.Connect()
          //looking for interupt(Ctrl+C)
          value := &lt;-keepAlive
          //If Ctrl+C is pressed then exit the application
          if value == os.Interrupt {
              fmt.Printf(&quot;Exiting the application&quot;)
              os.Exit(3)
          }
      }()
      s := grpc.NewServer()
      MqttRepository := repositories.MqttRepository()
      // It creates a new gRPC server instance
      rpc.NewMqttServer(s, MqttRepository)
      if err := s.Serve(lis); err != nil {
          log.Fatalf(&quot;Failed to serve: %v&quot;, err)
  
      }
  }
  
  func IsOnline() bool {
      timeout := time.Duration(5000 * time.Millisecond)
      client := http.Client{
          Timeout: timeout,
      }
      //default url to check connection is http://google.com
      _, err := client.Get(&quot;https://google.com&quot;)
  
      if err != nil {
          return false
      }
  
      return true
  }
  </code></pre>
  <p>I am using the go routine in my main in order for the application to start on every startup.</p>
  <p>Now I want to use this MQTT Connect function to publish the data from other different functions.</p>
  <p>e.g. Function A can call it like <code>Connect(payload1,topic1)</code> and function B can call it like <code>Connect(payload2,topic2)</code> and then this function should handle the publishing the data into the cloud.</p>
  <p>Should I just add the topic and payload in this Connect function and then call it from another function? or is there any possibility that I can return or export the client as a global and then use it in another function or go routine? I am sorry if my question sound very stupid .. I am not a golang expert..</p>