Skip to content

Commit

Permalink
Merge pull request #21 from elisasre/fixtests
Browse files Browse the repository at this point in the history
Exit if context is closed
  • Loading branch information
zetaab authored Nov 28, 2022
2 parents 7eb5c0c + 3673b82 commit 8297621
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
12 changes: 11 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -47,7 +48,13 @@ type Backoff struct {
}

// MakeRequest ...
func MakeRequest(ctx context.Context, request HTTPRequest, output interface{}, client *http.Client, backoff Backoff) (*HTTPResponse, error) {
func MakeRequest(
ctx context.Context,
request HTTPRequest,
output interface{},
client *http.Client,
backoff Backoff,
) (*HTTPResponse, error) {
httpresp := &HTTPResponse{}
err := SleepUntil(backoff, func() (bool, error) {
httpreq, err := http.NewRequest(request.Method, request.URL, nil)
Expand Down Expand Up @@ -79,6 +86,9 @@ func MakeRequest(ctx context.Context, request HTTPRequest, output interface{}, c
Str("url", request.URL).
Str("error", err.Error()).
Msg("do request error")
if errors.Is(err, context.DeadlineExceeded) {
return true, err
}
return false, err
}
defer resp.Body.Close()
Expand Down
21 changes: 20 additions & 1 deletion request_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package common

import (
"context"
"fmt"
"net/http"
"time"
Expand All @@ -18,7 +19,9 @@ func ExampleMakeRequest() {
}
out := Out{}
client := &http.Client{}
ctx := context.Background()
body, err := MakeRequest(
ctx,
HTTPRequest{
URL: "https://ingress-api.csf.elisa.fi/healthz",
Method: "GET",
Expand All @@ -29,10 +32,26 @@ func ExampleMakeRequest() {
backoff,
)

fmt.Printf("%s\n%s\n%d\n%v", out.Message, body.Body, body.StatusCode, err)
fmt.Printf("%s\n%s\n%d\n%v\n", out.Message, body.Body, body.StatusCode, err)

ctx, cancel := context.WithTimeout(ctx, 1*time.Millisecond)
defer cancel()
_, err = MakeRequest(
ctx,
HTTPRequest{
URL: "https://ingress-api.csf.elisa.fi/healthz",
Method: "GET",
OKCode: []int{200},
},
&out,
client,
backoff,
)

fmt.Printf("%v", err)
// Output: pong
// {"message":"pong","error":""}
// 200
// <nil>
// Get "https://ingress-api.csf.elisa.fi/healthz": context deadline exceeded
}
2 changes: 1 addition & 1 deletion time.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func SleepUntil(backoff Backoff, condition ConditionFunc) error {

}
if err != nil {
return errors.Wrap(err, "retrying timed out")
return err
}
return errors.New("Timed out waiting for the condition")
}

0 comments on commit 8297621

Please sign in to comment.