From 4afb8f6460dcaf7052303aaebffedb72834205ec Mon Sep 17 00:00:00 2001 From: Tibz-Dankan Date: Thu, 12 Sep 2024 23:11:23 +0300 Subject: [PATCH] fix: add a retry request incase of an error --- internal/services/httpRequest.go | 47 +++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/internal/services/httpRequest.go b/internal/services/httpRequest.go index 9774681..71de577 100644 --- a/internal/services/httpRequest.go +++ b/internal/services/httpRequest.go @@ -1,9 +1,12 @@ package services import ( + "fmt" + "io" "log" "net" "net/http" + "os" "time" ) @@ -20,6 +23,7 @@ func MakeHTTPRequest(URL string) (Response, error) { req, err := http.NewRequest(http.MethodGet, URL, nil) if err != nil { + log.Printf("Error creating request: %v", err) return response, err } @@ -43,10 +47,18 @@ func MakeHTTPRequest(URL string) (Response, error) { requestTimeMS := int(duration.Milliseconds()) if err != nil { + log.Printf("Error making request: %v", err) if isTimeoutError(err) { + retryBaseURL := os.Getenv("APPCRONS_RETRY_URL") + retryURL := fmt.Sprintf("%s?url=%s", retryBaseURL, URL) + + if err := MakeHTTPRetryRequest(retryURL); err != nil { + return response, err + } response.StatusCode = 503 response.RequestTimeMS = requestTimeMS response.StartedAt = startTime + response.Message = "Request timeout" return response, nil } return response, err @@ -59,8 +71,41 @@ func MakeHTTPRequest(URL string) (Response, error) { return response, nil } +func MakeHTTPRetryRequest(URL string) error { + req, err := http.NewRequest(http.MethodGet, URL, nil) + if err != nil { + log.Printf("Error creating request: %v", err) + return err + } + req.Header.Set("Content-Type", "application/json") + + transport := &http.Transport{ + DialContext: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + TLSHandshakeTimeout: 10 * time.Second, + } + + client := &http.Client{ + Transport: transport, + Timeout: time.Second * 35, + } + + res, err := client.Do(req) + + if err != nil { + return err + } + defer res.Body.Close() + + body, _ := io.ReadAll(res.Body) + log.Printf("Response Body: %s", string(body)) + + return nil +} + func isTimeoutError(err error) bool { - log.Println("Timeout error: ", err) e, ok := err.(net.Error) return ok && e.Timeout() }