Software /
code /
prosody
Comparison
plugins/mod_httpserver.lua @ 1667:c7bb2264e3b8
mod_httpserver: Set default file handler (you can now request static files as /*) and restructure code a bit
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Tue, 11 Aug 2009 21:33:24 +0100 |
parent | 1552:334b66f614a6 |
child | 1771:39e6b986ef01 |
comparison
equal
deleted
inserted
replaced
1666:d1243b321c45 | 1667:c7bb2264e3b8 |
---|---|
12 local open = io.open; | 12 local open = io.open; |
13 local t_concat = table.concat; | 13 local t_concat = table.concat; |
14 | 14 |
15 local http_base = "www_files"; | 15 local http_base = "www_files"; |
16 | 16 |
17 local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" }; | |
17 local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" }; | 18 local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" }; |
18 | 19 |
19 local http_path = { http_base }; | 20 local function preprocess_path(path) |
20 local function handle_request(method, body, request) | 21 if path:sub(1,1) ~= "/" then |
21 local path = request.url.path:gsub("%.%.%/", ""):gsub("^/[^/]+", ""); | 22 path = "/"..path; |
22 http_path[2] = path; | 23 end |
23 local f, err = open(t_concat(http_path), "r"); | 24 local level = 0; |
25 for component in path:gmatch("([^/]+)/") do | |
26 if component == ".." then | |
27 level = level - 1; | |
28 elseif component ~= "." then | |
29 level = level + 1; | |
30 end | |
31 if level < 0 then | |
32 return nil; | |
33 end | |
34 end | |
35 return path; | |
36 end | |
37 | |
38 function serve_file(path) | |
39 local f, err = open(http_base..path, "r"); | |
24 if not f then return response_404; end | 40 if not f then return response_404; end |
25 local data = f:read("*a"); | 41 local data = f:read("*a"); |
26 f:close(); | 42 f:close(); |
27 return data; | 43 return data; |
28 end | 44 end |
29 | 45 |
46 local function handle_file_request(method, body, request) | |
47 local path = preprocess_path(request.url.path); | |
48 if not path then return response_400; end | |
49 path = path:gsub("^/[^/]+", ""); -- Strip /files/ | |
50 return serve_file(path); | |
51 end | |
52 | |
53 local function handle_default_request(method, body, request) | |
54 local path = preprocess_path(request.url.path); | |
55 if not path then return response_400; end | |
56 return serve_file(path); | |
57 end | |
58 | |
30 local ports = config.get(module.host, "core", "http_ports") or { 5280 }; | 59 local ports = config.get(module.host, "core", "http_ports") or { 5280 }; |
31 httpserver.new_from_config(ports, "files", handle_request); | 60 httpserver.set_default_handler(handle_default_request); |
61 httpserver.new_from_config(ports, "files", handle_file_request); |