20 local tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type; |
20 local tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type; |
21 |
21 |
22 local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end |
22 local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end |
23 |
23 |
24 local log = require "util.logger".init("httpserver"); |
24 local log = require "util.logger".init("httpserver"); |
|
25 |
|
26 -- TODO: Should we read this from /etc/mime.types if it exists? (startup time...?) |
|
27 local mime_map = { html = "text/html", txt = "plain/text; charset=utf-8", js = "text/javascript" }; |
25 |
28 |
26 local http_servers = {}; |
29 local http_servers = {}; |
27 |
30 |
28 module "httpserver" |
31 module "httpserver" |
29 |
32 |
63 -- Response we have is just a string (the body) |
66 -- Response we have is just a string (the body) |
64 log("debug", "Sending 200 response to %s", request.id or "<none>"); |
67 log("debug", "Sending 200 response to %s", request.id or "<none>"); |
65 |
68 |
66 resp = { "HTTP/1.0 200 OK\r\n" }; |
69 resp = { "HTTP/1.0 200 OK\r\n" }; |
67 t_insert(resp, "Connection: close\r\n"); |
70 t_insert(resp, "Connection: close\r\n"); |
|
71 t_insert(resp, "Content-Type: "); |
|
72 t_insert(resp, mime_map[request.url.path:match("%.(%w+)")] or "application/octet-stream"); |
|
73 t_insert(resp, "\r\n"); |
68 t_insert(resp, "Content-Length: "); |
74 t_insert(resp, "Content-Length: "); |
69 t_insert(resp, #response); |
75 t_insert(resp, #response); |
70 t_insert(resp, "\r\n\r\n"); |
76 t_insert(resp, "\r\n\r\n"); |
71 |
77 |
72 t_insert(resp, response); |
78 t_insert(resp, response); |