Skip to content

Instantly share code, notes, and snippets.

@mengskysama
Last active January 2, 2017 14:44
Show Gist options
  • Save mengskysama/325ec5a116ac2c39676511caa906fc1d to your computer and use it in GitHub Desktop.
Save mengskysama/325ec5a116ac2c39676511caa906fc1d to your computer and use it in GitHub Desktop.
location ~ /(\d+)(.*) {
set $size $1;
set $unit $2;
access_by_lua_block {
local sent = 0
local bufsize = 8192
local payload = string.rep("0", bufsize)
local _u = ngx.var.unit
if _u ~= nil and _u ~= "" then
_u = string.lower(_u)
else
_u = "m"
end
local size_table = {
b = 1,
k = 1024,
m = 1048576,
g = 1073741824,
}
local dsize = ngx.var.size * size_table[_u]
if dsize > 1099511627776 then
ngx.exit(404)
end
local range = ngx.req.get_headers()["Range"]
if range ~= nil then
local content_range = string.gsub(range, "=", " ") .. "/" .. dsize
ngx.header["Content-Range"] = content_range
ngx.status = 206
end
ngx.header["Content-Length"] = dsize
ngx.header["Content-Type"] = "application/octet-stream"
local _bufferd = 0
while sent < dsize do
ngx.say(payload)
_bufferd = _bufferd + bufsize
if _bufferd > 524288 then
local ok, err = ngx.flush(true)
if not ok then
break
end
_bufferd = 0
end
sent = sent + bufsize
end
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment