title: How to make net.Dial in Go reconnect if connection is lost?
body: <p>I have an app in Go that's connecting to XMPP host using tcp and then xml Decoder to talk XMPP. How can I make net.Dial reconnect if tcp connection is dropped?</p>
  
  <p>I am getting the following error on my error channel when the connection is dropped:
  <code>write tcp client:port-&gt;xmpp_server:5222: write: broken pipe</code>. However I'm not sure how to properly handle it in my <code>Dial</code> function to make it reconnect.</p>
  
  <pre><code>// package xmpp
  // Conn represents a connection
  type Conn struct {
      incoming *xml.Decoder
      outgoing net.Conn
      errchan  chan error
  }
  
  // SetErrorChannel sets the channel for handling errors
  func (c *Conn) SetErrorChannel(channel chan error) {
      c.errchan = channel
  }
  
  // Dial dials an xmpp host
  func Dial(host string) (*Conn, error) {
      c := new(Conn)
      var err error
  
      c.outgoing, err = net.Dial("tcp", host+":5222")
      if err != nil {
          log.Printf("Can't dial %s:5222: %s", host, err)
          return c, err
      }
  
      // TCP Keep Alive
      err = c.outgoing.(*net.TCPConn).SetKeepAlive(true)
      if err != nil {
          c.errchan &lt;- err
      }
      err = c.outgoing.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)
      if err != nil {
          c.errchan &lt;- err
      }
  
      c.incoming = xml.NewDecoder(c.outgoing)
      log.Printf("Connected to: %s", c.outgoing.RemoteAddr())
      return c, nil
  }
  
  // In a separate package
  func NewXMPPClient(config) (*Client, error) {
      errchannel := make(chan error)
      connection, err := xmpp.Dial(host)
  
      if err != nil {
          return nil, err
      }
      connection.SetErrorChannel(errchannel)
  
      // Do XMPP auth, receive messages, etc...
  </code></pre>