This repository was archived by the owner on Nov 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp.lua
More file actions
73 lines (61 loc) · 2.35 KB
/
Copy pathhttp.lua
File metadata and controls
73 lines (61 loc) · 2.35 KB
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
69
70
71
72
73
local http = {}
function http.parseUrl(url)
local components = {}
components.scheme = string.match(url, "([^:]*):")
components.host = string.match(url, components.scheme .. "://([^:/]*)[:/]?")
components.port = string.match(url, components.scheme .. "://" .. components.host .. ":([%d]*)")
baseUrl = components.scheme .. "://" .. components.host
if components.port ~= nil then
baseUrl = baseUrl .. ":" .. components.port
end
components.pathAndQueryString = string.sub(url, string.len(baseUrl) + 1)
return components
end
function http.getContent(url, callWithData)
http.sendContent("GET", url, nil, nil, callWithData)
end
function http.postContent(url, content, contentType, callWithData)
http.sendContent("POST", url, content, contentType, callWithData)
end
function http.sendContent(method, url, contentToSend, contentType, callWithData)
local components = http.parseUrl(url)
if components.port == nil then
components.port = 80
else
components.port = to_number(components.port)
end
if components.pathAndQueryString == nil or components.pathAndQueryString == "" then
components.pathAndQueryString = "/"
end
if contentType == nil then
contentType = "application/x-www-form-urlencoded"
end
local conn=net.createConnection(net.TCP, false)
conn:on("connection", function(conn)
conn:send(method .. " " .. components.pathAndQueryString .. " HTTP/1.0\r\nHost: " .. components.host .. "\r\n"
.. "Accept: */*\r\n")
if contentToSend ~= nil then
conn:send("Content-Type: " .. contentType .. "\r\n");
conn:send("Content-Length: " .. string.len(contentToSend) .. "\r\n\r\n")
conn:send(contentToSend)
else
conn:send("\r\n")
end
end)
conn:on("receive", function(conn, pl)
local data = {}
data.status = string.match(pl, "HTTP/%d.%d (%d+)")
local location = string.find(pl, "\r\n\r\n")
if location ~= nil then
data.content = string.sub(pl, location + 4)
end
pl = nil
collectgarbage()
conn:close()
conn = nil
callWithData(data)
data = nil
end)
conn:connect(components.port, components.host)
end
return http