Skip to content

Commit

Permalink
Merge pull request #21 from robert-dzikowski/working_branch
Browse files Browse the repository at this point in the history
Corrected goroutine error handling by using better defer function.
Added const REQUEST_SUCCEEDED.
  • Loading branch information
robert-dzikowski authored Aug 24, 2023
2 parents 7795ad4 + c19afbf commit 91070e7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
32 changes: 25 additions & 7 deletions hrm/HTTPRequestMaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"golang.org/x/exp/slices"
)

const REQUEST_SUCCEEDED = "Success"

type HRM struct {
baseApiUrl string
authToken string
Expand Down Expand Up @@ -45,16 +47,33 @@ func (h *HRM) makeGETRequests(endpoints []string) {
for _, ep := range endpoints {
endPoint := ep
go func() {
fmt.Println("Requesting GET", endPoint)
response := h.sendGETRequest(h.baseApiUrl + endPoint)
response := &http.Response{}

defer func() {
if response.Body != nil {
response.Body.Close()
}

defer response.Body.Close()
x := recover()
if x != nil {
fmt.Printf("Run time panic: %v", x)
c <- "Request to " + endPoint + " was interrupted by an error"
fmt.Println("Error: request to " + endPoint + " was interrupted by an error.")
}
}()

// if endPoint == "/pets/13" {
// panic("Testing defer function.\n")
// }

fmt.Println("Requesting GET", endPoint)
response = h.sendGETRequest(h.baseApiUrl + endPoint)

responseSc := response.StatusCode
requestSucceeded := slices.Contains(h.ScGet, responseSc)

if requestSucceeded {
c <- ""
c <- REQUEST_SUCCEEDED
} else {
fr := fmt.Sprintf("GET %s, sc: %d\n", endPoint, responseSc)
fr = fr + fmt.Sprintf("Response: %s", getResponseBody(response))
Expand All @@ -76,11 +95,10 @@ func (h *HRM) makeGETRequests(endpoints []string) {
} //for

lenEP := len(endpoints)
//fmt.Println("len(endpoints):", lenEP)

for i := 0; i < lenEP; i++ {
result := <-c
if result != "" {
if result != REQUEST_SUCCEEDED {
h.FailedRequestsList = append(h.FailedRequestsList, result)
}
}
Expand Down Expand Up @@ -118,7 +136,7 @@ func (h HRM) sendGETRequest(endPoint string) *http.Response {
if h.authToken != "" {
response, err = GETProtectedResource(endPoint, h.authToken, h.Timeout)
} else {
response, err = GETResource(endPoint, h.Timeout, 3)
response, err = GETResource(endPoint, h.Timeout, 1)
}
CheckError(err)
return response
Expand Down
4 changes: 3 additions & 1 deletion hrm/authutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ func GETProtectedResource(
}
req.Header.Set("Authorization", fmt.Sprintf("Token %s", token))
resp, err := client.Do(req)
if urlErr, ok := err.(*url.Error); ok && urlErr.Timeout() {

urlErr, ok := err.(*url.Error)
if ok && urlErr.Timeout() {
resp = get408Response()
err = nil
}
Expand Down

0 comments on commit 91070e7

Please sign in to comment.