Christian-health / nginx-lua

nginx-lua并发实战
0 stars 0 forks source link

lua的好的博客 里面的教程很好 #4

Open Christian-health opened 5 years ago

Christian-health commented 5 years ago

https://jkzhao.github.io/2018/05/03/Lua-OpenResty%E4%BF%AE%E6%94%B9response-body/

Christian-health commented 5 years ago

image

Christian-health commented 5 years ago
-- body_filter_by_lua, body filter模块,ngx.arg[1]代表输入的chunk,ngx.arg[2]代表当前chunk是否为last
local chunk, eof = ngx.arg[1], ngx.arg[2]
local buffered = ngx.ctx.buffered
if not buffered then
   buffered = {}  -- XXX we can use table.new here 
   ngx.ctx.buffered = buffered
end
if chunk ~= "" then
   buffered[#buffered + 1] = chunk
   ngx.arg[1] = nil
end
if eof then
   local whole = table.concat(buffered)
   ngx.ctx.buffered = nil
   -- try to unzip
   -- local status, debody = pcall(com.decode, whole) 
   -- if status then whole = debody end
   -- try to add or replace response body
   -- local js_code = ...
   -- whole = whole .. js_code
   whole = string.gsub(whole, "max%-width%:1632px%;",  "")
   ngx.arg[1] = whole
Christian-health commented 5 years ago

When the Lua code may change the length of the response body,
 then it is required to always clear out the Content-Length response header (if any) 
in a header filter to enforce streaming output, as i
--
Christian-health commented 5 years ago
ngx.req.read_body()
local data = ngx.req.get_body_data()
local args = ngx.req.get_uri_args()
local res = ngx.location.capture("/bh-scenes-1.2.min.css", {method = ngx.HTTP_GET, body=data, args=args})
res.body = string.gsub(res.body, "max%-width%:1632px%;", "")
ngx.say(res.body)