-- a helper for handling API results: throws an error if the call
-- was unsuccessful, otherwise returns the result
function must(...)
local ok, result = ...
if not ok then
error(result)
end
return result
end
-- open a database connection
local db = must(luna.db.open("file:db.sqlite?_journal=WAL&_sync=NORMAL"))
must(luna.db.exec(db, [[
CREATE TABLE IF NOT EXISTS hits(creation_time DATETIME NOT NULL);
]], {}))
-- register a GET / route that displays a home page for the example site
luna.router.route("GET /", function (request)
local response = "{\"method\": \"" .. request.method .. "\""
response = response .. ", \"path\": \"" .. request.path .. "\"}"
return 200, {["Content-Type"] = "text/html"}, [[
A simple example of website made for luna
Wow! A simple website made for luna?
]]
end)
-- register a GET /json route and return some request data in response
luna.router.route("GET /json", function (request)
local response = "{\"method\": \"" .. request.method .. "\""
response = response .. ", \"path\": \"" .. request.path .. "\"}"
return 200, {["Content-Type"] = "application/json"}, response
end)
-- register a GET /db route. visiting it writes a hit to the database and
-- displays visits count
luna.router.route("GET /db", function (request)
local ok, err = luna.db.exec(
db,
"INSERT INTO hits VALUES (?)",
{os.date("%Y-%m-%d %H:%M:%S")}
)
if not ok then
return 500,
{["Content-Type"] = "application/json"},
"error while saving to db: " .. err
end
local ok, res = luna.db.query(db, "SELECT COUNT(*) FROM hits", {})
if not ok then
return 500,
{["Content-Type"] = "application/json"},
"error while querying db: " .. res
end
return 200, {["Content-Type"] = "text/html"}, "Hits: " .. tostring(res[1][1])
end)
-- register a GET /request route. when visited makes an HTTP-request to
-- https://ifconfig.me service and displays the result
luna.router.route("GET /request", function ()
local ok, response = luna.http.request("GET", "https://ifconfig.me", {}, "")
if not ok then
return 500,
{["Content-Type"] = "application/json"},
"error while fetching data from ifconfig.me: " .. response
end
return 200, {}, "Your IP is: " .. response.body
end)
-- serve static files from static/ directory
luna.router.static("GET /static/", "static/")
-- register a custom eval handler that will evaluate whatever is passed into
-- luna stdio when it's run with -D flag. in this case we print the result of
-- evaluation. eval handler is evaluated once for each worker so the result
-- may be printed more than once
luna.onEval(function (text)
local res = (_G.loadstring or _G.load)(text)
res()
end)