# HG changeset patch # User Matthew Wild # Date 1335449789 -3600 # Node ID 4ddf3ba0c749bbbabd57549f5fcc6e1918fd1fff # Parent 54ca6511e699607bdee9953ab7a363bf8359b19d mod_http_errors: Module to handle HTTP errors with a HTML page diff -r 54ca6511e699 -r 4ddf3ba0c749 plugins/mod_http_errors.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plugins/mod_http_errors.lua Thu Apr 26 15:16:29 2012 +0100 @@ -0,0 +1,75 @@ +module:set_global(); +module:depends("http"); + +local server = require "net.http.server"; +local codes = require "net.http.codes"; +local termcolours = require "util.termcolours"; + +local show_private = module:get_option_boolean("http_errors_detailed", false); + +local default_messages = { + [400] = { "What kind of request do you call that??" }; + [403] = { "You're not allowed to do that." }; + [404] = { "Whatever you were looking for is not here. %"; + "Where did you put it?", "It's behind you.", "Keep looking." }; + [500] = { "% Check your error log for more info."; + "Gremlins.", "It broke.", "Don't look at me." }; +}; + +local messages = setmetatable(module:get_option("http_errors_messages", {}), { __index = default_messages }); + +local html = [[ + + + + + + + +

$title

+

$message

+

$extra

+ +]]; +html = html:gsub("%s%s+", ""); + +local entities = { + ["<"] = "<", [">"] = ">", ["&"] = "&", + ["'"] = "'", ["\""] = """, ["\n"] = "
", +}; + +local function tohtml(plain) + return (plain:gsub("[<>&'\"\n]", entities)); + +end + +local function get_page(code, extra) + local message = messages[code]; + if message then + return (html:gsub("$(%a+)", { + title = rawget(codes, code) or ("Code "..tostring(code)); + message = message[1]:gsub("%%", function () + return message[math.random(2, math.max(#message,2))]; + end); + extra = tohtml(extra or ""); + })); + end +end + +module:hook_object_event(server, "http-error", function (event) + return get_page(event.code, (show_private and event.private_message) or event.message); +end);