-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttpclient.nim
57 lines (45 loc) · 1.32 KB
/
httpclient.nim
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
import std/[uri, strutils]
import cps
import types, conn, http, bio
type
Client = ref object
maxFollowRedirects: int
conn: Conn
bio: Bio
proc newClient*(): Client =
Client(
maxFollowRedirects: 5
)
proc request*(client: Client, meth: string, url: string, body: string = ""): Response {.cps:C.} =
# Build request
let req = newRequest(meth, url)
req.contentLength = body.len
# Open connection and send request
var port = req.uri.port
if port == "":
port = req.uri.scheme
let secure = req.uri.scheme == "https"
client.conn = conn.dial(req.uri.hostname, port, secure)
client.bio = newBio(client.conn)
client.bio.write(req)
if body.len > 0:
discard client.bio.write(body)
client.bio.flush()
# Handle response
var rsp = newResponse()
client.bio.read(rsp)
return rsp
proc readBody*(client: Client, rsp: Response): string {.cps:C.} =
if rsp.contentLength > 0:
# Get body with content length
result = client.bio.read(rsp.contentLength)
elif rsp.headers.get("transfer-encoding") == "chunked":
# Do de-chunking
while true:
let n = client.bio.readLine().parseHexInt()
if n == 0:
break
result.add client.bio.read(n)
discard client.bio.readLine()
proc get*(client: Client, url: string): Response {.cps:C} =
client.request("GET", url)