81 lines
2.0 KiB
Lua
81 lines
2.0 KiB
Lua
local cjson = require('cjson')
|
|
local conf = require('config')
|
|
local error_code = require('util.status')
|
|
|
|
local _M = {}
|
|
|
|
function _M:json(status, message, data, http_status)
|
|
-- you can modify this response struct as you favor
|
|
if status == 0 then status = ngx.HTTP_OK end
|
|
local msg = message
|
|
local response_status = http_status or ngx.HTTP_OK
|
|
if msg == nil or msg == '' then
|
|
--local locale = ngx.ctx.locale or conf.locale
|
|
--if error_code[locale] ~= nil then
|
|
--msg = error_code[locale][status]
|
|
--end
|
|
msg = error_code[status]
|
|
end
|
|
local response = {code = status, msg = msg, result = data,timestamp = ngx.time()}
|
|
if not response.code then
|
|
response.code = -1
|
|
response.message = 'not find status code'
|
|
end
|
|
return {
|
|
code = response_status,
|
|
headers = {content_type = 'application/json; charset=UTF-8'},
|
|
body = cjson.encode(response)
|
|
}
|
|
end
|
|
|
|
function _M:json(status, data, http_status)
|
|
-- you can modify this response struct as you favor
|
|
if status == 0 then status = ngx.HTTP_OK end
|
|
local msg = ''
|
|
local response_status = http_status or ngx.HTTP_OK
|
|
msg = error_code[status]
|
|
|
|
local response = {code = status, msg = msg, result = data,timestamp = ngx.time()}
|
|
if not response.code then
|
|
response.code = -1
|
|
response.message = 'not find status code'
|
|
end
|
|
return {
|
|
code = response_status,
|
|
headers = {content_type = 'application/json; charset=UTF-8'},
|
|
body = cjson.encode(response)
|
|
}
|
|
end
|
|
|
|
function _M:raw(http_status, http_body)
|
|
return {
|
|
code = http_status,
|
|
headers = {},
|
|
body = http_body,
|
|
timestamp = ngx.time()
|
|
}
|
|
end
|
|
|
|
function _M:error(http_status, http_headers, http_body)
|
|
return {
|
|
code = http_status,
|
|
headers = http_headers,
|
|
body = http_body,
|
|
timestamp = ngx.now()
|
|
}
|
|
end
|
|
|
|
function _M:send(response)
|
|
ngx.status = response.code
|
|
if response.headers ~= nil then
|
|
for name, value in pairs(response.headers) do
|
|
ngx.header[name] = value
|
|
end
|
|
end
|
|
if response.body ~= nil then
|
|
ngx.say(response.body)
|
|
end
|
|
end
|
|
|
|
return _M
|