Created
September 25, 2014 22:24
-
-
Save ebith/092485a29f4adddf094c to your computer and use it in GitHub Desktop.
lua-nginx-moduleで動くGyazoServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local upload = require "resty.upload" | |
math.randomseed(ngx.time()) | |
local function random_string(digit) | |
local alphabet = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} | |
local result = "" | |
repeat | |
result = result .. alphabet[math.random(36)] | |
digit = digit - 1 | |
until digit == 0 | |
return result | |
end | |
local function file_exists(name) | |
file = io.open(name, "r") | |
if file then io.close(file) return true else return false end | |
end | |
local form = upload:new(4096) | |
if not form then | |
ngx.exit(400) | |
end | |
local file, file_name, ext | |
while true do | |
local typ, res = form:read() | |
if typ == "header" then | |
ext = string.match(res[2], "filename=%\"%S-%.(%S-)%\"") | |
if ext == "com" then ext = "png" end -- for gyazo | |
if ext then | |
repeat | |
file_name = random_string(12) .. "." .. ext | |
until not file_exists(file_name) | |
file = io.open(ngx.var.document_root .. "/" .. file_name, "w") | |
end | |
elseif typ == "body" then | |
if file then file:write(res) end | |
elseif typ == "part_end" then | |
if file then io.close(file) end | |
elseif typ == "eof" then | |
ngx.say(ngx.var.scheme .. "://" .. ngx.var.http_host .. "/" .. file_name) | |
ngx.exit(200) | |
break | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment