summary refs log tree commit diff stats
path: root/lib/impure/web.nim
blob: af302cc57641bec6cf8219a47a4dbdcb5c22f331 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#
#
#            Nimrod's Runtime Library
#        (c) Copyright 2010 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module contains simple high-level procedures for dealing with the
## web. Use cases: 
##
## * requesting URLs
## * sending and retrieving emails
## * sending and retrieving files from an FTP server
##
## Currently only requesting URLs is implemented. The implementation depends
## on the libcurl library!
##
## **Deprecated since version 0.8.8:** Use the ``httpclient`` module instead. 
## 

{.deprecated.}

import libcurl, streams

proc curlwrapperWrite(p: pointer, size, nmemb: int, 
                      data: pointer): int {.cdecl.} = 
  var stream = cast[PStream](data)
  stream.writeData(stream, p, size*nmemb)
  return size*nmemb

proc URLretrieveStream*(url: string): PStream = 
  ## retrieves the given `url` and returns a stream which one can read from to
  ## obtain the contents. Returns nil if an error occurs.
  result = newStringStream()
  var hCurl = easy_init() 
  if hCurl == nil: return nil
  if easy_setopt(hCurl, OPT_URL, url) != E_OK: return nil
  if easy_setopt(hCurl, OPT_WRITEFUNCTION, 
                      curlwrapperWrite) != E_OK: return nil
  if easy_setopt(hCurl, OPT_WRITEDATA, result) != E_OK: return nil
  if easy_perform(hCurl) != E_OK: return nil
  easy_cleanup(hCurl)
  
proc URLretrieveString*(url: string): string = 
  ## retrieves the given `url` and returns the contents. Returns nil if an
  ## error occurs.
  var stream = newStringStream()
  var hCurl = easy_init()
  if hCurl == nil: return nil
  if easy_setopt(hCurl, OPT_URL, url) != E_OK: return nil
  if easy_setopt(hCurl, OPT_WRITEFUNCTION, 
                      curlwrapperWrite) != E_OK: return nil
  if easy_setopt(hCurl, OPT_WRITEDATA, stream) != E_OK: return nil
  if easy_perform(hCurl) != E_OK: return nil
  easy_cleanup(hCurl)
  result = stream.data

when isMainModule:
  echo URLretrieveString("http://nimrod.ethexor.com/")