Skip to content

Commit

Permalink
Merge pull request #174 from Tibz-Dankan/switch/sqlite
Browse files Browse the repository at this point in the history
fix: add a retry request incase of an error
  • Loading branch information
Tibz-Dankan authored Sep 12, 2024
2 parents 4f763dc + 4afb8f6 commit 74a1fac
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion internal/services/httpRequest.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package services

import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"time"
)

Expand All @@ -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
}

Expand All @@ -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
Expand All @@ -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()
}

0 comments on commit 74a1fac

Please sign in to comment.