diff options
author | Dominik Picheta <dominikpicheta@googlemail.com> | 2018-01-18 13:08:35 +0000 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2018-01-18 14:08:35 +0100 |
commit | ef196340659af5a22c9149e7dd81aebddd5ec660 (patch) | |
tree | e4f57442f8c672aa150f4bd498131adb0b9cd72e /lib | |
parent | 090d22c71518babf662e55e971f9382e0d993052 (diff) | |
download | Nim-ef196340659af5a22c9149e7dd81aebddd5ec660.tar.gz |
Workaround 'defer' issue in httpclient.downloadFile. Refs #3877. (#7101)
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/httpclient.nim | 45 |
1 files changed, 32 insertions, 13 deletions
diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index aefcff37a..4c40a81fe 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -1263,21 +1263,30 @@ proc postContent*(client: HttpClient | AsyncHttpClient, url: string, else: return await resp.bodyStream.readAll() -proc downloadFile*(client: HttpClient | AsyncHttpClient, - url: string, filename: string): Future[void] {.multisync.} = +proc downloadFile*(client: HttpClient, url: string, filename: string) = ## Downloads ``url`` and saves it to ``filename``. client.getBody = false defer: client.getBody = true - let resp = await client.get(url) - - when client is HttpClient: - client.bodyStream = newFileStream(filename, fmWrite) - if client.bodyStream.isNil: - fileError("Unable to open file") - parseBody(client, resp.headers, resp.version) - client.bodyStream.close() - else: + let resp = client.get(url) + + client.bodyStream = newFileStream(filename, fmWrite) + if client.bodyStream.isNil: + fileError("Unable to open file") + parseBody(client, resp.headers, resp.version) + client.bodyStream.close() + + if resp.code.is4xx or resp.code.is5xx: + raise newException(HttpRequestError, resp.status) + +proc downloadFile*(client: AsyncHttpClient, url: string, + filename: string): Future[void] = + proc downloadFileEx(client: AsyncHttpClient, + url, filename: string): Future[void] {.async.} = + ## Downloads ``url`` and saves it to ``filename``. + client.getBody = false + let resp = await client.get(url) + client.bodyStream = newFutureStream[string]("downloadFile") var file = openAsync(filename, fmWrite) # Let `parseBody` write response data into client.bodyStream in the @@ -1288,5 +1297,15 @@ proc downloadFile*(client: HttpClient | AsyncHttpClient, await file.writeFromStream(client.bodyStream) file.close() - if resp.code.is4xx or resp.code.is5xx: - raise newException(HttpRequestError, resp.status) + if resp.code.is4xx or resp.code.is5xx: + raise newException(HttpRequestError, resp.status) + + result = newFuture[void]("downloadFile") + try: + result = downloadFileEx(client, url, filename) + except Exception as exc: + result.fail(exc) + finally: + result.addCallback( + proc () = client.getBody = true + ) \ No newline at end of file |