Skip to content

Commit

Permalink
Add support for custom error documents and provide an example
Browse files Browse the repository at this point in the history
  • Loading branch information
devurandom committed Dec 16, 2012
1 parent fda1476 commit 1a17597
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
12 changes: 12 additions & 0 deletions error-document.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
return function (app, options)
return function (req, res)
app(req, function (code, headers, body)
local errordocument = options[code]
if errordocument then
errordocument(code, headers, body, res)
else
res(code, headers, body)
end
end)
end
end
36 changes: 36 additions & 0 deletions errorhandlers.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
local errorhandlers = {}

function errorhandlers.text(text)
return function (code, headers, body, res)
res(code, headers, text)
end
end

function errorhandlers.file(path)
return function (code, headers, body, res)
local file = io.open(path)
body = file:read("*a")
res(code, headers, body)
end
end

function errorhandlers.execute(path)
return function (code, headers, body, res)
local chunk = loadfile(path)
local success, err = pcall(chunk, code, headers, body, res)
if not success then
error("Failed to execute error document handler: " .. err)
res(code, headers, body)
end
end
end

function errorhandlers.redirect(url)
return function (code, headers, body, res)
code = 302
headers["Location"] = url
res(code, headers, {})
end
end

return errorhandlers
46 changes: 46 additions & 0 deletions samples/test-errordocument.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
local p = require('utils').prettyPrint
local socketHandler = require('web').socketHandler
local createServer = require('uv').createServer
local errhdl = require('errorhandlers')

local host = os.getenv("IP") or "0.0.0.0"
local port = os.getenv("PORT") or 8080

local state = 1
local app = function (req, res)
local code = 200
if state > 3 then
code = 404
end

res(code, {
["Content-Type"] = "text/plain"
}, {"Hello ", "World ", tostring(state), "\n"})

if req.url.path == "/" then
state = state + 1
end
end

app = require('error-document')(app, {
[404] = errhdl.text("TEST 404"),
})

app = require('autoheaders')(app)

app = require('log')(app)

p{app=app}

app({
method = "GET",
url = { path = "/" },
headers = {}
}, p)

createServer(host, port, socketHandler(app))
print("http server listening at http://localhost:8080/")

require('luv').run()

print("done.")

0 comments on commit 1a17597

Please sign in to comment.