6.4.3 定义HTTP过滤模块
定义ngx_module_t模块前,需要先定义好它的两个关键成员:ngx_command_t类型的commands数组和ngx_http_module_t类型的ctx成员。
下面定义了ngx_http_myfilter_commands数组,它会处理add_prefix配置项,将配置项参数解析到ngx_http_myfilter_conf_t上下文结构体的enable成员中。
static ngx_command_t ngx_http_myfilter_commands[]={
{ngx_string("add_prefix"),
NGXHTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP
LMT_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_myfilter_conf_t,enable),
NULL},
ngx_null_command
};
在定义ngx_http_module_t类型的ngx_http_myfilter_module_ctx时,需要将6.4.2节中定义的ngx_http_myfilter_create_conf回调方法放到create_loc_conf成员中,而ngx_http_myfilter_merge_conf回调方法则要放到merge_loc_conf成员中。另外,在6.4.4节中定义的ngx_http_myfilter_init模块初始化方法也要放到postconfiguration成员中,表示当读取完所有的配置项后就会回调ngx_http_myfilter_init方法,代码如下所示:
static ngx_http_module_t ngx_http_myfilter_module_ctx={
NULL,
/preconfiguration方法/
ngx_http_myfilter_init,
/postconfiguration方法/
NULL,
/create_main_conf方法/
NULL,
/init_main_conf方法/
NULL,
/create_srv_conf方法/
NULL,
/merge_srv_conf方法/
ngx_http_myfilter_create_conf,/create_loc_conf方法/
ngx_http_myfilter_merge_conf/merge_loc_conf方法/
};
有了ngx_command_t类型的commands数组和ngx_http_module_t类型的ctx成员后,下面就可以定义ngx_http_myfilter_module过滤模块了。
ngx_module_t ngx_http_myfilter_module={
NGX_MODULE_V1,
&ngx_http_myfilter_module_ctx,
/module context/
ngx_http_myfilter_commands,
/module directives/
NGX_HTTP_MODULE,
/module type/
NULL,
/init master/
NULL,
/init module/
NULL,
/init process/
NULL,
/init thread/
NULL,
/exit thread/
NULL,
/exit process/
NULL,
/exit master/
NGX_MODULE_V1_PADDING
};
它的类型仍然是NGX_HTTP_MODULE。