解剖Nginx·模块开发篇(2)ngx_http_hello_world_module 基本结构定义
- 作者:柳大·Poechant(钟超)
- 邮箱:zhongchao.ustc#gmail.com(# -> @)
- 博客:Blog.CSDN.net/Poechant
- 日期:June 2nd, 2012
HelloWorld 是一个典型的 location 模块。什么是 location 模块?在 Nginx 中,根据作用域,有 main 模块、server 模块、location 模块。
1 模块定义
在 HelloWorld 模块中有一个 ngx_http_hello_world_module 变量,用于定义模块。它是 ngx_module_t 类型。ngx_module_t 是 ngx_module_s 的别名,其定义如下:
struct ngx_module_s {
ngx_uint_t ctx_index;
ngx_uint_t index;
ngx_uint_t spare0;
ngx_uint_t spare1;
ngx_uint_t spare2;
ngx_uint_t spare3;
ngx_uint_t version; // Nginx模块版本
void *ctx; // 上下文定义的地址
ngx_command_t *commands; // 命令定义地址
ngx_uint_t type; // 模块类型
ngx_int_t (*init_master)(ngx_log_t *log); // 初始化 master 时执行
ngx_int_t (*init_module)(ngx_cycle_t *cycle); // 初始化模块时执行
ngx_int_t (*init_process)(ngx_cycle_t *cycle); // 初始化进程时执行
ngx_int_t (*init_thread)(ngx_cycle_t *cycle); // 初始化线程时执行
void (*exit_thread)(ngx_cycle_t *cycle); // 退出线程时执行
void (*exit_process)(ngx_cycle_t *cycle); // 退出进程时执行
void (*exit_master)(ngx_cycle_t *cycle); // 退出 master 时执行
uintptr_t spare_hook0;
uintptr_t spare_hook1;
uintptr_t spare_hook2;
uintptr_t spare_hook3;
uintptr_t spare_hook4;
uintptr_t spare_hook5;
uintptr_t spare_hook6;
uintptr_t spare_hook7;
};
在 HelloWorld 例子中:
// Structure for the HelloWorld module, the most important thing
ngx_module_t ngx_http_hello_world_module = {
NGX_MODULE_V1,
&ngx_http_hello_world_module_ctx,
ngx_http_hello_world_commands,
NGX_HTTP_MODULE,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NGX_MODULE_V1_PADDING
};
1.1 NGX_MODULE_V1
看它的定义你就知道,它是用来填充前 7 个 fields 的。
NGX_MODULE_V1 0, 0, 0, 0, 0, 0, 1
1.2 模块类型
我们的模块是 HTTP 模块,还可以开发 CORE 模块,或者 CONF 模块等等。