title: golang mqtt publish and subscribe
body: <p>Does anybody know where I can get some example MQTT client Go (golang) code that does both publish and subscribe in an infinite loop ?</p>
  
  <p>I am messaging with a Mosquitto broker running on MacOs.</p>
  
  <p>In more detail... </p>
  
  <ol>
  <li>Get a message from the network (a topic)</li>
  <li>Compute something based on that message</li>
  <li>Send the result of the computation back to the network (topic)</li>
  </ol>
  
  <p>Here is the code I am using:</p>
  
  <pre><code>package main
  
  import (
  "fmt"
   MQTT "github.com/eclipse/paho.mqtt.golang"
  "os"
  "time"
  )
  
  var knt int
  
  var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) 
  { 
     fmt.Printf("MSG: %s\n", msg.Payload())
     text:= fmt.Sprintf("this is result msg #%d!", knt)
     knt++
     token := client.Publish("nn/result", 0, false, text)
     token.Wait()
  }
  
  func main() {
     knt = 0
  
     opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
     opts.SetClientID("mac-go")
     opts.SetDefaultPublishHandler(f)
  
     c := MQTT.NewClient(opts)
     if token := c.Connect(); token.Wait() &amp;&amp; token.Error() != nil {
          panic(token.Error())
     }
  
    if token := c.Subscribe("nn/sensors", 0, nil); token.Wait() &amp;&amp; 
       token.Error() != nil {
       fmt.Println(token.Error())
       os.Exit(1)
    }
  
    time.Sleep(3 * time.Second)
  } //end of main
  </code></pre>
  
  <p>I looked through the GoDocs for some hint as to how to keep the connections open but nothing seems pertinent. I can certainly do an infinite loop 
  over the 'subscribe' but that seems inefficient. </p>