Main connect function. Will connect to the nats-server.
()
| 2777 | |
| 2778 | // Main connect function. Will connect to the nats-server. |
| 2779 | func (nc *Conn) connect() (bool, error) { |
| 2780 | var err error |
| 2781 | var connectionEstablished bool |
| 2782 | |
| 2783 | // Create actual socket connection |
| 2784 | // For first connect we walk all servers in the pool and try |
| 2785 | // to connect immediately. |
| 2786 | nc.mu.Lock() |
| 2787 | defer nc.mu.Unlock() |
| 2788 | nc.initc = true |
| 2789 | // The pool may change inside the loop iteration due to INFO protocol. |
| 2790 | for i := 0; i < len(nc.srvPool); i++ { |
| 2791 | nc.current = nc.srvPool[i] |
| 2792 | |
| 2793 | if err = nc.createConn(); err == nil { |
| 2794 | // This was moved out of processConnectInit() because |
| 2795 | // that function is now invoked from doReconnect() too. |
| 2796 | nc.setup() |
| 2797 | |
| 2798 | err = nc.processConnectInit() |
| 2799 | |
| 2800 | if err == nil { |
| 2801 | nc.current.didConnect = true |
| 2802 | nc.current.Reconnects = 0 |
| 2803 | nc.current.lastErr = nil |
| 2804 | break |
| 2805 | } else { |
| 2806 | nc.mu.Unlock() |
| 2807 | nc.close(DISCONNECTED, false, err) |
| 2808 | nc.mu.Lock() |
| 2809 | // Do not reset nc.current here since it would prevent |
| 2810 | // RetryOnFailedConnect to work should this be the last server |
| 2811 | // to try before starting doReconnect(). |
| 2812 | } |
| 2813 | } else { |
| 2814 | // Cancel out default connection refused, will trigger the |
| 2815 | // No servers error conditional |
| 2816 | if strings.Contains(err.Error(), "connection refused") { |
| 2817 | err = nil |
| 2818 | } |
| 2819 | } |
| 2820 | } |
| 2821 | |
| 2822 | if err == nil && nc.status != CONNECTED { |
| 2823 | err = ErrNoServers |
| 2824 | } |
| 2825 | |
| 2826 | if err == nil { |
| 2827 | connectionEstablished = true |
| 2828 | nc.initc = false |
| 2829 | } else if nc.Opts.RetryOnFailedConnect { |
| 2830 | nc.setup() |
| 2831 | nc.changeConnStatus(RECONNECTING) |
| 2832 | nc.bw.switchToPending() |
| 2833 | go nc.doReconnect(err, false) |
| 2834 | err = nil |
| 2835 | } else { |
| 2836 | nc.current = nil |
no test coverage detected