ikibooru/pegasus/init.lua
2024-06-01 17:40:11 +03:00

64 lines
1.8 KiB
Lua

local socket = require 'socket'
local Handler = require 'pegasus.handler'
local FCNTL = require 'posix.fcntl'
local time = require 'posix.time'
local Pegasus = {}
Pegasus.__index = Pegasus
function Pegasus:new(params)
params = params or {}
local server = {}
server.host = params.host or '*'
server.port = params.port or '9090'
server.location = params.location or ''
server.plugins = params.plugins or {}
server.timeout = params.timeout or 1
server.threads = {}
return setmetatable(server, self)
end
function Pegasus:start(callback)
local handler = Handler:new(callback, self.location, self.plugins)
local server = assert(socket.bind(self.host, self.port))
local ip, port = server:getsockname()
print('Pegasus is up on ' .. ip .. ":".. port)
FCNTL.fcntl(server:getfd(), FCNTL.F_SETFD, FCNTL.FD_CLOEXEC)
--server:settimeout(0)
local i = 1
while 1 do
local client, errmsg = server:accept()
if client then
FCNTL.fcntl(client:getfd(), FCNTL.F_SETFD, FCNTL.FD_CLOEXEC)
client:settimeout(self.timeout, 'b')
--local coro = coroutine.create(handler.processRequest)
--coroutine.resume(coro, handler, self.port, client, server)
--if coroutine.status(coro) ~= "dead" then
-- self.threads[#self.threads + 1] = coro
--end
handler:processRequest(self.port, client, server)
elseif errmsg ~= 'timeout' then
io.stderr:write('Failed to accept connection:' .. errmsg .. '\n')
end
--[[if #self.threads > 0 then
coroutine.resume(self.threads[i])
if coroutine.status(self.threads[i]) == "dead" then
table.remove(self.threads, i)
else
i = i % #self.threads + 1
end
else
time.nanosleep({tv_sec = 0, tv_nsec = 500000})
end]]
end
end
return Pegasus