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

좋은 웹페이지 즐겨찾기