From b46d3b802f9620ee43c2f6d173a54f74af9d2362 Mon Sep 17 00:00:00 2001 From: dingjun Date: Mon, 19 Apr 2021 13:40:33 +0800 Subject: [PATCH] add retry logical --- handler.go | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/handler.go b/handler.go index 58ab149..63d3529 100644 --- a/handler.go +++ b/handler.go @@ -49,6 +49,9 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { tr := &http.Transport{ DialContext: localDialer, } + + log.Debugf("%s %s", r.Method, r.RequestURI) + resp, err := tr.RoundTrip(r) if err != nil { log.Errorln(err) @@ -70,22 +73,30 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { io.Copy(w, resp.Body) } -func handleConnect(w http.ResponseWriter, r *http.Request) { - ip := getLocalIP() +func mydail(uri string) (net.Conn, error) { + addr := &net.TCPAddr{} + dialer := &net.Dialer{ + LocalAddr: addr, + Timeout: 3 * time.Second, + } - log.Debugf("connect to %s, use local ip %s", r.RequestURI, ip) + for i := 0; i < 3; i++ { + ip := getLocalIP() + addr.IP = net.ParseIP(ip) - addr := &net.TCPAddr{ - IP: net.ParseIP(ip), - Port: 0, - } + log.Debugf("connect to %s, use local ip %s", uri, ip) - dialer := &net.Dialer{ - LocalAddr: addr, - Timeout: 10 * time.Second, + conn, err := dialer.Dial("tcp", uri) + if err == nil { + return conn, err + } + log.Errorf("connect to %s, %s, retrying", uri, err) } + return nil, fmt.Errorf("connect to %s, max retries reached, give up", uri) +} - conn, err := dialer.Dial("tcp", r.RequestURI) +func handleConnect(w http.ResponseWriter, r *http.Request) { + conn, err := mydail(r.RequestURI) if err != nil { log.Errorln(err) http.Error(w, "connection failed", http.StatusBadGateway)