httpclient.nim 46 KB

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