Openresty编写Lua代码一例

1.前段时间纠结了很久,一直弄不清lua和tomcat的联系。一直认为是lua调用tomcat的接口才可使用,后面才明白过来,进入了一个误区,lua本身就是一门独立的脚本语言。在openresty里面配置好,即可编写映射和响应。

下面是自己编写的lua代码一例,仅供参考。还有些不完善,要开始忙项目了,等有空再继续更新。

2.下面是lua代码,记得在nginx.conf写好配置。

local request_method = ngx.var.request_method
local cjson = require("cjson")
local mysql = require("resty.mysql")
local quote = ngx.quote_sql_str
local db,err = mysql:new()
local function close_db(db)  
    if not db then  
        return  
    end  
    db:close()  
end 
if not db 
then
	nax.say("new mysql error",err)
end

local args = nil
local username = nil
local pwd = nil
if "GET" == request_method
then
	args = ngx.req.get_uri_args()
elseif "POST" == ngx.request_method
then
	ngx.req.read_body()
	args = ngx.req.get_post_args()
end
username = tostring(args["username"])
pwd = tostring(args["pwd"])
if username == nil then
	ngx.say("username not nil")
	return
elseif username == '' then
	ngx.say("username not nil")
	return
elseif pwd == nil then
	ngx.say("password not nil")
	return;
elseif pwd == '' then
	ngx.say("password not nil")
	return;
end

db:set_timeout(1000)  

local props = {  
    host = "127.0.0.1",  
    port = 3306,  
    database = "hwc_hello",  
    user = "root",  
    password = "hwc123456"  
}  

local res, err, errno, sqlstate = db:connect(props) 
if not res then  
   ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
   return close_db(db)  
end 

local select_name = "select username from user_table where username="..quote(username)
res, err, errno, sqlstate = db:query(select_name)  
if not res then  
   ngx.exec("/vi/404.html")  
   return close_db(db)  
end  
local result = {}
result.success = true;
result.info = "登录成功"
ngx.say(cjson.encode(result))

 

posted @ 2018-06-21 13:48  一剑天门  阅读(890)  评论(0编辑  收藏  举报