lua demo

ngx.header.content_type = "text/plain"
local cjson = require "cjson";
local funova_libs = require "funova_libs";

local Code_Result =
{
success = 1, --礼包领取成功
not_exists = 2, --礼包码无效
used = 3, --礼包码已被使用
channel_not_match = 4, --礼包码无效
channel_used = 5, --已经领取过此类礼包
channel_error = 6, --礼包码无效
error = 7 --兑换失败
}

redis_instance = funova_libs:redis_connect();

function UpdateCode(param)
local result = {}
if redis_instance then
local pid = param['pid'];
local code = param['code'];
local channel = param['ch'];

--ngx.say("pid:"..pid .. " code:"..code .. " ch:"..channel)
if pid and code and channel then
local usepid = redis_instance:hget("code_hash",code)

result["statu"] = 0;
if usepid == ngx.null then
result["msg"] = "Code not exists!";
result["statu"] = Code_Result.not_exists
elseif usepid ~= "0" then
result["msg"] = "Code has been used!";
result["statu"] = Code_Result.used
else
local code_type_ch = string.sub(code, 1,6)
local code_ch = string.sub(code, 4,6)

local ch = redis_instance:hget("channel_hash", code_ch)
if ch == ngx.null then
result["msg"] = "Code not exists, channel error";
result["statu"] = Code_Result.channel_error
elseif ch ~= channel then
result["msg"] = "Code can not use on this channel : "..ch;
result["statu"] = Code_Result.channel_not_match
else
local pid_code_type = pid.."|"..code_type_ch
local usecnt = redis_instance:hget("pid_use_code_hash",pid_code_type)
if usecnt == ngx.null then --默认 一种类型的激活码只能使用一次
redis_instance:hset("code_hash", code, pid)
redis_instance:hincrby("pid_use_code_hash", pid_code_type,1);
result["statu"] = Code_Result.success
result["msg"] = "ok";
elseif usecnt >= "1" then
result["msg"] = "Has been used code on this channel";
result["statu"] = Code_Result.channel_used
end
end

end
else
result["msg"] = "parm error"
result["statu"] = Code_Result.error
--ngx.say("{\"statu\" : 0, \"msg\" : 'param error'}")
end
else
result["msg"] = "redis connect error"
result["statu"] = Code_Result.error
end

res_json = cjson.encode(result)
ngx.say(res_json)
end

function GetArgs()
local request_method = ngx.var.request_method
local args = nil
if "GET" == request_method then
args = ngx.req.get_uri_args()
elseif "POST" == request_method then
ngx.req.read_body()
args = ngx.req.get_post_args()
end
return args;
end


local args = GetArgs()
UpdateCode(args)

posted @ 2015-06-08 20:22  麦田守望者~  阅读(519)  评论(0编辑  收藏  举报