Openresty

lua-mysql

function _M.val_escape(val)
    if val then
        -- 防止SQL注入,OpenResty自带
        return ndk.set_var.set_quote_mysql_str(val)
    else
        return "null"
    end
end
function _M.val_escape(val)
    local type = type(val)
    if "string" == type then
        return "'" .. tostring((val:gsub("'", "''"))) .. "'"
    elseif "number" == type then
        return tostring(val)
    elseif "boolean" == val then
        return val and "TRUE" or "FALSE"
    else
        return "null"
    end
end

OPM

OPM(OpenResty Package Manager)是 OpenResty 官方提供的包管理工具,可以用来从中心 OPM 包服务器上面安装社区贡献的第三方模块。专门用于安装和管理 OpenResty 的 Lua 模块。

它是官方推荐使用的工具,因为它确保了模块与 OpenResty 的兼容性,并优化了性能,在你安装好 OpenResty 之后,就可以直接使用。

# openresty-opm.noarch : OpenResty Package Manager
# openresty-doc.noarch : OpenResty documentation tool, restydoc

yum install openresty-opm openresty-resty openresty-doc

opm list
opm install bungle/lua-resty-template
openresty/lua-resty-websocket                     Lua WebSocket implementation for the ngx_lua module
openresty/lua-resty-mysql                         Lua MySQL client driver for ngx_lua based on the cosocket API
openresty/lua-resty-redis                         Lua redis client driver for the ngx_lua based on the cosocket API

bungle/lua-resty-template                         Templating Engine (HTML) for Lua and OpenResty
https://github.com/bungle/lua-resty-template

bungle/lua-resty-session                          Session Library for OpenResty - Flexible and Secure
https://github.com/bungle/lua-resty-session

agentzh/lua-resty-http                            Lua HTTP client cosocket driver for OpenResty/ngx_lua

bungle/lua-resty-validation                       Validation Library (Input Validation and Filtering) for Lua and OpenResty

https://github.com/pronan/lua-resty-mvc

Lua

前端

lua-resty-template

标签 用途 范例 说明
{{expression}} 写入结果,html转义    
{*expression*} 写入结果    
{% lua code %} 执行lua代码    
{(template)} 包含模板文件 {(file.html, { message = "Hello, World" } )} 文件名不能包含,号
{(template, context)}   传入指定的新context
{[expression]} 用表达式包含文件 {["file,with,comma"]} 文件名有,时也可用此方式替代
{-block-}...{-block-} 块引用-为存储的块表    
{-verbatim-}...{-verbatim-} 内部不做处理原样输出   内部预定义块
{-raw-}...{-raw-}  
{# comments #} 注释,不执行和输出    
\ 用\排除处理模板标签 \{{message}}  
\\ 对\转义 \\{{message}}  
       

ajax请求

后端返回数据

{
    "status": "success",
    "data": {
        "user": {
            "id": 1,
            "name": "Alice",
            "email": "alice@example.com"
        },
        "items": ["apple", "banana"]
    }
}

提取嵌套数据

$.ajax({
    url: "/api/user",
    dataType: "json",
    success: function(response) {
        if (response.status === "success") {
            const user = response.data.user;
            const items = response.data.items;
            
            // 更新 DOM
            $("#user-name").text(user.name);
            $("#user-email").text(user.email);
            
            // 动态生成列表
            const listHtml = items.map(item => `<li>${item}</li>`).join("");
            $("#item-list").html(listHtml);
        } else {
            console.error("后端业务逻辑错误:", response.message);
        }
    }
});

完整示例:提交表单并处理 JSON 响应

明确告知 jQuery 将响应解析为 JSON,避免手动调用 JSON.parse。

如果请求跨域,确保后端设置了正确的 CORS 头(如 Access-Control-Allow-Origin)。

对动态插入到 DOM 中的 JSON 数据做 XSS 转义(如使用 .text() 而非 .html())。

敏感数据(如密码)避免明文传输,使用 HTTPS。

使用浏览器开发者工具(Network 面板)检查请求和响应内容。

js字符串拼接

时间

Date.parse("2023-10-01T12:00:00Z");        // UTC 时间
Date.parse("2023-10-01T12:00:00+08:00");   // 东八区时间

// 假设本地时区是东八区(UTC+8)
Date.parse("2023-10-01T12:00:00");
// 等价于解析为 "2023-10-01T12:00:00+08:00"

使用 Date.UTC() 构造 UTC 时间戳
// 将年月日等参数按 UTC 解析
const year = 2023, month = 9, day = 1; // 月份从 0 开始(0=1月)
const timestampUTC = Date.UTC(year, month, day, 12, 0, 0);

// 假设原始时间字符串是本地时区,需转为 UTC
const localTime = "2023-10-01T12:00:00";
const date = new Date(localTime);
const timestampUTC = date.getTime() - date.getTimezoneOffset() * 60 * 1000;

ISO 8601 格式(YYYY-MM-DDTHH:mm:ssZ)

javascript中的时区

// 假设本地时区为 UTC+8(东八区)

// 带时区信息(UTC)
const utcTime = Date.parse("2023-10-01T12:00:00Z");
console.log(utcTime); // 1696161600000(UTC 时间戳)

// 无时区信息(按本地时区解析)
const localTime = Date.parse("2023-10-01T12:00:00");
console.log(localTime); // 1696132800000(比 UTC 时间戳少 8 小时)

// 带东八区时区信息(结果与 UTC 解析不同)
const cstTime = Date.parse("2023-10-01T12:00:00+08:00");
console.log(cstTime === localTime); // true(因为本地时区就是东八区)

Date.parse() 的时区行为由输入字符串的时区标识决定。

若需精确控制时区,请始终在字符串中包含时区信息(如 Z 或 +HH:mm)。

对于复杂时区操作,建议使用专门的日期库(如 moment-timezone)。

ngx调用接口

模拟一个接口场景,一个公共服务专门用来对外提供加了“盐” md5 计算,业务系统调用这个公共服务完成业务逻辑,用来判断请求本身是否合法。

http {
  server {
    listen  80;

    location /test {
      content_by_lua_block {
        ngx.req.read_body()
        local args, err = ngx.req.get_uri_args()

        local http = require "resty.http"   -- 引用 resty.http 库资源
        local httpc = http.new()
        local res, err = httpc:request_uri( -- request_uri 函数完成了连接池、HTTP 请求等一系列动作
          "http://127.0.0.1:81/spe_md5",
            {
            method = "POST",
            body = args.data,
            }
        )

        if 200 ~= res.status then
          ngx.exit(res.status)
        end

        if args.key == res.body then
          ngx.say("valid request")
        else
          ngx.say("invalid request")
        end
      }
    }
  }

  server {
    listen  81;

    location /spe_md5 {
      content_by_lua_block {
        ngx.req.read_body()
        local data = ngx.req.get_body_data()
        ngx.print(ngx.md5(data .. "*&^%$#$^&kjtrKUYG"))
      }
    }
  }
}

VScode换行符设置

windows默认是回车换行符,即:\r\n

linux默认是换行符,即:\n

同时在两种操作系统里编辑,经常会造成文件里含有\r,导致在linux会显示^M,也就是回车符

可以对vscode的默认换行符进行设置:

打开VSCode菜单文件->首选项->设置:

在搜索框里输入eol

将默认行尾字符修改为\n