Added context to http json sender

This commit is contained in:
Quentin Renard
2024-12-03 14:32:02 +01:00
parent a46bce549c
commit 7c3a7f9e4c
2 changed files with 19 additions and 1 deletions

View File

@@ -200,6 +200,7 @@ type HTTPSendJSONOptions struct {
BodyError interface{}
BodyIn interface{}
BodyOut interface{}
Context context.Context
HeadersIn map[string]string
HeadersOut HTTPSenderHeaderFunc
Host string
@@ -222,9 +223,15 @@ func (s *HTTPSender) SendJSON(o HTTPSendJSONOptions) (err error) {
bi = bb
}
// Get context
ctx := o.Context
if ctx == nil {
ctx = context.Background()
}
// Create request
var req *http.Request
if req, err = http.NewRequest(o.Method, o.URL, bi); err != nil {
if req, err = http.NewRequestWithContext(ctx, o.Method, o.URL, bi); err != nil {
err = fmt.Errorf("astikit: creating request failed: %w", err)
return
}

View File

@@ -212,6 +212,17 @@ func TestHTTPSender(t *testing.T) {
}); err != nil {
t.Fatalf("expected no error, got %s", err)
}
// Context
ctx, cancel := context.WithCancel(context.Background())
cancel()
ctxCheckerMockedHTTPClient := mockedHTTPClient(func(req *http.Request) (resp *http.Response, err error) {
return &http.Response{}, req.Context().Err()
})
s5 := NewHTTPSender(HTTPSenderOptions{Client: ctxCheckerMockedHTTPClient})
if err := s5.SendJSON(HTTPSendJSONOptions{Context: ctx}); !errors.Is(err, context.Canceled) {
t.Fatalf("expected context cancelled error, got %s", err)
}
}
func TestHTTPDownloader(t *testing.T) {