mirror of
https://github.com/asticode/go-astikit.git
synced 2025-12-24 11:50:53 +08:00
Added context to http json sender
This commit is contained in:
9
http.go
9
http.go
@@ -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
|
||||
}
|
||||
|
||||
11
http_test.go
11
http_test.go
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user