CancelableDownload performs an http request and allows for it to be canceled at any time.
(c *HTTPRequestCanceller, do func(req *http.Request) (*http.Response, error), req *http.Request)
| 52 | |
| 53 | // CancelableDownload performs an http request and allows for it to be canceled at any time. |
| 54 | func CancelableDownload(c *HTTPRequestCanceller, do func(req *http.Request) (*http.Response, error), req *http.Request) (*http.Response, chan bool, error) { |
| 55 | chDone := make(chan bool) |
| 56 | ctx, cancel := context.WithCancel(req.Context()) |
| 57 | req = req.WithContext(ctx) |
| 58 | if c != nil { |
| 59 | c.lock.Lock() |
| 60 | c.reqCancel[req] = cancel |
| 61 | c.lock.Unlock() |
| 62 | } |
| 63 | |
| 64 | go func() { |
| 65 | <-chDone |
| 66 | if c != nil { |
| 67 | c.lock.Lock() |
| 68 | cancel() |
| 69 | delete(c.reqCancel, req) |
| 70 | c.lock.Unlock() |
| 71 | } |
| 72 | }() |
| 73 | |
| 74 | resp, err := do(req) |
| 75 | if err != nil { |
| 76 | close(chDone) |
| 77 | return nil, nil, err |
| 78 | } |
| 79 | |
| 80 | return resp, chDone, nil |
| 81 | } |
no test coverage detected
searching dependent graphs…