6.4.2 配置项和上下文
首先希望在nginx.conf中有一个控制当前HTTP过滤模块是否生效的配置项,它的参数值为on或者off,分别表示开启或者关闭。因此,按照第4章介绍的用法,需要建立ngx_http_myfilter_conf_t结构体来存储配置项,其中使用ngx_flag_t类型的enable变量来存储这个参数值,如下所示:
typedef struct{
ngx_flag_t enable;
}ngx_http_myfilter_conf_t;
同样,下面实现的ngx_http_myfilter_create_conf用于分配存储配置项的结构体ngx_http_myfilter_conf_t:
static voidngx_http_myfilter_create_conf(ngx_conf_tcf)
{
ngx_http_myfilter_conf_t*mycf;
//创建存储配置项的结构体
mycf=(ngx_http_myfilter_conf_t*)ngx_pcalloc(cf->pool,sizeof(ngx_http_myfilter_conf_t));
if(mycf==NULL){
return NULL;
}
//ngx_flat_t类型的变量。如果使用预设函数ngx_conf_set_flag_slot解析配置项参数,那么必须初始化为NGX_CONF_UNSET
mycf->enable=NGX_CONF_UNSET;
return mycf;
}
就像gzip等其他HTTP过滤模块的配置项一样,我们往往会允许配置项不只出现在location{……}配置块中,还可以出现在server{……}或者http{……}配置块中,因此,还需要实现一个配置项值的合并方法——ngx_http_myfilter_merge_conf,代码如下所示:
static char*
ngx_http_myfilter_merge_conf(ngx_conf_tcf,voidparent,void*child)
{
ngx_http_myfilter_conf_tprev=(ngx_http_myfilter_conf_t)parent;
ngx_http_myfilter_conf_tconf=(ngx_http_myfilter_conf_t)child;
//合并ngx_flat_t类型的配置项enable
ngx_conf_merge_value(conf->enable,prev->enable,0);
return NGX_CONF_OK;
}
根据6.4.3节中介绍的配置项名称可知,在nginx.conf配置文件中需要有"add_prefix on;"字样的配置项。
再建立一个HTTP上下文结构体ngx_http_myfilter_ctx_t,其中包括add_prefix整型成员,在处理HTTP头部时用这个add_prefix表示在处理HTTP包体时是否添加前缀。
typedef struct{
ngx_int_t add_prefix;
}ngx_http_myfilter_ctx_t;
当add_prefix为0时,表示不需要在返回的包体前加前缀;当add_prefix为1时,表示应当在包体前加前缀;当add_prefix为2时,表示已经添加过前缀了。为什么add_prefix有3个值呢?因为HTTP头部处理方法在1个请求中只会被调用1次,但包体处理方法在1个请求中是有可能被多次调用的,而实际上我们只希望在包头加1次前缀,因此add_prefix制定了3个值。