openresty使用lua获取post的请求头
日志格式
log_format main '{"@timestamp":"$time_iso8601",' '"createtime":"$time_iso8601",' '"host":"$hostname",' '"server_ip":"$server_addr",' '"client_ip":"$remote_addr",' '"xff":"$http_x_forwarded_for",' '"domain":"$host",' '"url":"$uri",' '"referer":"$http_referer",' '"args":"$args",' '"upstreamtime":"$upstream_response_time",' '"responsetime":"$request_time",' '"request_method":"$request_method",' '"status":"$status",' '"size":"$body_bytes_sent",' '"request_length":"$request_length",' '"protocol":"$server_protocol",' '"upstreamhost":"$upstream_addr",' '"file_dir":"$request_filename",' '"request_body":"$request_body",' '"http_user_agent":"$http_user_agent"}';
nginx的配置
location / { default_type text/html; content_by_lua_file /usr/local/openresty/nginx/lua/test.lua; }
vim /usr/local/openresty/nginx/lua/test.lua
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) ngx.say("<br>") end -- 获取body信息 ngx.req.read_body() --解析 body参数之前先获取body local data = ngx.req.get_body_data() ngx.say(data) if data then --使用ngx.log记录数据,注意日志级别 ngx.log(ngx.ERR,"Received body data: ", data) 写入error.log else --如果没有获取到数据,可以记录相关信息 ngx.log(ngx.ERR,"No body data received") end
操作redis
local redis = require "resty.redis" local red = redis:new() red:set_timeouts(1000, 1000, 1000) -- 1 sec //连接redis ip 和端口号 local ok, err = red:connect("192.168.47.128", 6379) // 没有成功 if not ok then ngx.say("not success", err) return end -- 认证登陆问题 --[[ local count count,err = red.get_reused_times() if 0 == count then ok,err = red:auth("") if not ok then ngx.say("failed to auth:",err) return end elseif err then ngx.say("failed to gt resued times :",err) return end --]] //成功开始进行存储cc ok, err = red:set("cc", "tiantain") if not ok then ngx.say("error", err) return end //打印成功 ngx.say("set result: ", ok) //获取cc信息 local res, err = red:get("cc") if not res then ngx.say("success", err) return end if res == ngx.null then ngx.say("not found") return end ngx.say("成功", res) local results, err = red:commit_pipeline() if not results then ngx.say("failed to commit the pipelined requests: ", err) return end for i, res in ipairs(results) do if type(res) == "table" then if res[1] == false then ngx.say("failed to run command ", i, ": ", res[2]) else -- process the table value end else -- process the scalar value end end -- put it into the connection pool of size 100, -- with 10 seconds max idle time local ok, err = red:set_keepalive(10000, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end -- or just close the connection right away: local ok, err = red:close() if not ok then ngx.say("failed to close: ", err) return
end

浙公网安备 33010602011771号