openrestry基本语法
日志输出:
ngx.log(log_level, ...)
有关 Nginx 的日志级别,请看下表:
ngx.STDERR -- 标准输出
ngx.EMERG -- 紧急报错
ngx.ALERT -- 报警
ngx.CRIT -- 严重,系统故障,触发运维告警系统
ngx.ERR -- 错误,业务不可恢复性错误
ngx.WARN -- 告警,业务中可忽略错误
ngx.NOTICE -- 提醒,业务比较重要信息
ngx.INFO -- 信息,业务琐碎日志信息,包含不同情况判断等
ngx.DEBUG -- 调试
案例:
local num = 55
local str = "string"
ngx.log(ngx.ERR, "num:", num)
ngx.log(ngx.INFO, " string:", str)
合并请求:
ngx.location.capture(uri):单个请求,默认请求方式是get
ngx.location.capture_multi({uri1,uri2,...}):多个请求
请求头:
local headers = ngx.req.get_headers()
获取请求参数:
获取get请求:local uri_args = ngx.req.get_uri_args() 返回的是一个table类型的数据结构。
获取post请求:ngx.req.read_body();local post_args = ngx.req.get_post_args() 返回结果是一个table类型的数据。
请求的body内容体:
ngx.req.get_body_data()
获取请求方法:
local method=ngx.var.request_method 则method==‘GET’ 或者‘POST’
重定向:
ngx.redirect:重定向
ngx.status:状态码,设置响应的状态码
ngx.resp.get_headers():获取设置的响应状态码
ngx.send_headers():发送响应状态码,当调用ngx.say/ngx.print时自动发送响应状态码;可以通过
ngx.headers_sent=true:判断是否发送了响应状态码
lua_cjson模块
Json是一种常见的数据交换格式,常用于http通信协议和其他数据传输领域。在openresty默认内嵌了lua_cjson模块,用来序列化数据。
它常用的API如下:
- local cjson = require “cjson” 获取一个cjson对象
- local str = cjson.encode(obj) obj转换成string
- local obj = cjson.decode(str) 将string转obj
测试json库:
local cjson = require("cjson")
function open1()
--lua对象到字符串
local obj = {
id = 1,
name = "zhangsan",
age = nil,
is_male = false,
hobby = {"film", "music", "read"}
}
local str = cjson.encode(obj)
ngx.say("lua对象到字符串:",str)
ngx.say("--------------------------------");
--字符串到lua对象
str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'
local obj = cjson.decode(str)
ngx.say("字符串到lua对象:")
ngx.say("obj.age ",obj.age)
ngx.say("obj.age == nil ",obj.age == nil)
ngx.say("obj.age == cjson.null ",obj.age == cjson.null)
ngx.say("obj.hobby[1] ",obj.hobby[1])
end
输出结果:
lua对象到字符串:{"is_male":false,"name":"zhangsan","hobby":["film","music","read"],"id":1}
--------------------------------
字符串到lua对象:
obj.age null
obj.age == nil false
obj.age == cjson.null true
obj.hobby[1] film
测试:get请求
function open2(ngxObj)
local uri_args = ngxObj.req.get_uri_args();
local storeCode = uri_args["storeCode"] or "";
local supplierCode = uri_args["supplierCode"] or "";
local cityCode = uri_args["cityCode"] or 025;
ngx.say("----------获取get请求:req.get_uri_args()-------------");
ngx.say("storeCode:",storeCode);
ngx.say("supplierCode:",supplierCode);
ngx.say("cityCode:",cityCode);
end
输出结果:
----------获取get请求:req.get_uri_args()-------------
storeCode:5263
supplierCode:0000000
cityCode:025
获取请求头:
function open3(ngxObj)
local headers = ngxObj.req.get_headers()
ngx.say("获取请求头: req.get_headers():");
ngx.say("Host : ", headers["Host"])
ngx.say("user-agent : ", headers["user-agent"])
ngx.say("user-agent : ", headers.user_agent)
for k,v in pairs(headers) do
if type(v) == "table" then
ngx.say(k, " : ", table.concat(v, ","))
else
ngx.say(k, " : ", v)
end
end
end
输出结果:
获取请求头: req.get_headers():
Host : localhost
user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
host : localhost
connection : keep-alive
sec-fetch-site : none
upgrade-insecure-requests : 1
cache-control : max-age=0
sec-fetch-mode : navigate
accept-encoding : gzip, deflate, br
user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
accept-language : zh-CN,zh;q=0.9
accept : text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
sec-fetch-user : ?1
测试post请求:
function open4(ngxObj)
--获取请求方法
local method=ngxObj.var.request_method
ngx.say("method:",method);
--读取post参数.表单需要是x-www-form-urlencoded格式
-- 解析body参数之前一定要先读取body
ngx.req.read_body()
local arg = ngx.req.get_post_args()
for k,v in pairs(arg) do
ngx.say("[POST] key:", k, " v:", v)
end
end
postman测试结果: