5.6.4 父请求的回调方法
将父请求的回调方法定义为mytest_post_handler,如下所示:
static void
mytest_post_handler(ngx_http_request_t*r)
{
//如果没有返回200,则直接把错误码发回用户
if(r->headers_out.status!=NGX_HTTP_OK)
{
ngx_http_finalize_request(r,r->headers_out.status);
return;
}
//当前请求是父请求,直接取其上下文
ngx_http_mytest_ctx_t*myctx=ngx_http_get_module_ctx(r,ngx_http_mytest_module);
/定义发给用户的HTTP包体内容,格式为:stock[……],Today current price:……,volumn:……/
ngx_str_t output_format=ngx_string("stock[%V],Today current price:%V,volumn:%V");
//计算待发送包体的长度
int bodylen=output_format.len+myctx->stock[0].len
+myctx->stock[1].len+myctx->stock[4].len-6;
r->headers_out.content_length_n=bodylen;
//在内存池上分配内存以保存将要发送的包体
ngx_buf_t*b=ngx_create_temp_buf(r->pool,bodylen);
ngx_snprintf(b->pos,bodylen,(char*)output_format.data,
&myctx->stock[0],&myctx->stock[1],&myctx->stock[4]);
b->last=b->pos+bodylen;
b->last_buf=1;
ngx_chain_t out;
out.buf=b;
out.next=NULL;
//设置Content-Type,注意,在汉字编码方面,新浪服务器使用了GBK
static ngx_str_t type=ngx_string("text/plain;charset=GBK");
r->headers_out.content_type=type;
r->headers_out.status=NGX_HTTP_OK;
r->connection->buffered|=NGX_HTTP_WRITE_BUFFERED;
ngx_int_t ret=ngx_http_send_header(r);
ret=ngx_http_output_filter(r,&out);
/注意,这里发送完响应后必须手动调用ngx_http_finalize_request结束请求,因为这时HTTP框架不会再帮忙调用它/
ngx_http_finalize_request(r,ret);
}