httpclient.nim 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple HTTP client that can be used to retrieve
  10. ## webpages and other data.
  11. ##
  12. ## Retrieving a website
  13. ## ====================
  14. ##
  15. ## This example uses HTTP GET to retrieve
  16. ## `http://google.com`:
  17. ##
  18. ## .. code-block:: Nim
  19. ## import std/httpclient
  20. ## var client = newHttpClient()
  21. ## echo client.getContent("http://google.com")
  22. ##
  23. ## The same action can also be performed asynchronously, simply use the
  24. ## `AsyncHttpClient`:
  25. ##
  26. ## .. code-block:: Nim
  27. ## import std/[asyncdispatch, httpclient]
  28. ##
  29. ## proc asyncProc(): Future[string] {.async.} =
  30. ## var client = newAsyncHttpClient()
  31. ## return await client.getContent("http://example.com")
  32. ##
  33. ## echo waitFor asyncProc()
  34. ##
  35. ## The functionality implemented by `HttpClient` and `AsyncHttpClient`
  36. ## is the same, so you can use whichever one suits you best in the examples
  37. ## shown here.
  38. ##
  39. ## **Note:** You need to run asynchronous examples in an async proc
  40. ## otherwise you will get an `Undeclared identifier: 'await'` error.
  41. ##
  42. ## Using HTTP POST
  43. ## ===============
  44. ##
  45. ## This example demonstrates the usage of the W3 HTML Validator, it
  46. ## uses `multipart/form-data` as the `Content-Type` to send the HTML to be
  47. ## validated to the server.
  48. ##
  49. ## .. code-block:: Nim
  50. ## var client = newHttpClient()
  51. ## var data = newMultipartData()
  52. ## data["output"] = "soap12"
  53. ## data["uploaded_file"] = ("test.html", "text/html",
  54. ## "<html><head></head><body><p>test</p></body></html>")
  55. ##
  56. ## echo client.postContent("http://validator.w3.org/check", multipart=data)
  57. ##
  58. ## To stream files from disk when performing the request, use `addFiles`.
  59. ##
  60. ## **Note:** This will allocate a new `Mimetypes` database every time you call
  61. ## it, you can pass your own via the `mimeDb` parameter to avoid this.
  62. ##
  63. ## .. code-block:: Nim
  64. ## let mimes = newMimetypes()
  65. ## var client = newHttpClient()
  66. ## var data = newMultipartData()
  67. ## data.addFiles({"uploaded_file": "test.html"}, mimeDb = mimes)
  68. ##
  69. ## echo client.postContent("http://validator.w3.org/check", multipart=data)
  70. ##
  71. ## You can also make post requests with custom headers.
  72. ## This example sets `Content-Type` to `application/json`
  73. ## and uses a json object for the body
  74. ##
  75. ## .. code-block:: Nim
  76. ## import std/[httpclient, json]
  77. ##
  78. ## let client = newHttpClient()
  79. ## client.headers = newHttpHeaders({ "Content-Type": "application/json" })
  80. ## let body = %*{
  81. ## "data": "some text"
  82. ## }
  83. ## let response = client.request("http://some.api", httpMethod = HttpPost, body = $body)
  84. ## echo response.status
  85. ##
  86. ## Progress reporting
  87. ## ==================
  88. ##
  89. ## You may specify a callback procedure to be called during an HTTP request.
  90. ## This callback will be executed every second with information about the
  91. ## progress of the HTTP request.
  92. ##
  93. ## .. code-block:: Nim
  94. ## import std/[asyncdispatch, httpclient]
  95. ##
  96. ## proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
  97. ## echo("Downloaded ", progress, " of ", total)
  98. ## echo("Current rate: ", speed div 1000, "kb/s")
  99. ##
  100. ## proc asyncProc() {.async.} =
  101. ## var client = newAsyncHttpClient()
  102. ## client.onProgressChanged = onProgressChanged
  103. ## discard await client.getContent("http://speedtest-ams2.digitalocean.com/100mb.test")
  104. ##
  105. ## waitFor asyncProc()
  106. ##
  107. ## If you would like to remove the callback simply set it to `nil`.
  108. ##
  109. ## .. code-block:: Nim
  110. ## client.onProgressChanged = nil
  111. ##
  112. ## .. warning:: The `total` reported by httpclient may be 0 in some cases.
  113. ##
  114. ##
  115. ## SSL/TLS support
  116. ## ===============
  117. ## This requires the OpenSSL library. Fortunately it's widely used and installed
  118. ## on many operating systems. httpclient will use SSL automatically if you give
  119. ## any of the functions a url with the `https` schema, for example:
  120. ## `https://github.com/`.
  121. ##
  122. ## You will also have to compile with `ssl` defined like so:
  123. ## `nim c -d:ssl ...`.
  124. ##
  125. ## Certificate validation is performed by default.
  126. ##
  127. ## A set of directories and files from the `ssl_certs <ssl_certs.html>`_
  128. ## module are scanned to locate CA certificates.
  129. ##
  130. ## Example of setting SSL verification parameters in a new client:
  131. ##
  132. ## .. code-block:: Nim
  133. ## import httpclient
  134. ## var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeer))
  135. ##
  136. ## There are three options for verify mode:
  137. ##
  138. ## * ``CVerifyNone``: certificates are not verified;
  139. ## * ``CVerifyPeer``: certificates are verified;
  140. ## * ``CVerifyPeerUseEnvVars``: certificates are verified and the optional
  141. ## environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to
  142. ## locate certificates
  143. ##
  144. ## See `newContext <net.html#newContext.string,string,string,string>`_ to tweak or disable certificate validation.
  145. ##
  146. ## Timeouts
  147. ## ========
  148. ##
  149. ## Currently only the synchronous functions support a timeout.
  150. ## The timeout is
  151. ## measured in milliseconds, once it is set any call on a socket which may
  152. ## block will be susceptible to this timeout.
  153. ##
  154. ## It may be surprising but the
  155. ## function as a whole can take longer than the specified timeout, only
  156. ## individual internal calls on the socket are affected. In practice this means
  157. ## that as long as the server is sending data an exception will not be raised,
  158. ## if however data does not reach the client within the specified timeout a
  159. ## `TimeoutError` exception will be raised.
  160. ##
  161. ## Here is how to set a timeout when creating an `HttpClient` instance:
  162. ##
  163. ## .. code-block:: Nim
  164. ## import std/httpclient
  165. ##
  166. ## let client = newHttpClient(timeout = 42)
  167. ##
  168. ## Proxy
  169. ## =====
  170. ##
  171. ## A proxy can be specified as a param to any of the procedures defined in
  172. ## this module. To do this, use the `newProxy` constructor. Unfortunately,
  173. ## only basic authentication is supported at the moment.
  174. ##
  175. ## Some examples on how to configure a Proxy for `HttpClient`:
  176. ##
  177. ## .. code-block:: Nim
  178. ## import std/httpclient
  179. ##
  180. ## let myProxy = newProxy("http://myproxy.network")
  181. ## let client = newHttpClient(proxy = myProxy)
  182. ##
  183. ## Get Proxy URL from environment variables:
  184. ##
  185. ## .. code-block:: Nim
  186. ## import std/httpclient
  187. ##
  188. ## var url = ""
  189. ## try:
  190. ## if existsEnv("http_proxy"):
  191. ## url = getEnv("http_proxy")
  192. ## elif existsEnv("https_proxy"):
  193. ## url = getEnv("https_proxy")
  194. ## except ValueError:
  195. ## echo "Unable to parse proxy from environment variables."
  196. ##
  197. ## let myProxy = newProxy(url = url)
  198. ## let client = newHttpClient(proxy = myProxy)
  199. ##
  200. ## Redirects
  201. ## =========
  202. ##
  203. ## The maximum redirects can be set with the `maxRedirects` of `int` type,
  204. ## it specifies the maximum amount of redirects to follow,
  205. ## it defaults to `5`, you can set it to `0` to disable redirects.
  206. ##
  207. ## Here you can see an example about how to set the `maxRedirects` of `HttpClient`:
  208. ##
  209. ## .. code-block:: Nim
  210. ## import std/httpclient
  211. ##
  212. ## let client = newHttpClient(maxRedirects = 0)
  213. ##
  214. import std/private/since
  215. import std/[
  216. net, strutils, uri, parseutils, base64, os, mimetypes,
  217. math, random, httpcore, times, tables, streams, monotimes,
  218. asyncnet, asyncdispatch, asyncfile, nativesockets,
  219. ]
  220. export httpcore except parseHeader # TODO: The `except` doesn't work
  221. type
  222. Response* = ref object
  223. version*: string
  224. status*: string
  225. headers*: HttpHeaders
  226. body: string
  227. bodyStream*: Stream
  228. AsyncResponse* = ref object
  229. version*: string
  230. status*: string
  231. headers*: HttpHeaders
  232. body: string
  233. bodyStream*: FutureStream[string]
  234. proc code*(response: Response | AsyncResponse): HttpCode
  235. {.raises: [ValueError, OverflowDefect].} =
  236. ## Retrieves the specified response's `HttpCode`.
  237. ##
  238. ## Raises a `ValueError` if the response's `status` does not have a
  239. ## corresponding `HttpCode`.
  240. return response.status[0 .. 2].parseInt.HttpCode
  241. proc contentType*(response: Response | AsyncResponse): string {.inline.} =
  242. ## Retrieves the specified response's content type.
  243. ##
  244. ## This is effectively the value of the "Content-Type" header.
  245. response.headers.getOrDefault("content-type")
  246. proc contentLength*(response: Response | AsyncResponse): int =
  247. ## Retrieves the specified response's content length.
  248. ##
  249. ## This is effectively the value of the "Content-Length" header.
  250. ##
  251. ## A `ValueError` exception will be raised if the value is not an integer.
  252. var contentLengthHeader = response.headers.getOrDefault("Content-Length")
  253. result = contentLengthHeader.parseInt()
  254. doAssert(result >= 0 and result <= high(int32))
  255. proc lastModified*(response: Response | AsyncResponse): DateTime =
  256. ## Retrieves the specified response's last modified time.
  257. ##
  258. ## This is effectively the value of the "Last-Modified" header.
  259. ##
  260. ## Raises a `ValueError` if the parsing fails or the value is not a correctly
  261. ## formatted time.
  262. var lastModifiedHeader = response.headers.getOrDefault("last-modified")
  263. result = parse(lastModifiedHeader, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", utc())
  264. proc body*(response: Response): string =
  265. ## Retrieves the specified response's body.
  266. ##
  267. ## The response's body stream is read synchronously.
  268. if response.body.len == 0:
  269. response.body = response.bodyStream.readAll()
  270. return response.body
  271. proc body*(response: AsyncResponse): Future[string] {.async.} =
  272. ## Reads the response's body and caches it. The read is performed only
  273. ## once.
  274. if response.body.len == 0:
  275. response.body = await readAll(response.bodyStream)
  276. return response.body
  277. type
  278. Proxy* = ref object
  279. url*: Uri
  280. auth*: string
  281. MultipartEntry = object
  282. name, content: string
  283. case isFile: bool
  284. of true:
  285. filename, contentType: string
  286. fileSize: int64
  287. isStream: bool
  288. else: discard
  289. MultipartEntries* = openArray[tuple[name, content: string]]
  290. MultipartData* = ref object
  291. content: seq[MultipartEntry]
  292. ProtocolError* = object of IOError ## exception that is raised when server
  293. ## does not conform to the implemented
  294. ## protocol
  295. HttpRequestError* = object of IOError ## Thrown in the `getContent` proc
  296. ## and `postContent` proc,
  297. ## when the server returns an error
  298. const defUserAgent* = "Nim httpclient/" & NimVersion
  299. proc httpError(msg: string) =
  300. var e: ref ProtocolError
  301. new(e)
  302. e.msg = msg
  303. raise e
  304. proc fileError(msg: string) =
  305. var e: ref IOError
  306. new(e)
  307. e.msg = msg
  308. raise e
  309. when not defined(ssl):
  310. type SslContext = ref object
  311. var defaultSslContext {.threadvar.}: SslContext
  312. proc getDefaultSSL(): SslContext =
  313. result = defaultSslContext
  314. when defined(ssl):
  315. if result == nil:
  316. defaultSslContext = newContext(verifyMode = CVerifyPeer)
  317. result = defaultSslContext
  318. doAssert result != nil, "failure to initialize the SSL context"
  319. proc newProxy*(url: string; auth = ""): Proxy =
  320. ## Constructs a new `TProxy` object.
  321. result = Proxy(url: parseUri(url), auth: auth)
  322. proc newProxy*(url: Uri; auth = ""): Proxy =
  323. ## Constructs a new `TProxy` object.
  324. result = Proxy(url: url, auth: auth)
  325. proc newMultipartData*: MultipartData {.inline.} =
  326. ## Constructs a new `MultipartData` object.
  327. MultipartData()
  328. proc `$`*(data: MultipartData): string {.since: (1, 1).} =
  329. ## convert MultipartData to string so it's human readable when echo
  330. ## see https://github.com/nim-lang/Nim/issues/11863
  331. const sep = "-".repeat(30)
  332. for pos, entry in data.content:
  333. result.add(sep & center($pos, 3) & sep)
  334. result.add("\nname=\"" & entry.name & "\"")
  335. if entry.isFile:
  336. result.add("; filename=\"" & entry.filename & "\"\n")
  337. result.add("Content-Type: " & entry.contentType)
  338. result.add("\n\n" & entry.content & "\n")
  339. proc add*(p: MultipartData, name, content: string, filename: string = "",
  340. contentType: string = "", useStream = true) =
  341. ## Add a value to the multipart data.
  342. ##
  343. ## When `useStream` is `false`, the file will be read into memory.
  344. ##
  345. ## Raises a `ValueError` exception if
  346. ## `name`, `filename` or `contentType` contain newline characters.
  347. if {'\c', '\L'} in name:
  348. raise newException(ValueError, "name contains a newline character")
  349. if {'\c', '\L'} in filename:
  350. raise newException(ValueError, "filename contains a newline character")
  351. if {'\c', '\L'} in contentType:
  352. raise newException(ValueError, "contentType contains a newline character")
  353. var entry = MultipartEntry(
  354. name: name,
  355. content: content,
  356. isFile: filename.len > 0
  357. )
  358. if entry.isFile:
  359. entry.isStream = useStream
  360. entry.filename = filename
  361. entry.contentType = contentType
  362. p.content.add(entry)
  363. proc add*(p: MultipartData, xs: MultipartEntries): MultipartData
  364. {.discardable.} =
  365. ## Add a list of multipart entries to the multipart data `p`. All values are
  366. ## added without a filename and without a content type.
  367. ##
  368. ## .. code-block:: Nim
  369. ## data.add({"action": "login", "format": "json"})
  370. for name, content in xs.items:
  371. p.add(name, content)
  372. result = p
  373. proc newMultipartData*(xs: MultipartEntries): MultipartData =
  374. ## Create a new multipart data object and fill it with the entries `xs`
  375. ## directly.
  376. ##
  377. ## .. code-block:: Nim
  378. ## var data = newMultipartData({"action": "login", "format": "json"})
  379. result = MultipartData()
  380. for entry in xs:
  381. result.add(entry.name, entry.content)
  382. proc addFiles*(p: MultipartData, xs: openArray[tuple[name, file: string]],
  383. mimeDb = newMimetypes(), useStream = true):
  384. MultipartData {.discardable.} =
  385. ## Add files to a multipart data object. The files will be streamed from disk
  386. ## when the request is being made. When `stream` is `false`, the files are
  387. ## instead read into memory, but beware this is very memory ineffecient even
  388. ## for small files. The MIME types will automatically be determined.
  389. ## Raises an `IOError` if the file cannot be opened or reading fails. To
  390. ## manually specify file content, filename and MIME type, use `[]=` instead.
  391. ##
  392. ## .. code-block:: Nim
  393. ## data.addFiles({"uploaded_file": "public/test.html"})
  394. for name, file in xs.items:
  395. var contentType: string
  396. let (_, fName, ext) = splitFile(file)
  397. if ext.len > 0:
  398. contentType = mimeDb.getMimetype(ext[1..ext.high], "")
  399. let content = if useStream: file else: readFile(file)
  400. p.add(name, content, fName & ext, contentType, useStream = useStream)
  401. result = p
  402. proc `[]=`*(p: MultipartData, name, content: string) {.inline.} =
  403. ## Add a multipart entry to the multipart data `p`. The value is added
  404. ## without a filename and without a content type.
  405. ##
  406. ## .. code-block:: Nim
  407. ## data["username"] = "NimUser"
  408. p.add(name, content)
  409. proc `[]=`*(p: MultipartData, name: string,
  410. file: tuple[name, contentType, content: string]) {.inline.} =
  411. ## Add a file to the multipart data `p`, specifying filename, contentType
  412. ## and content manually.
  413. ##
  414. ## .. code-block:: Nim
  415. ## data["uploaded_file"] = ("test.html", "text/html",
  416. ## "<html><head></head><body><p>test</p></body></html>")
  417. p.add(name, file.content, file.name, file.contentType, useStream = false)
  418. proc getBoundary(p: MultipartData): string =
  419. if p == nil or p.content.len == 0: return
  420. while true:
  421. result = $rand(int.high)
  422. for i, entry in p.content:
  423. if result in entry.content: break
  424. elif i == p.content.high: return
  425. proc sendFile(socket: Socket | AsyncSocket,
  426. entry: MultipartEntry) {.multisync.} =
  427. const chunkSize = 2^18
  428. let file =
  429. when socket is AsyncSocket: openAsync(entry.content)
  430. else: newFileStream(entry.content, fmRead)
  431. var buffer: string
  432. while true:
  433. buffer =
  434. when socket is AsyncSocket: (await read(file, chunkSize))
  435. else: readStr(file, chunkSize)
  436. if buffer.len == 0: break
  437. await socket.send(buffer)
  438. file.close()
  439. proc getNewLocation(lastURL: Uri, headers: HttpHeaders): Uri =
  440. let newLocation = headers.getOrDefault"Location"
  441. if newLocation == "": httpError("location header expected")
  442. # Relative URLs. (Not part of the spec, but soon will be.)
  443. let parsedLocation = parseUri(newLocation)
  444. if parsedLocation.hostname == "" and parsedLocation.path != "":
  445. result = lastURL
  446. result.path = parsedLocation.path
  447. result.query = parsedLocation.query
  448. result.anchor = parsedLocation.anchor
  449. else:
  450. result = parsedLocation
  451. proc generateHeaders(requestUrl: Uri, httpMethod: HttpMethod, headers: HttpHeaders,
  452. proxy: Proxy): string =
  453. # GET
  454. result = $httpMethod
  455. result.add ' '
  456. if proxy.isNil or requestUrl.scheme == "https":
  457. # /path?query
  458. if not requestUrl.path.startsWith("/"): result.add '/'
  459. result.add(requestUrl.path)
  460. if requestUrl.query.len > 0:
  461. result.add("?" & requestUrl.query)
  462. else:
  463. # Remove the 'http://' from the URL for CONNECT requests for TLS connections.
  464. var modifiedUrl = requestUrl
  465. if requestUrl.scheme == "https": modifiedUrl.scheme = ""
  466. result.add($modifiedUrl)
  467. # HTTP/1.1\c\l
  468. result.add(" HTTP/1.1" & httpNewLine)
  469. # Host header.
  470. if not headers.hasKey("Host"):
  471. if requestUrl.port == "":
  472. add(result, "Host: " & requestUrl.hostname & httpNewLine)
  473. else:
  474. add(result, "Host: " & requestUrl.hostname & ":" & requestUrl.port & httpNewLine)
  475. # Connection header.
  476. if not headers.hasKey("Connection"):
  477. add(result, "Connection: Keep-Alive" & httpNewLine)
  478. # Proxy auth header.
  479. if not proxy.isNil and proxy.auth != "":
  480. let auth = base64.encode(proxy.auth)
  481. add(result, "Proxy-Authorization: basic " & auth & httpNewLine)
  482. for key, val in headers:
  483. add(result, key & ": " & val & httpNewLine)
  484. add(result, httpNewLine)
  485. type
  486. ProgressChangedProc*[ReturnType] =
  487. proc (total, progress, speed: BiggestInt):
  488. ReturnType {.closure, gcsafe.}
  489. HttpClientBase*[SocketType] = ref object
  490. socket: SocketType
  491. connected: bool
  492. currentURL: Uri ## Where we are currently connected.
  493. headers*: HttpHeaders ## Headers to send in requests.
  494. maxRedirects: Natural ## Maximum redirects, set to `0` to disable.
  495. userAgent: string
  496. timeout*: int ## Only used for blocking HttpClient for now.
  497. proxy: Proxy
  498. ## `nil` or the callback to call when request progress changes.
  499. when SocketType is Socket:
  500. onProgressChanged*: ProgressChangedProc[void]
  501. else:
  502. onProgressChanged*: ProgressChangedProc[Future[void]]
  503. when defined(ssl):
  504. sslContext: net.SslContext
  505. contentTotal: BiggestInt
  506. contentProgress: BiggestInt
  507. oneSecondProgress: BiggestInt
  508. lastProgressReport: MonoTime
  509. when SocketType is AsyncSocket:
  510. bodyStream: FutureStream[string]
  511. parseBodyFut: Future[void]
  512. else:
  513. bodyStream: Stream
  514. getBody: bool ## When `false`, the body is never read in requestAux.
  515. type
  516. HttpClient* = HttpClientBase[Socket]
  517. proc newHttpClient*(userAgent = defUserAgent, maxRedirects = 5,
  518. sslContext = getDefaultSSL(), proxy: Proxy = nil,
  519. timeout = -1, headers = newHttpHeaders()): HttpClient =
  520. ## Creates a new HttpClient instance.
  521. ##
  522. ## `userAgent` specifies the user agent that will be used when making
  523. ## requests.
  524. ##
  525. ## `maxRedirects` specifies the maximum amount of redirects to follow,
  526. ## default is 5.
  527. ##
  528. ## `sslContext` specifies the SSL context to use for HTTPS requests.
  529. ## See `SSL/TLS support <#sslslashtls-support>`_
  530. ##
  531. ## `proxy` specifies an HTTP proxy to use for this HTTP client's
  532. ## connections.
  533. ##
  534. ## `timeout` specifies the number of milliseconds to allow before a
  535. ## `TimeoutError` is raised.
  536. ##
  537. ## `headers` specifies the HTTP Headers.
  538. runnableExamples:
  539. import std/strutils
  540. let exampleHtml = newHttpClient().getContent("http://example.com")
  541. assert "Example Domain" in exampleHtml
  542. assert "Pizza" notin exampleHtml
  543. new result
  544. result.headers = headers
  545. result.userAgent = userAgent
  546. result.maxRedirects = maxRedirects
  547. result.proxy = proxy
  548. result.timeout = timeout
  549. result.onProgressChanged = nil
  550. result.bodyStream = newStringStream()
  551. result.getBody = true
  552. when defined(ssl):
  553. result.sslContext = sslContext
  554. type
  555. AsyncHttpClient* = HttpClientBase[AsyncSocket]
  556. proc newAsyncHttpClient*(userAgent = defUserAgent, maxRedirects = 5,
  557. sslContext = getDefaultSSL(), proxy: Proxy = nil,
  558. headers = newHttpHeaders()): AsyncHttpClient =
  559. ## Creates a new AsyncHttpClient instance.
  560. ##
  561. ## `userAgent` specifies the user agent that will be used when making
  562. ## requests.
  563. ##
  564. ## `maxRedirects` specifies the maximum amount of redirects to follow,
  565. ## default is 5.
  566. ##
  567. ## `sslContext` specifies the SSL context to use for HTTPS requests.
  568. ##
  569. ## `proxy` specifies an HTTP proxy to use for this HTTP client's
  570. ## connections.
  571. ##
  572. ## `headers` specifies the HTTP Headers.
  573. runnableExamples:
  574. import std/[asyncdispatch, strutils]
  575. proc asyncProc(): Future[string] {.async.} =
  576. let client = newAsyncHttpClient()
  577. result = await client.getContent("http://example.com")
  578. let exampleHtml = waitFor asyncProc()
  579. assert "Example Domain" in exampleHtml
  580. assert "Pizza" notin exampleHtml
  581. new result
  582. result.headers = headers
  583. result.userAgent = userAgent
  584. result.maxRedirects = maxRedirects
  585. result.proxy = proxy
  586. result.timeout = -1 # TODO
  587. result.onProgressChanged = nil
  588. result.bodyStream = newFutureStream[string]("newAsyncHttpClient")
  589. result.getBody = true
  590. when defined(ssl):
  591. result.sslContext = sslContext
  592. proc close*(client: HttpClient | AsyncHttpClient) =
  593. ## Closes any connections held by the HTTP client.
  594. if client.connected:
  595. client.socket.close()
  596. client.connected = false
  597. proc getSocket*(client: HttpClient): Socket {.inline.} =
  598. ## Get network socket, useful if you want to find out more details about the connection
  599. ##
  600. ## this example shows info about local and remote endpoints
  601. ##
  602. ## .. code-block:: Nim
  603. ## if client.connected:
  604. ## echo client.getSocket.getLocalAddr
  605. ## echo client.getSocket.getPeerAddr
  606. ##
  607. return client.socket
  608. proc getSocket*(client: AsyncHttpClient): AsyncSocket {.inline.} =
  609. return client.socket
  610. proc reportProgress(client: HttpClient | AsyncHttpClient,
  611. progress: BiggestInt) {.multisync.} =
  612. client.contentProgress += progress
  613. client.oneSecondProgress += progress
  614. if (getMonoTime() - client.lastProgressReport).inSeconds > 1:
  615. if not client.onProgressChanged.isNil:
  616. await client.onProgressChanged(client.contentTotal,
  617. client.contentProgress,
  618. client.oneSecondProgress)
  619. client.oneSecondProgress = 0
  620. client.lastProgressReport = getMonoTime()
  621. proc recvFull(client: HttpClient | AsyncHttpClient, size: int, timeout: int,
  622. keep: bool): Future[int] {.multisync.} =
  623. ## Ensures that all the data requested is read and returned.
  624. var readLen = 0
  625. while true:
  626. if size == readLen: break
  627. let remainingSize = size - readLen
  628. let sizeToRecv = min(remainingSize, net.BufferSize)
  629. when client.socket is Socket:
  630. let data = client.socket.recv(sizeToRecv, timeout)
  631. else:
  632. let data = await client.socket.recv(sizeToRecv)
  633. if data == "":
  634. client.close()
  635. break # We've been disconnected.
  636. readLen.inc(data.len)
  637. if keep:
  638. await client.bodyStream.write(data)
  639. await reportProgress(client, data.len)
  640. return readLen
  641. proc parseChunks(client: HttpClient | AsyncHttpClient): Future[void]
  642. {.multisync.} =
  643. while true:
  644. var chunkSize = 0
  645. var chunkSizeStr = await client.socket.recvLine()
  646. var i = 0
  647. if chunkSizeStr == "":
  648. httpError("Server terminated connection prematurely")
  649. while i < chunkSizeStr.len:
  650. case chunkSizeStr[i]
  651. of '0'..'9':
  652. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('0'))
  653. of 'a'..'f':
  654. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('a') + 10)
  655. of 'A'..'F':
  656. chunkSize = chunkSize shl 4 or (ord(chunkSizeStr[i]) - ord('A') + 10)
  657. of ';':
  658. # http://tools.ietf.org/html/rfc2616#section-3.6.1
  659. # We don't care about chunk-extensions.
  660. break
  661. else:
  662. httpError("Invalid chunk size: " & chunkSizeStr)
  663. inc(i)
  664. if chunkSize <= 0:
  665. discard await recvFull(client, 2, client.timeout, false) # Skip \c\L
  666. break
  667. var bytesRead = await recvFull(client, chunkSize, client.timeout, true)
  668. if bytesRead != chunkSize:
  669. httpError("Server terminated connection prematurely")
  670. bytesRead = await recvFull(client, 2, client.timeout, false) # Skip \c\L
  671. if bytesRead != 2:
  672. httpError("Server terminated connection prematurely")
  673. # Trailer headers will only be sent if the request specifies that we want
  674. # them: http://tools.ietf.org/html/rfc2616#section-3.6.1
  675. proc parseBody(client: HttpClient | AsyncHttpClient, headers: HttpHeaders,
  676. httpVersion: string): Future[void] {.multisync.} =
  677. # Reset progress from previous requests.
  678. client.contentTotal = 0
  679. client.contentProgress = 0
  680. client.oneSecondProgress = 0
  681. client.lastProgressReport = MonoTime()
  682. when client is AsyncHttpClient:
  683. assert(not client.bodyStream.finished)
  684. if headers.getOrDefault"Transfer-Encoding" == "chunked":
  685. await parseChunks(client)
  686. else:
  687. # -REGION- Content-Length
  688. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.3
  689. var contentLengthHeader = headers.getOrDefault"Content-Length"
  690. if contentLengthHeader != "":
  691. var length = contentLengthHeader.parseInt()
  692. client.contentTotal = length
  693. if length > 0:
  694. let recvLen = await client.recvFull(length, client.timeout, true)
  695. if recvLen == 0:
  696. client.close()
  697. httpError("Got disconnected while trying to read body.")
  698. if recvLen != length:
  699. httpError("Received length doesn't match expected length. Wanted " &
  700. $length & " got: " & $recvLen)
  701. else:
  702. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.4 TODO
  703. # -REGION- Connection: Close
  704. # (http://tools.ietf.org/html/rfc2616#section-4.4) NR.5
  705. let implicitConnectionClose =
  706. httpVersion == "1.0" or
  707. # This doesn't match the HTTP spec, but it fixes issues for non-conforming servers.
  708. (httpVersion == "1.1" and headers.getOrDefault"Connection" == "")
  709. if headers.getOrDefault"Connection" == "close" or implicitConnectionClose:
  710. while true:
  711. let recvLen = await client.recvFull(4000, client.timeout, true)
  712. if recvLen != 4000:
  713. client.close()
  714. break
  715. when client is AsyncHttpClient:
  716. client.bodyStream.complete()
  717. else:
  718. client.bodyStream.setPosition(0)
  719. # If the server will close our connection, then no matter the method of
  720. # reading the body, we need to close our socket.
  721. if headers.getOrDefault"Connection" == "close":
  722. client.close()
  723. proc parseResponse(client: HttpClient | AsyncHttpClient,
  724. getBody: bool): Future[Response | AsyncResponse]
  725. {.multisync.} =
  726. new result
  727. var parsedStatus = false
  728. var linei = 0
  729. var fullyRead = false
  730. var line = ""
  731. result.headers = newHttpHeaders()
  732. while true:
  733. linei = 0
  734. when client is HttpClient:
  735. line = await client.socket.recvLine(client.timeout)
  736. else:
  737. line = await client.socket.recvLine()
  738. if line == "":
  739. # We've been disconnected.
  740. client.close()
  741. break
  742. if line == httpNewLine:
  743. fullyRead = true
  744. break
  745. if not parsedStatus:
  746. # Parse HTTP version info and status code.
  747. var le = skipIgnoreCase(line, "HTTP/", linei)
  748. if le <= 0:
  749. httpError("invalid http version, `" & line & "`")
  750. inc(linei, le)
  751. le = skipIgnoreCase(line, "1.1", linei)
  752. if le > 0: result.version = "1.1"
  753. else:
  754. le = skipIgnoreCase(line, "1.0", linei)
  755. if le <= 0: httpError("unsupported http version")
  756. result.version = "1.0"
  757. inc(linei, le)
  758. # Status code
  759. linei.inc skipWhitespace(line, linei)
  760. result.status = line[linei .. ^1]
  761. parsedStatus = true
  762. else:
  763. # Parse headers
  764. var name = ""
  765. var le = parseUntil(line, name, ':', linei)
  766. if le <= 0: httpError("invalid headers")
  767. inc(linei, le)
  768. if line[linei] != ':': httpError("invalid headers")
  769. inc(linei) # Skip :
  770. result.headers.add(name, line[linei .. ^1].strip())
  771. if result.headers.len > headerLimit:
  772. httpError("too many headers")
  773. if not fullyRead:
  774. httpError("Connection was closed before full request has been made")
  775. when client is HttpClient:
  776. result.bodyStream = newStringStream()
  777. else:
  778. result.bodyStream = newFutureStream[string]("parseResponse")
  779. if getBody and result.code != Http204:
  780. client.bodyStream = result.bodyStream
  781. when client is HttpClient:
  782. parseBody(client, result.headers, result.version)
  783. else:
  784. assert(client.parseBodyFut.isNil or client.parseBodyFut.finished)
  785. # do not wait here for the body request to complete
  786. client.parseBodyFut = parseBody(client, result.headers, result.version)
  787. client.parseBodyFut.addCallback do():
  788. if client.parseBodyFut.failed:
  789. client.bodyStream.fail(client.parseBodyFut.error)
  790. proc newConnection(client: HttpClient | AsyncHttpClient,
  791. url: Uri) {.multisync.} =
  792. if client.currentURL.hostname != url.hostname or
  793. client.currentURL.scheme != url.scheme or
  794. client.currentURL.port != url.port or
  795. (not client.connected):
  796. # Connect to proxy if specified
  797. let connectionUrl =
  798. if client.proxy.isNil: url else: client.proxy.url
  799. let isSsl = connectionUrl.scheme.toLowerAscii() == "https"
  800. if isSsl and not defined(ssl):
  801. raise newException(HttpRequestError,
  802. "SSL support is not available. Cannot connect over SSL. Compile with -d:ssl to enable.")
  803. if client.connected:
  804. client.close()
  805. client.connected = false
  806. # TODO: I should be able to write 'net.Port' here...
  807. let port =
  808. if connectionUrl.port == "":
  809. if isSsl:
  810. nativesockets.Port(443)
  811. else:
  812. nativesockets.Port(80)
  813. else: nativesockets.Port(connectionUrl.port.parseInt)
  814. when client is HttpClient:
  815. client.socket = await net.dial(connectionUrl.hostname, port)
  816. elif client is AsyncHttpClient:
  817. client.socket = await asyncnet.dial(connectionUrl.hostname, port)
  818. else: {.fatal: "Unsupported client type".}
  819. when defined(ssl):
  820. if isSsl:
  821. try:
  822. client.sslContext.wrapConnectedSocket(
  823. client.socket, handshakeAsClient, connectionUrl.hostname)
  824. except:
  825. client.socket.close()
  826. raise getCurrentException()
  827. # If need to CONNECT through proxy
  828. if url.scheme == "https" and not client.proxy.isNil:
  829. when defined(ssl):
  830. # Pass only host:port for CONNECT
  831. var connectUrl = initUri()
  832. connectUrl.hostname = url.hostname
  833. connectUrl.port = if url.port != "": url.port else: "443"
  834. let proxyHeaderString = generateHeaders(connectUrl, HttpConnect,
  835. newHttpHeaders(), client.proxy)
  836. await client.socket.send(proxyHeaderString)
  837. let proxyResp = await parseResponse(client, false)
  838. if not proxyResp.status.startsWith("200"):
  839. raise newException(HttpRequestError,
  840. "The proxy server rejected a CONNECT request, " &
  841. "so a secure connection could not be established.")
  842. client.sslContext.wrapConnectedSocket(
  843. client.socket, handshakeAsClient, url.hostname)
  844. else:
  845. raise newException(HttpRequestError,
  846. "SSL support is not available. Cannot connect over SSL. Compile with -d:ssl to enable.")
  847. # May be connected through proxy but remember actual URL being accessed
  848. client.currentURL = url
  849. client.connected = true
  850. proc readFileSizes(client: HttpClient | AsyncHttpClient,
  851. multipart: MultipartData) {.multisync.} =
  852. for entry in multipart.content.mitems():
  853. if not entry.isFile: continue
  854. if not entry.isStream:
  855. entry.fileSize = entry.content.len
  856. continue
  857. # TODO: look into making getFileSize work with async
  858. let fileSize = getFileSize(entry.content)
  859. entry.fileSize = fileSize
  860. proc format(entry: MultipartEntry, boundary: string): string =
  861. result = "--" & boundary & httpNewLine
  862. result.add("Content-Disposition: form-data; name=\"" & entry.name & "\"")
  863. if entry.isFile:
  864. result.add("; filename=\"" & entry.filename & "\"" & httpNewLine)
  865. result.add("Content-Type: " & entry.contentType & httpNewLine)
  866. else:
  867. result.add(httpNewLine & httpNewLine & entry.content)
  868. proc format(client: HttpClient | AsyncHttpClient,
  869. multipart: MultipartData): Future[seq[string]] {.multisync.} =
  870. let bound = getBoundary(multipart)
  871. client.headers["Content-Type"] = "multipart/form-data; boundary=" & bound
  872. await client.readFileSizes(multipart)
  873. var length: int64
  874. for entry in multipart.content:
  875. result.add(format(entry, bound) & httpNewLine)
  876. if entry.isFile:
  877. length += entry.fileSize + httpNewLine.len
  878. result.add "--" & bound & "--" & httpNewLine
  879. for s in result: length += s.len
  880. client.headers["Content-Length"] = $length
  881. proc override(fallback, override: HttpHeaders): HttpHeaders =
  882. # Right-biased map union for `HttpHeaders`
  883. result = newHttpHeaders()
  884. # Copy by value
  885. result.table[] = fallback.table[]
  886. if override.isNil:
  887. # Return the copy of fallback so it does not get modified
  888. return result
  889. for k, vs in override.table:
  890. result[k] = vs
  891. proc requestAux(client: HttpClient | AsyncHttpClient, url: Uri,
  892. httpMethod: HttpMethod, body = "", headers: HttpHeaders = nil,
  893. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  894. {.multisync.} =
  895. # Helper that actually makes the request. Does not handle redirects.
  896. if url.scheme == "":
  897. raise newException(ValueError, "No uri scheme supplied.")
  898. when client is AsyncHttpClient:
  899. if not client.parseBodyFut.isNil:
  900. # let the current operation finish before making another request
  901. await client.parseBodyFut
  902. client.parseBodyFut = nil
  903. await newConnection(client, url)
  904. var newHeaders: HttpHeaders
  905. var data: seq[string]
  906. if multipart != nil and multipart.content.len > 0:
  907. # `format` modifies `client.headers`, see
  908. # https://github.com/nim-lang/Nim/pull/18208#discussion_r647036979
  909. data = await client.format(multipart)
  910. newHeaders = client.headers.override(headers)
  911. else:
  912. newHeaders = client.headers.override(headers)
  913. # Only change headers if they have not been specified already
  914. if not newHeaders.hasKey("Content-Length"):
  915. if body.len != 0:
  916. newHeaders["Content-Length"] = $body.len
  917. elif httpMethod notin {HttpGet, HttpHead}:
  918. newHeaders["Content-Length"] = "0"
  919. if not newHeaders.hasKey("user-agent") and client.userAgent.len > 0:
  920. newHeaders["User-Agent"] = client.userAgent
  921. let headerString = generateHeaders(url, httpMethod, newHeaders,
  922. client.proxy)
  923. await client.socket.send(headerString)
  924. if data.len > 0:
  925. var buffer: string
  926. for i, entry in multipart.content:
  927. buffer.add data[i]
  928. if not entry.isFile: continue
  929. if buffer.len > 0:
  930. await client.socket.send(buffer)
  931. buffer.setLen(0)
  932. if entry.isStream:
  933. await client.socket.sendFile(entry)
  934. else:
  935. await client.socket.send(entry.content)
  936. buffer.add httpNewLine
  937. # send the rest and the last boundary
  938. await client.socket.send(buffer & data[^1])
  939. elif body.len > 0:
  940. await client.socket.send(body)
  941. let getBody = httpMethod notin {HttpHead, HttpConnect} and
  942. client.getBody
  943. result = await parseResponse(client, getBody)
  944. proc request*(client: HttpClient | AsyncHttpClient, url: Uri | string,
  945. httpMethod: HttpMethod | string = HttpGet, body = "",
  946. headers: HttpHeaders = nil,
  947. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  948. {.multisync.} =
  949. ## Connects to the hostname specified by the URL and performs a request
  950. ## using the custom method string specified by `httpMethod`.
  951. ##
  952. ## Connection will be kept alive. Further requests on the same `client` to
  953. ## the same hostname will not require a new connection to be made. The
  954. ## connection can be closed by using the `close` procedure.
  955. ##
  956. ## This procedure will follow redirects up to a maximum number of redirects
  957. ## specified in `client.maxRedirects`.
  958. ##
  959. ## You need to make sure that the `url` doesn't contain any newline
  960. ## characters. Failing to do so will raise `AssertionDefect`.
  961. ##
  962. ## `headers` are HTTP headers that override the `client.headers` for
  963. ## this specific request only and will not be persisted.
  964. ##
  965. ## **Deprecated since v1.5**: use HttpMethod enum instead; string parameter httpMethod is deprecated
  966. when url is string:
  967. doAssert(not url.contains({'\c', '\L'}), "url shouldn't contain any newline characters")
  968. let url = parseUri(url)
  969. when httpMethod is string:
  970. {.warning:
  971. "Deprecated since v1.5; use HttpMethod enum instead; string parameter httpMethod is deprecated".}
  972. let httpMethod = case httpMethod
  973. of "HEAD":
  974. HttpHead
  975. of "GET":
  976. HttpGet
  977. of "POST":
  978. HttpPost
  979. of "PUT":
  980. HttpPut
  981. of "DELETE":
  982. HttpDelete
  983. of "TRACE":
  984. HttpTrace
  985. of "OPTIONS":
  986. HttpOptions
  987. of "CONNECT":
  988. HttpConnect
  989. of "PATCH":
  990. HttpPatch
  991. else:
  992. raise newException(ValueError, "Invalid HTTP method name: " & httpMethod)
  993. result = await client.requestAux(url, httpMethod, body, headers, multipart)
  994. var lastURL = url
  995. for i in 1..client.maxRedirects:
  996. let statusCode = result.code
  997. if statusCode notin {Http301, Http302, Http303, Http307, Http308}:
  998. break
  999. let redirectTo = getNewLocation(lastURL, result.headers)
  1000. var redirectMethod: HttpMethod
  1001. var redirectBody: string
  1002. # For more informations about the redirect methods see:
  1003. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
  1004. case statusCode
  1005. of Http301, Http302, Http303:
  1006. # The method is changed to GET unless it is GET or HEAD (RFC2616)
  1007. if httpMethod notin {HttpGet, HttpHead}:
  1008. redirectMethod = HttpGet
  1009. else:
  1010. redirectMethod = httpMethod
  1011. # The body is stripped away
  1012. redirectBody = ""
  1013. # Delete any header value associated with the body
  1014. if not headers.isNil():
  1015. headers.del("Content-Length")
  1016. headers.del("Content-Type")
  1017. headers.del("Transfer-Encoding")
  1018. of Http307, Http308:
  1019. # The method and the body are unchanged
  1020. redirectMethod = httpMethod
  1021. redirectBody = body
  1022. else:
  1023. # Unreachable
  1024. doAssert(false)
  1025. # Check if the redirection is to the same domain or a sub-domain (foo.com
  1026. # -> sub.foo.com)
  1027. if redirectTo.hostname != lastURL.hostname and
  1028. not redirectTo.hostname.endsWith("." & lastURL.hostname):
  1029. # Perform some cleanup of the header values
  1030. if headers != nil:
  1031. # Delete the Host header
  1032. headers.del("Host")
  1033. # Do not send any sensitive info to a unknown host
  1034. headers.del("Authorization")
  1035. result = await client.requestAux(redirectTo, redirectMethod, redirectBody,
  1036. headers, multipart)
  1037. lastURL = redirectTo
  1038. proc responseContent(resp: Response | AsyncResponse): Future[string] {.multisync.} =
  1039. ## Returns the content of a response as a string.
  1040. ##
  1041. ## A `HttpRequestError` will be raised if the server responds with a
  1042. ## client error (status code 4xx) or a server error (status code 5xx).
  1043. if resp.code.is4xx or resp.code.is5xx:
  1044. raise newException(HttpRequestError, resp.status)
  1045. else:
  1046. return await resp.bodyStream.readAll()
  1047. proc head*(client: HttpClient | AsyncHttpClient,
  1048. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1049. ## Connects to the hostname specified by the URL and performs a HEAD request.
  1050. ##
  1051. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1052. result = await client.request(url, HttpHead)
  1053. proc get*(client: HttpClient | AsyncHttpClient,
  1054. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1055. ## Connects to the hostname specified by the URL and performs a GET request.
  1056. ##
  1057. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1058. result = await client.request(url, HttpGet)
  1059. proc getContent*(client: HttpClient | AsyncHttpClient,
  1060. url: Uri | string): Future[string] {.multisync.} =
  1061. ## Connects to the hostname specified by the URL and returns the content of a GET request.
  1062. let resp = await get(client, url)
  1063. return await responseContent(resp)
  1064. proc delete*(client: HttpClient | AsyncHttpClient,
  1065. url: Uri | string): Future[Response | AsyncResponse] {.multisync.} =
  1066. ## Connects to the hostname specified by the URL and performs a DELETE request.
  1067. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1068. result = await client.request(url, HttpDelete)
  1069. proc deleteContent*(client: HttpClient | AsyncHttpClient,
  1070. url: Uri | string): Future[string] {.multisync.} =
  1071. ## Connects to the hostname specified by the URL and returns the content of a DELETE request.
  1072. let resp = await delete(client, url)
  1073. return await responseContent(resp)
  1074. proc post*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1075. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1076. {.multisync.} =
  1077. ## Connects to the hostname specified by the URL and performs a POST request.
  1078. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1079. result = await client.request(url, HttpPost, body, multipart=multipart)
  1080. proc postContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1081. multipart: MultipartData = nil): Future[string]
  1082. {.multisync.} =
  1083. ## Connects to the hostname specified by the URL and returns the content of a POST request.
  1084. let resp = await post(client, url, body, multipart)
  1085. return await responseContent(resp)
  1086. proc put*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1087. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1088. {.multisync.} =
  1089. ## Connects to the hostname specified by the URL and performs a PUT request.
  1090. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1091. result = await client.request(url, HttpPut, body, multipart=multipart)
  1092. proc putContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1093. multipart: MultipartData = nil): Future[string] {.multisync.} =
  1094. ## Connects to the hostname specified by the URL andreturns the content of a PUT request.
  1095. let resp = await put(client, url, body, multipart)
  1096. return await responseContent(resp)
  1097. proc patch*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1098. multipart: MultipartData = nil): Future[Response | AsyncResponse]
  1099. {.multisync.} =
  1100. ## Connects to the hostname specified by the URL and performs a PATCH request.
  1101. ## This procedure uses httpClient values such as `client.maxRedirects`.
  1102. result = await client.request(url, HttpPatch, body, multipart=multipart)
  1103. proc patchContent*(client: HttpClient | AsyncHttpClient, url: Uri | string, body = "",
  1104. multipart: MultipartData = nil): Future[string]
  1105. {.multisync.} =
  1106. ## Connects to the hostname specified by the URL and returns the content of a PATCH request.
  1107. let resp = await patch(client, url, body, multipart)
  1108. return await responseContent(resp)
  1109. proc downloadFile*(client: HttpClient, url: Uri | string, filename: string) =
  1110. ## Downloads `url` and saves it to `filename`.
  1111. client.getBody = false
  1112. defer:
  1113. client.getBody = true
  1114. let resp = client.get(url)
  1115. if resp.code.is4xx or resp.code.is5xx:
  1116. raise newException(HttpRequestError, resp.status)
  1117. client.bodyStream = newFileStream(filename, fmWrite)
  1118. if client.bodyStream.isNil:
  1119. fileError("Unable to open file")
  1120. parseBody(client, resp.headers, resp.version)
  1121. client.bodyStream.close()
  1122. proc downloadFileEx(client: AsyncHttpClient,
  1123. url: Uri | string, filename: string): Future[void] {.async.} =
  1124. ## Downloads `url` and saves it to `filename`.
  1125. client.getBody = false
  1126. let resp = await client.get(url)
  1127. if resp.code.is4xx or resp.code.is5xx:
  1128. raise newException(HttpRequestError, resp.status)
  1129. client.bodyStream = newFutureStream[string]("downloadFile")
  1130. var file = openAsync(filename, fmWrite)
  1131. defer: file.close()
  1132. # Let `parseBody` write response data into client.bodyStream in the
  1133. # background.
  1134. let parseBodyFut = parseBody(client, resp.headers, resp.version)
  1135. parseBodyFut.addCallback do():
  1136. if parseBodyFut.failed:
  1137. client.bodyStream.fail(parseBodyFut.error)
  1138. # The `writeFromStream` proc will complete once all the data in the
  1139. # `bodyStream` has been written to the file.
  1140. await file.writeFromStream(client.bodyStream)
  1141. proc downloadFile*(client: AsyncHttpClient, url: Uri | string,
  1142. filename: string): Future[void] =
  1143. result = newFuture[void]("downloadFile")
  1144. try:
  1145. result = downloadFileEx(client, url, filename)
  1146. except Exception as exc:
  1147. result.fail(exc)
  1148. finally:
  1149. result.addCallback(
  1150. proc () = client.getBody = true
  1151. )