|
| 1 | +-- A simple one-time pastebin. |
| 2 | +-- |
| 3 | +-- This example will keep updating with upcoming new features of Abel. |
| 4 | + |
| 5 | +local crypto = require "crypto" |
| 6 | +local fs = require "fs" |
| 7 | + |
| 8 | +local method_not_allowed = HttpError { |
| 9 | + status = 405, |
| 10 | + error = "method not allowed", |
| 11 | +} |
| 12 | + |
| 13 | +local function gen_uid() |
| 14 | + local template = "xxxxxxxx" |
| 15 | + return (string.gsub(template, "x", function(c) |
| 16 | + local v = crypto.thread_rng:gen_range(0, 0xf) |
| 17 | + return string.format('%x', v) |
| 18 | + end)) |
| 19 | +end |
| 20 | + |
| 21 | +function abel.start() |
| 22 | + fs.mkdir "files" |
| 23 | +end |
| 24 | + |
| 25 | +abel.listen("/", function(req) |
| 26 | + if req.method ~= "POST" then |
| 27 | + error(method_not_allowed { |
| 28 | + allowed = { "POST" }, |
| 29 | + got = req.method, |
| 30 | + }) |
| 31 | + end |
| 32 | + |
| 33 | + local content = req.body:to_string() |
| 34 | + local uid = gen_uid() |
| 35 | + |
| 36 | + local file <close> = assert(io.open("files/" .. uid, "w")) |
| 37 | + assert(file:write(content)) |
| 38 | + |
| 39 | + return { uid = uid } |
| 40 | +end) |
| 41 | + |
| 42 | +abel.listen("/:uid", function(req) |
| 43 | + if req.method ~= "GET" then |
| 44 | + error(method_not_allowed { |
| 45 | + allowed = { "GET" }, |
| 46 | + got = req.method, |
| 47 | + }) |
| 48 | + end |
| 49 | + |
| 50 | + local uid = req.params.uid |
| 51 | + if #uid ~= 8 then |
| 52 | + error { status = 400, error = "invalid UID" } |
| 53 | + end |
| 54 | + |
| 55 | + local path = "files/" .. uid |
| 56 | + local file = io.open(path) |
| 57 | + if not file then |
| 58 | + error { status = 404, error = "file not found" } |
| 59 | + end |
| 60 | + |
| 61 | + -- This works on POSIX systems, but not Windows |
| 62 | + assert(os.remove(path)) |
| 63 | + return file:into_stream() |
| 64 | +end) |
0 commit comments