vadv / gopher-lua-libs

Libs for gopher lua

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Usage http.server as plugin after error

spigell opened this issue · comments

Greetings! I try to start http service as plugin. But if main loop tries to restart server after error I got error binding for port. This is example.

local plugin = require("plugin")
local time = require("time")


local plugin_server = [[
http = require("http")
inspect = require("inspect")

s = {}

local server, err = http.server("127.0.0.1:5001")
if err then error(err) end

function s.start()
  while true do
    local req, resp = server:accept()
    print(inspect(req))

    if req then 
    
      print("received")
      resp:code(500)
      resp:done()

      error("I am broken")
    end
  end
end


s.start()
]]



server = plugin.do_string(plugin_server)
server:run()

while true do
  time.sleep(1)
  if not server:is_running() then
    print("error:", tostring(server:error()))
    server:run()
  end
end
error:	<string>:20: I am broken
stack traceback:
	[G]: in function 'error'
	<string>:20: in function 'start'
	<string>:26: in main chunk
	[G]: ?
error:	<string>:7: listen tcp 127.0.0.1:5001: bind: address already in use
stack traceback:
	[G]: in function 'error'
	<string>:7: in main chunk
	[G]: ?

Is any way to use http.server like this?
Thank you!

commented

good case, i will check it.
as workaround, I can suggest pcall() when processing a handler.

commented

in branch master now there are commits which stop the internal net.Listener on p:stop():

  if not server:is_running() then
    print("error:", tostring(server:error()))
    server:stop() -- close tcp listener
    server:run() -- now plugin bind tcp port successfully 
  end