Moonshark/http/http.lua
2025-07-14 17:36:59 -05:00

149 lines
3.0 KiB
Lua

-- Fast response handling
local response = {status = 200, headers = {}, cookies = {}}
local session_data = {}
http = {}
function http.listen(port)
return __http_listen(port)
end
function http.route(method, path, handler)
return __http_route(method, path, handler)
end
function http.status(code)
response.status = code
end
function http.header(k, v)
response.headers[k] = v
end
function http.json(data)
http.header("Content-Type", "application/json")
return json.encode(data)
end
function http.html(content)
http.header("Content-Type", "text/html")
return content
end
function http.text(content)
http.header("Content-Type", "text/plain")
return content
end
function http.redirect(url, code)
response.status = code or 302
response.headers["Location"] = url
coroutine.yield()
end
-- Session functions
session = {}
function session.get(key)
return session_data[key]
end
function session.set(key, val)
session_data[key] = val
end
function session.flash(key, val)
session_data["_flash_" .. key] = val
end
function session.get_flash(key)
local val = session_data["_flash_" .. key]
session_data["_flash_" .. key] = nil
return val
end
-- Cookie functions
cookie = {}
function cookie.get(name)
return COOKIES and COOKIES[name]
end
function cookie.set(name, value, options)
response.cookies[#response.cookies + 1] = {
name = name,
value = value,
options = options or {}
}
end
-- CSRF functions
csrf = {}
function csrf.generate()
local token = CSRF_TOKEN or ""
session.set("_csrf_token", token)
return token
end
function csrf.validate()
local session_token = session.get("_csrf_token")
local form_token = FORM and FORM._csrf_token
return session_token and session_token == form_token
end
function csrf.field()
return '<input type="hidden" name="_csrf_token" value="' .. csrf.generate() .. '" />'
end
-- Fast JSON encoding
json = {
encode = function(data)
if type(data) == "string" then
return '"' .. data .. '"'
elseif type(data) == "number" then
return tostring(data)
elseif type(data) == "boolean" then
return data and "true" or "false"
elseif data == nil then
return "null"
elseif type(data) == "table" then
-- Check if it's an array
local isArray = true
local n = 0
for k, v in pairs(data) do
n = n + 1
if type(k) ~= "number" or k ~= n then
isArray = false
break
end
end
if isArray then
local result = "["
for i = 1, n do
if i > 1 then result = result .. "," end
result = result .. json.encode(data[i])
end
return result .. "]"
else
local result = "{"
local first = true
for k, v in pairs(data) do
if not first then result = result .. "," end
result = result .. '"' .. tostring(k) .. '":' .. json.encode(v)
first = false
end
return result .. "}"
end
else
return json_encode_fallback(data)
end
end
}
-- Helper functions
function redirect_with_flash(url, type, message)
session.flash(type, message)
http.redirect(url)
end