nginx http handler 過程

一直容易忘記的httphandle處理過程

ngx_http_handler 起步

void
ngx_http_core_run_phases(ngx_http_request_t *r) //循環處理函數
{
    ngx_int_t                   rc;
    ngx_http_phase_handler_t   *ph;
    ngx_http_core_main_conf_t  *cmcf;

    cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module);

    ph = cmcf->phase_engine.handlers;

    while (ph[r->phase_handler].checker) {

        rc = ph[r->phase_handler].checker(r, &ph[r->phase_handler]);

        if (rc == NGX_OK) {
            return;
        }
    }
}

上面代碼涉及到cmcf->phase_engine.handlers ,先看一下ngx_http_phase_handler_t 的結構

struct ngx_http_phase_handler_s {
    ngx_http_phase_handler_pt  checker; //階段性 處理函數
    ngx_http_handler_pt        handler; //真實處理函數
    ngx_uint_t                 next; //鏈表結構
};

接下來是模塊的處理函數,push到cmcf->phases[各個階段] 的數組中(以gzip爲例子):

static ngx_int_t
ngx_http_gzip_static_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt        *h;
    ngx_http_core_main_conf_t  *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_gzip_static_handler;

    return NGX_OK;
}

接下來就是在每個handler函數中去處理,結束返回ngx_OK,想執行下一個返回ngx_again

if (gzcf->enable == NGX_HTTP_GZIP_STATIC_OFF) { //config 是否配置
        return NGX_DECLINED;
    }

    if (gzcf->enable == NGX_HTTP_GZIP_STATIC_ON) { 
        rc = ngx_http_gzip_ok(r);

    } else {
        /* always */
        rc = NGX_OK;
    }

關於NGX_HTTP_CONTENT_PHASE 階段還有一個單獨的優先級非常高的處理函數

ngx_int_t
ngx_http_core_content_phase(ngx_http_request_t *r,
    ngx_http_phase_handler_t *ph){
    ....    
 if (r->content_handler) {
        r->write_event_handler = ngx_http_request_empty_handler; 
        ngx_http_finalize_request(r, r->content_handler(r));//clcf->handler postconfiguration中初始化的優先級高
        return NGX_OK;
    }
    rc = ph->handler(r); // array 中的處理函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章