參考 zlib 官方 API:deflateInit2。模塊分為頭部過濾器 ngx_http_gzip_header_filter 和主體過濾器 ngx_http_gzip_body_filter。
ctx,雙向關聯 request。gzip_buffers 設置 wbits、memlevel,計算需預分配內存大小 allocated。Content-Encoding: gzip。Content-Length(壓縮後大小未知)。ctx,將輸入鏈 in 的 buf 複製到 ctx->in(ngx_http_gzip_filter_buffer)。ngx_http_gzip_filter_deflate_start:分配 preallocated 空間,初始化 z_stream 結構(設置分配/釋放回調、輸入輸出緩衝區)。ngx_chain_add_copy 將 in 的 buf 掛入 ctx->in。ngx_http_gzip_filter_add_data:設置 zstream->next_in/avail_in,判斷是否為最後一個 buf(決定 flush 模式)。ngx_http_gzip_filter_get_buf:創建臨時輸出 buf(大小 conf->bufs.size),設置 zstream->next_out。ngx_http_gzip_filter_deflate:調用 deflate() 執行壓縮。add_data 處理剩餘輸入。ngx_http_next_body_filter(r, ctx->out) 將壓縮後的輸出鏈傳遞給下一個過濾器,實現輸出流重定向。ngx_http_gzip_ctx_t:保存 z_stream、輸入/輸出鏈、預分配內存指針、flush 模式、allocated 大小等。z_stream:zlib 核心結構,包含輸入輸出指針、可用空間、內存管理回調、壓縮狀態等。