PageRenderTime 51ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/impure/web.nim

https://bitbucket.org/ivanhernandez/nimrod
Nim | 62 lines | 30 code | 8 blank | 24 comment | 20 complexity | 84d079dd82b560e49a91c36f4df14bec MD5 | raw file
  1. #
  2. #
  3. # Nimrod's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains simple high-level procedures for dealing with the
  10. ## web. Use cases:
  11. ##
  12. ## * requesting URLs
  13. ## * sending and retrieving emails
  14. ## * sending and retrieving files from an FTP server
  15. ##
  16. ## Currently only requesting URLs is implemented. The implementation depends
  17. ## on the libcurl library!
  18. ##
  19. ## **Deprecated since version 0.8.8:** Use the ``httpclient`` module instead.
  20. ##
  21. {.deprecated.}
  22. import libcurl, streams
  23. proc curlwrapperWrite(p: pointer, size, nmemb: int,
  24. data: pointer): int {.cdecl.} =
  25. var stream = cast[PStream](data)
  26. stream.writeData(p, size*nmemb)
  27. return size*nmemb
  28. proc URLretrieveStream*(url: string): PStream =
  29. ## retrieves the given `url` and returns a stream which one can read from to
  30. ## obtain the contents. Returns nil if an error occurs.
  31. result = newStringStream()
  32. var hCurl = easy_init()
  33. if hCurl == nil: return nil
  34. if easy_setopt(hCurl, OPT_URL, url) != E_OK: return nil
  35. if easy_setopt(hCurl, OPT_WRITEFUNCTION,
  36. curlwrapperWrite) != E_OK: return nil
  37. if easy_setopt(hCurl, OPT_WRITEDATA, result) != E_OK: return nil
  38. if easy_perform(hCurl) != E_OK: return nil
  39. easy_cleanup(hCurl)
  40. proc URLretrieveString*(url: string): TaintedString =
  41. ## retrieves the given `url` and returns the contents. Returns nil if an
  42. ## error occurs.
  43. var stream = newStringStream()
  44. var hCurl = easy_init()
  45. if hCurl == nil: return
  46. if easy_setopt(hCurl, OPT_URL, url) != E_OK: return
  47. if easy_setopt(hCurl, OPT_WRITEFUNCTION,
  48. curlwrapperWrite) != E_OK: return
  49. if easy_setopt(hCurl, OPT_WRITEDATA, stream) != E_OK: return
  50. if easy_perform(hCurl) != E_OK: return
  51. easy_cleanup(hCurl)
  52. result = stream.data.TaintedString
  53. when isMainModule:
  54. echo URLretrieveString("http://nimrod.ethexor.com/")