napkin/main.lua
2025-03-08 00:07:37 -03:00

103 lines
2.7 KiB
Lua

local weblit = require('weblit')
local cookie = require('weblit-cookie')
local multipart = require('weblit-multipart')
local timer = require("timer")
local radon = require("radon")
local foppy = require("./foppy")
local database = require("./database")
local errors = require("./errors")
local utils = require("./utils")
local templater = function(template, rate)
return function(req, res)
if rate then
local coro = coroutine.running()
timer.setTimeout(rate, function()
if coroutine.status(coro) ~= "dead" then
coroutine.resume(coro)
end
end)
end
local func = dofile("template/" .. template .. ".lua")
res.code = 200
res.body = radon.compile(func, {
request = req,
response = res
})
res.headers["Content-Type"] = "text/html"
if rate then
coroutine.yield()
end
end
end
weblit.app
.bind({ host = "0.0.0.0", port = 1337 })
-- Configure weblit server
.use(weblit.logger)
.use(weblit.autoHeaders)
.use(utils.forms)
.use(cookie)
.route(
{ path = "/static/:path" },
weblit.static("static")
)
.route(
{ path = "/media/:path:", method = "GET" },
weblit.static("database/media")
)
.route(
{ path = "/media", method = "POST" },
multipart { writeTo = "database/media" }
)
-- TODO: CLONE ALL OF THIS AS A REST API EVENTUALLY,
.route({ path = "/signup" }, templater("signup"))
.route({ path = "/signup2" }, templater("signup2", 3000))
.route({ path = "/login" }, templater("login"))
.route({ path = "/login2" }, templater("login2", 3000))
.route({ path = "/logout" }, templater("logout", 3000))
.route({ path = "/new-blog" }, templater("new-blog"))
.route({ path = "/new-blog2" }, templater("new-blog2", 2000))
.route({ path = "/@:blog" }, templater("blog"))
.route({ path = "/@:blog/:post" }, templater("post"))
.route({ path = "/p/:path" }, function(req, res)
local path = req.params.path
if #path == 0 then
res.code = 301
res.headers["Location"] = "/"
return
end
local redirects = foppy.open("database/redirects.json")
assert(redirects)
local redirect = redirects[path]
if redirect then
res.code = 301
res.headers["Location"] = redirect
return
end
return error_handler({
request = req,
response = res
}, "post_not_found", "/")
end)
.route({ path = "/" }, templater("index"))
.route({ path = "/rules" }, templater("rules"))
-- Start the server
.start()