--------------------------------------------------------- --- Simple HTTP library for ZD --------------------------------------------------------- local http = require("http") local fs = require("fs") return function(ZD) ZD.simpleHTTP = function(port, cb) local simpleHTTP = {} simpleHTTP.dataTypes = {} http.createServer(function (req, res) function req.socket:address() if self._handle then return self._handle:getpeername() end return nil end res:on("error", function(err) ZD.cout("Error while sending a response: " .. tostring(err)) return true end) local function out(out, _ctype, code) local body = out local ctype = _ctype or "text/html" if not body then body = ZD.htmlError(code or 404) code = code or 404 ctype= "text/html" else code = 200 end res:writeHead(code, {["Content-Type"] = ctype,["Content-Length"] = #body}) res:finish(body) end local url = ZD.parseURL(req.url) ZD.cout("Request for:", tostring(req.headers.host) .. req.url, "by:", req.socket:address().address) if simpleHTTP.dataTypes[url.ending] then local custom = simpleHTTP.dataTypes[url.ending] if type(custom) == "function" then custom(url, req, out) else if fs.existsSync("." .. url.path) then out(fs.readFileSync("." .. url.path), custom) else out() end end else if cb then cb(req, out, res) else out(nil, nil, 500) end end end):listen(port) simpleHTTP.addDataType = function(tbl, ending, custom) tbl.dataTypes[ending] = custom end ZD.cout("Started simpleHTTP Server on port", port) return simpleHTTP end end