• 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))
    
  • 相关阅读:
    大二(上期)学期末个人学习总结
    《梦断代码》阅读笔记01
    软件工程概论课程评价
    03《构建之法》阅读笔记第三篇(终结篇)
    02《构建之法》阅读笔记第二篇
    个人简评——2345王牌拼音输入法
    《人件集》阅读笔记第一篇
    个人学习进度条
    AcWing ST算法(区间求最值)打卡
    AcWing 101. 最高的牛 (差分) 打卡
  • 原文地址:https://www.cnblogs.com/dslx/p/9208622.html
Copyright © 2020-2023  润新知