OpenResty body_filter_by_lua Nginx 반환 내용 지정
2316 단어 openresty
error 의 반환 을 통일 적 으로 처리 해 야 합 니 다. 사실은 nginx 의 기본 error 는 html 형식 이 고 우리 의 통일 규범 에 부합 되 지 않 기 때문에 마지막 에 획일 화 되 어야 합 니 다.물론 body 까지 연장 할 수 있 습 니 다.filter_by_lua 에서 반환 내용 을 수정 하고 반환 내용 을 지정 합 니 다.
원리 설명:
먼저 성명 이 필요 합 니 다!!HTTP 1.1 이후 스 트림 처리 방식, bodyfilter_by_lua 는 기본적으로 한 요청 에서 여러 번 호출 됩 니 다.간단 하고 직 설 적 인 이 해 는 스 트림 출력 입 니 다. 매번 받 을 때마다 처리 하려 면 처리 하고 처리 하지 않 으 면 출력 합 니 다!!
git 소스 코드 링크 body_filter_by_lua
The input data chunk is passed via ngx.arg[1] (as a Lua string value) and the "eof" flag indicating the end of the response body data stream is passed via ngx.arg[2] (as a Lua boolean value).
간단 한 설명 은
매번 흐 르 는 내용 출력 은 ngx. arg [1] 가운데eof 에 도착 할 지 여부 - 마지막 표 시 는 ngx. arg [2] 에 있 습 니 다.
그래서 출력 내용 을 바 꾸 려 면 ngx. arg [1] 을... 고 쳐, 앞으로 의 내용 을 원 하지 않 는 다 면 ngx. arg [2] = true 면 돼.
코드: bodyfilter.lua
---
--- Created by sunfangyuan.
--- DateTime: 18/1/31 9:53
---
local headers = ngx.header
local constant = require("conf.constant")
local log = ngx.log
local ERR = ngx.ERR
local json_util = require("cjosn")
local function res_json()
local res = {}
res["message"] = " "
res["code"] = " "
return json_util.encode(res)
end
if headers["Content-Type"] == nil or string.find(headers["Content-Type"], "application/json") == nil then
local status = ngx.var.status
headers["Content-Type"] = "application/json"
local chunk, eof = ngx.arg[1], ngx.arg[2] --
local info = ngx.ctx.buf
chunk = chunk or ""
if info then
ngx.ctx.buf = info .. chunk --
else
ngx.ctx.buf = chunk
end
if eof then
ngx.ctx.buffered = nil
if status == 413 or status == "413" then -- 413 nginx request body
ngx.arg[1] = res_json() --
else
log(ERR, "[ Internal Exception ] " .. ngx.ctx.buf)
ngx.arg[1] = res_json()
end
else
ngx.arg[1] = nil --
end
end
body 내용 길이 가 바 뀌 었 기 때문에 header 의 길 이 를 업데이트 하 는 것 을 기억 하 세 요.
ngx.header.content_length = nil
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
openresty 소스 분석 - 루아 코드의 실행accessby_lua content_by_lua 등 단계에서 Openresty에서 새로운 협정을 만듭니다.luaresume 실행 루아 코드 content_by_**단계에 대응하는 요청이 오면 실행 절차는ngxht...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.