Nginx服务器中的模块编写及相关内核源码初探

2019-10-17 19:58:56刘景俊

d、下载nginx源码包,我下载的是nginx-1.0.13.tar.gz
这里注意在编译helloworld模块前首先确认,nginx是否可以独立编译成功,是否安装了所需的所有模块。
与helloworld模块一起编译nginx:

./configure --prefix=/usr/local/nginx --add-module=/opt/nginx_hello_world/ 
make 
make install 

e、配置nginx.conf

location= /hello { 
 hello_world; 
} 

f、启动nginx,访问http://localhost/hello ,可以看到编写的helloworld模块输出的文字。
 
3.hello world模块分析
a.ngx_command_t函数用于定义包含模块指令的静态数组ngx_http_hello_world_commands

static ngx_command_t ngx_http_hello_world_commands[] = { 
 { ngx_string("hello_world"), //设置指令名称字符串,注意不能包含空格,数据类型ngx_str_t之后会详细讲解。 
  NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS, //配置指令的合法位置,这里表示:location部分合法,并且指令没有参数。 
  ngx_http_hello_world,//回调函数,三个参数(ngx_conf_t *cf,ngx_command_t *cmd, void *conf) 
  0,//后面的参数有待发掘,我还没有用到 
  0, 
  NULL }, 
 ngx_null_command 
}; 

b.static u_char ngx_hello_world[] ="hello world" 则是输出到屏幕的字符串。
c.ngx_http_module_t用来定义结构体ngx_http_hello_world_module_ctx:

static ngx_http_module_t ngx_http_hello_world_module_ctx = { 
 NULL,         /* 读入配置前调用*/ 
 NULL,          /* 读入配置后调用*/ 
 NULL,         /* 创建全局部分配置时调用 */ 
 NULL,         /* 初始化全局部分的配置时调用*/ 
 NULL,         /* 创建虚拟主机部分的配置时调用*/ 
 NULL,         /* 与全局部分配置合并时调用 */ 
 NULL,         /* 创建位置部分的配置时调用 */ 
 NULL         /* 与主机部分配置合并时调用*/ 
}; 

d.ngx_module_t定义结构体ngx_http_hello_world_module

ngx_module_t ngx_http_hello_world_module = { 
 NGX_MODULE_V1, 
 &ngx_http_hello_world_module_ctx,    /* module context */ 
 ngx_http_hello_world_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 
}; 

e.处理函数,ngx_http_hello_world_handler,也是hello world 模块的核心部分。

static ngx_int_t 
ngx_http_hello_world_handler(ngx_http_request_t *r)//ngx_http_request_t *r 
//可以访问到客户端的头部和不久要发送的回复头部 
{ 
 ngx_int_t  rc; 
 ngx_buf_t *b; 
 ngx_chain_t out; 
 /* Http Output Buffer */ 
 r->headers_out.content_type.len = sizeof("text/plain") - 1; 
 r->headers_out.content_type.data = (u_char *) "text/plain"; 
  
 b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); 
  
 out.buf = b; 
 out.next = NULL; 
  
 b->pos = ngx_hello_world; 
 b->last = ngx_hello_world + sizeof(ngx_hello_world); 
 b->memory = 1; 
 b->last_buf = 1; 
  
 r->headers_out.status = NGX_HTTP_OK; 
 r->headers_out.content_length_n = sizeof(ngx_hello_world); 
 ngx_http_send_header(r); 
  
 return ngx_http_output_filter(r, &out); 
}