title: How to detect dead RabbitMQ connection?
body: <p>I have a RabbitMQ consumer script in Go. This is a simple script from <a href="https://www.rabbitmq.com/tutorials/tutorial-two-go.html" rel="noreferrer">RabbitMQ tutorial</a> that uses <a href="https://github.com/streadway/amqp" rel="noreferrer"><code>streadway/amqp</code></a> library.</p>
  <p>The problem is that if the RabbitMQ server is stopped, the consumer script does not exit; and when RabbitMQ server is restarted, the consumer does not receive messages anymore.</p>
  <p>Is there a way to detect that the consumer connection is dead and reconnect, or at least terminate the consumer script?</p>
  <p>I know that the library sets a default 10 sec. heartbeat interval for the connection; is it possible to use that someway?</p>
  <pre><code>func main() {
      conn, err := amqp.Dial(&quot;amqp://guest:guest@localhost:5672/&quot;)
      failOnError(err, &quot;Failed to connect to RabbitMQ&quot;)
      defer conn.Close()
  
      ch, err := conn.Channel()
      failOnError(err, &quot;Failed to open a channel&quot;)
      defer ch.Close()
  
      q, err := ch.QueueDeclare(
          &quot;test_task_queue&quot;, // name
          true,         // durable
          false,        // delete when unused
          false,        // exclusive
          false,        // no-wait
          nil,          // arguments
      )
      failOnError(err, &quot;Failed to declare a queue&quot;)
  
      err = ch.Qos(
          1,     // prefetch count
          0,     // prefetch size
          false, // global
      )
      failOnError(err, &quot;Failed to set QoS&quot;)
  
      msgs, err := ch.Consume(
          q.Name, // queue
          &quot;&quot;,     // consumer
          false,  // auto-ack
          false,  // exclusive
          false,  // no-local
          false,  // no-wait
          nil,    // args
      )
      failOnError(err, &quot;Failed to register a consumer&quot;)
  
      forever := make(chan bool)
  
      go func() {
          for d := range msgs {
              log.Printf(&quot;Received a message: %s&quot;, d.Body)
              d.Ack(false)
              dot_count := bytes.Count(d.Body, []byte(&quot;.&quot;))
              t := time.Duration(dot_count)
              time.Sleep(t * time.Second)
              log.Printf(&quot;Done&quot;)
          }
      }()
  
      log.Printf(&quot; [*] Waiting for messages. To exit press CTRL+C&quot;)
      &lt;-forever
  }
  </code></pre>