From 6620b6ea3d467ca0b8f0e0aeb6a99961d2577687 Mon Sep 17 00:00:00 2001 From: Peter Grlica Date: Mon, 28 Mar 2022 16:12:37 +0200 Subject: [PATCH] Fixed timeout issues in http request workflow function --- automation/automation/http_request_handler.go | 13 ++++++------ .../automation/http_request_handler_test.go | 21 ++++++++++++++++++- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/automation/automation/http_request_handler.go b/automation/automation/http_request_handler.go index 6f39f638d1..7523f157df 100644 --- a/automation/automation/http_request_handler.go +++ b/automation/automation/http_request_handler.go @@ -41,6 +41,13 @@ func (h httpRequestHandler) send(ctx context.Context, args *httpRequestSendArgs) return nil, err } + if args.Timeout > 0 { + var tfn context.CancelFunc + ctx, tfn = context.WithTimeout(ctx, args.Timeout) + req = req.WithContext(ctx) + defer tfn() + } + rsp, err = http.DefaultClient.Do(req) if err != nil { return @@ -113,12 +120,6 @@ func (h httpRequestHandler) makeRequest(ctx context.Context, args *httpRequestSe return nil, err } - if args.Timeout > 0 { - var tfn context.CancelFunc - ctx, tfn = context.WithTimeout(ctx, args.Timeout) - defer tfn() - } - if args.hasParams { purl, err := url.Parse(args.Url) if err != nil { diff --git a/automation/automation/http_request_handler_test.go b/automation/automation/http_request_handler_test.go index 109aa5d9ca..540e629e17 100644 --- a/automation/automation/http_request_handler_test.go +++ b/automation/automation/http_request_handler_test.go @@ -2,11 +2,14 @@ package automation import ( "context" - "github.com/stretchr/testify/require" + "errors" "io/ioutil" "net/http" "net/url" "testing" + "time" + + "github.com/stretchr/testify/require" ) func TestHttpRequestMaker(t *testing.T) { @@ -35,6 +38,22 @@ func TestHttpRequestMaker(t *testing.T) { r.Equal("http://localhost/test", req.URL.String()) }) + t.Run("basic timeout", func(t *testing.T) { + var ( + r = require.New(t) + ctx = context.Background() + + _, err = httpRequestHandler{}.send(ctx, &httpRequestSendArgs{ + Timeout: time.Nanosecond, + HeaderAuthBearer: "foo", + Url: "http://localhost/test", + Method: "GET", + }) + ) + + r.True(errors.Is(err, context.DeadlineExceeded)) + }) + t.Run("post form", func(t *testing.T) { var ( r = require.New(t)