trashmail/nginx/lua/modules/response.lua

64 lines
1.4 KiB
Lua

local json = require 'json'
local module = {}
module.raw = function(status, data)
ngx.status = status
ngx.say(data)
end
module.json = function(status, data)
ngx.status = status
ngx.header['Content-type'] = 'application/json'
ngx.say(json.encode(data))
end
module.status = function(status)
ngx.status = status
end
module.exit = function(status)
return ngx.exit(status)
end
module.isValidResponseType = function(request_type)
return (request_type == 'raw' or request_type == 'json' or request_type == 'xml' or request_type == 'status') and true or false
end
module.quit = module.exit
module.xml = function(status, data)
local response = '<?xml version="1.0" encoding="utf-8"?><response>'
for i, v in pairs(data) do
response = response .. '<'..i..'>'..tostring(v)..'</'..i..'>'
end
ngx.status = status
response = response .. '</response>'
ngx.header['Content-type'] = 'text/xml; charset=utf-8'
ngx.say(response)
end
module.createResponse = function(response_type, email, domain, isBad)
if response_type == 'status' then
module.status(isBad and ngx.HTTP_FORBIDDEN or ngx.HTTP_OK)
elseif response_type == 'raw' then
module.raw(ngx.HTTP_OK, tostring(isBad))
elseif response_type == 'json' then
module.json(ngx.HTTP_OK, {
['email'] = email,
['domain'] = domain,
['bad'] = isBad
})
elseif response_type == 'xml' then
module.xml(ngx.HTTP_OK, {
['email'] = email,
['domain'] = domain,
['bad'] = isBad
})
end
end
return module