Software / code / prosody
Comparison
plugins/mod_http_errors.lua @ 4711:4ddf3ba0c749
mod_http_errors: Module to handle HTTP errors with a HTML page
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Thu, 26 Apr 2012 15:16:29 +0100 |
| child | 4737:7b9e2a8c4710 |
comparison
equal
deleted
inserted
replaced
| 4710:54ca6511e699 | 4711:4ddf3ba0c749 |
|---|---|
| 1 module:set_global(); | |
| 2 module:depends("http"); | |
| 3 | |
| 4 local server = require "net.http.server"; | |
| 5 local codes = require "net.http.codes"; | |
| 6 local termcolours = require "util.termcolours"; | |
| 7 | |
| 8 local show_private = module:get_option_boolean("http_errors_detailed", false); | |
| 9 | |
| 10 local default_messages = { | |
| 11 [400] = { "What kind of request do you call that??" }; | |
| 12 [403] = { "You're not allowed to do that." }; | |
| 13 [404] = { "Whatever you were looking for is not here. %"; | |
| 14 "Where did you put it?", "It's behind you.", "Keep looking." }; | |
| 15 [500] = { "% Check your error log for more info."; | |
| 16 "Gremlins.", "It broke.", "Don't look at me." }; | |
| 17 }; | |
| 18 | |
| 19 local messages = setmetatable(module:get_option("http_errors_messages", {}), { __index = default_messages }); | |
| 20 | |
| 21 local html = [[ | |
| 22 <!DOCTYPE html> | |
| 23 <html> | |
| 24 <head> | |
| 25 <meta charset="utf-8"> | |
| 26 <style> | |
| 27 body{ | |
| 28 margin-top:14%; | |
| 29 text-align:center; | |
| 30 background-color:#F8F8F8; | |
| 31 font-family:sans-serif; | |
| 32 } | |
| 33 h1{ | |
| 34 font-size:xx-large; | |
| 35 } | |
| 36 p{ | |
| 37 font-size:x-large; | |
| 38 } | |
| 39 p+p { font-size: large; font-family: courier } | |
| 40 </style> | |
| 41 </head> | |
| 42 <body> | |
| 43 <h1>$title</h1> | |
| 44 <p>$message</p> | |
| 45 <p>$extra</p> | |
| 46 </body> | |
| 47 </html>]]; | |
| 48 html = html:gsub("%s%s+", ""); | |
| 49 | |
| 50 local entities = { | |
| 51 ["<"] = "<", [">"] = ">", ["&"] = "&", | |
| 52 ["'"] = "'", ["\""] = """, ["\n"] = "<br/>", | |
| 53 }; | |
| 54 | |
| 55 local function tohtml(plain) | |
| 56 return (plain:gsub("[<>&'\"\n]", entities)); | |
| 57 | |
| 58 end | |
| 59 | |
| 60 local function get_page(code, extra) | |
| 61 local message = messages[code]; | |
| 62 if message then | |
| 63 return (html:gsub("$(%a+)", { | |
| 64 title = rawget(codes, code) or ("Code "..tostring(code)); | |
| 65 message = message[1]:gsub("%%", function () | |
| 66 return message[math.random(2, math.max(#message,2))]; | |
| 67 end); | |
| 68 extra = tohtml(extra or ""); | |
| 69 })); | |
| 70 end | |
| 71 end | |
| 72 | |
| 73 module:hook_object_event(server, "http-error", function (event) | |
| 74 return get_page(event.code, (show_private and event.private_message) or event.message); | |
| 75 end); |