ngx_http_output_filter
1 定义1 位置ngx_http_output_filter 函数 定义在 ./nginx-1.24.0/src/http/ngx_http_core_module.c2 源码ngx_int_tngx_http_output_filter(ngx_http_request_t*r,ngx_chain_t*in){ngx_int_trc;ngx_connection_t*c;cr-connection;ngx_log_debug2(NGX_LOG_DEBUG_HTTP,c-log,0,http output filter \%V?%V\,r-uri,r-args);rcngx_http_top_body_filter(r,in);if(rcNGX_ERROR){/* NGX_ERROR may be returned by any filter */c-error1;}returnrc;}2 目的1 设计意图ngx_http_output_filter是 Nginx HTTP 处理流程中响应体输出阶段的统一入口函数。它不直接执行任何实际的数据写入操作而是将输出请求委托给 Body Filter 链ngx_http_top_body_filter由链上的各个过滤器模块按序处理。其核心设计目的在于解耦调用方与过滤器链各个内容处理模块如ngx_http_static_module、ngx_http_proxy_module只需调用此函数传递缓冲区链无需关心具体的过滤器链结构。响应输出流的序列化保证所有响应体数据都经过相同顺序的过滤器管道维持响应数据的一致性。2 职责边界职责范围内职责范围外作为 Body Filter 链的唯一公共入口不直接读写套接字由 Filter 链尾的ngx_http_write_filter处理统一捕获NGX_ERROR并设置c-error不参与缓冲区构造、数据变换、编码等工作将缓冲区链ngx_chain_t交付给过滤器链不管理过滤器的生命周期或注册顺序提供调试日志记录不处理头部过滤那是ngx_http_send_header的职责3 详解1 函数签名ngx_int_tngx_http_output_filter(ngx_http_request_t*r,ngx_chain_t*in)1 返回值ngx_int_t用于表示执行状态返回值含义NGX_OK(0)处理成功NGX_AGAIN(-2)暂时无法处理需等待事件重试NGX_ERROR(-1)处理失败NGX_DECLINED(-5)拒绝处理2 函数名ngx_http_output_filter词段含义ngx_Nginx 核心命名空间前缀http_归属于 HTTP 子系统output_输出方向区别于input/request_body方向的过滤器filter表明此函数是过滤器链的统一入口3 参数列表参数类型含义来源约束rngx_http_request_t *当前 HTTP 请求对象由请求处理流程传递非空r-connection必须有效inngx_chain_t *待输出的缓冲区链可能为 NULL响应数据构造完成后传入链表以next NULL结尾可以为NULL此时仅触发 flush2 逻辑流程ngx_http_output_filter(r, in) ├─ [1] 获取连接对象 │ └─ c r-connection ├─ [2] 调试日志记录 │ └─ 记录 http output filter 请求 URI 和参数 ├─ [3] 委托给 Body Filter 链 │ └─ rc ngx_http_top_body_filter(r, in) ├─ [4] 错误处理 │ ├─ if (rc NGX_ERROR) → c-error 1 │ └─ (其他返回值不操作) └─ [5] 返回 rc{ngx_int_trc;ngx_connection_t*c;1 获取连接对象cr-connection;2 调试日志记录ngx_log_debug2(NGX_LOG_DEBUG_HTTP,c-log,0,http output filter \%V?%V\,r-uri,r-args);3 委托给 Body Filter 链rcngx_http_top_body_filter(r,in);4 错误处理if(rcNGX_ERROR){/* NGX_ERROR may be returned by any filter */c-error1;}5 返回returnrc;}