illidan33 commented on issue #10915:
URL: https://github.com/apache/apisix/issues/10915#issuecomment-1929846363

   > > You can change the status of response in the `header_filter` phase. like 
this: `ngx.header.content_length = #your body's length` 
`ngx.header.content_encoding = nil ` `ngx.status = 400` `header_filter` must 
work with `body_filter` when you want to modify both header and body. It worked 
for me.
   > 
   > I can change the response status only in the `header_filter` phase, but I 
want to change the status only when the response body is invalid. The following 
situation arises: In the `header_filter` phase, we can change the status of the 
response, but we cannot read and validate the response body and set the status 
based on the validation. In the `body_filter` phase, we can read and validate 
the response body, but we cannot change the response status.
   
   ```
   function _M.access(conf, ctx)
       local body = ngx.req.get_body_data()
       core.log.info("example2 access phase, get_body_data: ", body)
       if string.find(body, "test") then
           core.log.info("example2 access phase, set filter_flag true")
           ctx.filter_flag = true
       else
           ctx.filter_flag = false
       end
   end
   
   function _M.header_filter(conf, ctx)
       core.log.info("example2 header_filter phase, ctx filter_flag: ", 
ctx.filter_flag)
       if ctx.filter_flag then
           ngx.status = 401
       end
   end
   ```
   
   Part of the log after I run it is here:
   > 2024/02/06 14:08:06 [info] 75#75: *610 [lua] example-plugin2.lua:63: 
phase_func(): example2 access phase, get_body_data: {"test":"test"}
   > 2024/02/06 14:08:06 [info] 75#75: *610 [lua] example-plugin2.lua:65: 
phase_func(): example2 access phase, set filter_flag true
   > 2024/02/06 14:08:06 [info] 75#75: *610 [lua] example-plugin2.lua:73: 
phase_func(): example2 header_filter phase, ctx filter_flag: true while reading 
response header from upstream
   
   curl log:
   > curl -sL  -w   "http_code:%{http_code} content_type:%{content_type}"  -o 
/dev/null  --request POST 'http://xxxxxxx' -d '{"test":"test"}'
   > http_code:401 content_type:application/json; charset=utf-8%
   
   In the access phase, the body is read and the flag is set. In the 
header_filter phase, the response status can be set according to the flag.
   Is that ok for you?
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to