summaryrefslogtreecommitdiff
path: root/tests/test-http-client.lua
blob: 7d0e0957a8bc7e8a59e111020ad32624a6194b24 (plain)
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
63
64
65
66
67
68
l = require "luxio"

local req = "GET / HTTP/1.1\r\nHost: www.rjek.com\r\nConnection: close\r\n\r\n"

local r, errno

r, addrinfo = l.getaddrinfo("www.rjek.com", "80", 0, l.AF_UNSPEC, l.SOCK_STREAM)

if (r < 0) then
   io.stdout:write(("FAIL: getaddrinfo: %s\n"):format(l.gai_strerror(r)))
   os.exit(false)
end

local sock

for idx, ai in ipairs(addrinfo) do
   io.stdout:write(("STAT: trying suggestion %d...\n"):format(idx))
   for i, v in pairs(ai) do
      io.stdout:write(("STAT:  '%s' is '%s'\n"):format(tostring(i), tostring(v)))
   end
   
   sock, errno = l.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
   if (sock < 0) then
      io.stdout:write(("STAT:  can't create socket: %s\n"):format(l.strerror(errno)))
      sock = nil
   else
      r, errno = l.connect(sock, ai.ai_addr);
      if (r < 0) then
	 io.stdout:write(("STAT:  can't connect: %s\n"):format(l.strerror(errno)))
	 r, errno = l.close(sock)
	 if (r < 0) then
	    io.stdout:write(("FAIL: close: %s\n"):format(l.strerror(errno)))
	    os.exit(false)
	 end
	 sock = nil
      else
	 break -- we connected!
      end
   end
end

if (sock == nil) then
   io.stdout:write("FAIL: unable to find anything to connect to!\n")
   os.exit(false)
end

local sent = 0
while sent < #req do
   r, errno = l.write(sock, req, sent)
   if (r < 0) then
      io.stdout:write(("FAIL: write: %s\n"):format(l.strerror(errno)))
      os.exit(false);
   end
   
   sent = sent + r
   io.stdout:write(("STAT: wrote %d of %d bytes, %d total sent\n"):format(r, #req, sent))
end

repeat
   r, errno = l.read(sock, 1024)
   if (r == -1) then
      io.stdout:write(("FAIL: read: %s\n"):format(l.strerror(errno)))
      os.exit(false)
   end
      io.stdout:write(r)
until #r == 0

io.stdout:write("PASS: Well, possibly.\n")