Moonshark/http/http.lua
2025-07-14 16:03:02 -05:00

115 lines
2.2 KiB
Lua

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)
return __http_set_status(code)
end
function http.header(name, value)
return __http_set_header(name, value)
end
function http.redirect(url, status)
__http_redirect(url, status or 302)
coroutine.yield() -- Exit handler
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
-- Session functions
session = {}
function session.get(key)
return __session_get(key)
end
function session.set(key, value)
return __session_set(key, value)
end
function session.flash(key, value)
return __session_flash(key, value)
end
function session.get_flash(key)
return __session_get_flash(key)
end
-- Cookie functions
cookie = {}
function cookie.set(name, value, options)
return __cookie_set(name, value, options)
end
function cookie.get(name)
return __cookie_get(name)
end
-- CSRF functions
csrf = {}
function csrf.generate()
return __csrf_generate()
end
function csrf.validate()
return __csrf_validate()
end
function csrf.field()
local token = csrf.generate()
return string.format('<input type="hidden" name="_csrf_token" value="%s" />', token)
end
-- Helper functions
function redirect_with_flash(url, type, message)
session.flash(type, message)
http.redirect(url)
end
-- JSON encoding/decoding placeholder
json = {
encode = function(data)
-- Simplified JSON encoding
if type(data) == "table" then
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 .. "}"
elseif type(data) == "string" then
return '"' .. data .. '"'
else
return tostring(data)
end
end,
decode = function(str)
-- Simplified JSON decoding - you'd want a proper implementation
return {}
end
}