5.4.2 实现子请求处理完毕时的回调方法

Nginx在子请求正常或者异常结束时,都会调用ngx_http_post_subrequest_pt回调方法,如下所示。


typedef ngx_int_t(ngx_http_post_subrequest_pt)(ngx_http_request_tr,void*data,ngx_int_t rc);


如何把这个回调方法传递给subrequest子请求呢?要建立ngx_http_post_subrequest_t结构体:


typedef struct{

ngx_http_post_subrequest_pt

handler;

void*data;

}ngx_http_post_subrequest_t;


在生成ngx_http_post_subrequest_t结构体时,可以把任意数据赋给这里的data指针,ngx_http_post_subrequest_pt回调方法执行时的data参数就是ngx_http_post_subrequest_t结构体中的data成员指针。

ngx_http_post_subrequest_pt回调方法中的rc参数是子请求在结束时的状态,它的取值则是执行ngx_http_finalize_request销毁请求时传递的rc参数(对于本例来说,由于子请求使用反向代理模块访问上游HTTP服务器,所以rc此时是HTTP响应码。例如,在正常情况下,rc会是200)。相应源代码如下:


void

ngx_http_finalize_request(ngx_http_request_t*r,ngx_int_t rc)

{

……

//如果当前请求属于某个原始请求的子请求

if(r!=r->main&&r->post_subrequest){

rc=r->post_subrequest->handler(r,r->post_subrequest->data,rc);

}

……


上面代码中的r变量是子请求(不是父请求)。

在ngx_http_post_subrequest_pt回调方法内必须设置父请求激活后的处理方法,设置的方法很简单,首先要找出父请求,例如:


ngx_http_request_t

*pr=r->parent;


然后将实现好的ngx_http_event_handler_pt回调方法赋给父请求的write_event_handler指针(为什么设置write_event_handler?因为父请求正处于等待发送响应的阶段,详见11.7节),例如:


pr->write_event_handler=mytest_post_handler;


mytest_post_handler就是5.6.4节中实现的父请求重新激活后的回调方法。

在5.6.3节中可以看到相关的具体例子。