|零基础开发 nginx 模块( 三 )
首先引入 nginx 头文件 , 声明模块入口 ngx_module_t 对象 , 变量名必须为 config 脚本中配置的模块名 , 本例中即为 ngx_http_hello_module。
#include
static ngx_http_module_t ngx_http_hello_module_ctx = { NULL,/* preconfiguration */ NULL,/* postconfiguration */ NULL,/* create main configuration */ NULL,/* init main configuration */ NULL,/* create server configuration */ NULL,/* merge server configuration */ NULL,/* create location configuration */ NULL/* merge location configuration */ };指令列表 ngx_command_t[] 设置为一个空列表 , 仅包含 ngx_null_command 结尾标记 。
static ngx_command_t ngx_http_hello_commands[] = { ngx_null_command };最后 , 定义模块入口对象 ngx_module_t。 开头私有字段使用 NGX_MODULE_V1 表示 , 结尾扩展备用字段使用 NGX_MODULE_V1_PADDING 表示 。 设置上述定义的 HTTP 模块信息 ngx_http_hello_module_ctx 和指令列表 ngx_http_hello_commands, 生命周期管理函数全部设置为 NULL。
ngx_module_t ngx_http_hello_module = { NGX_MODULE_V1, &ngx_http_hello_module_ctx,/* module context */ ngx_http_hello_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 };至此 , 一个空模块开发完成 。 这可以作为开发 HTTP 模块的初始模板 , 我们将在此基础上逐渐增加功能 。
在 nginx 代码仓库目录下执行 make modules, 即可重新编译生成动态模块文件 objs/ngx_http_hello_module.so。 因为我们没有修改模块配置 , 没有添加或删除源码文件 , 所以不需要重新执行 auto/configure 配置脚本 , 直接执行 make modules 即可 。
测试运行 nginx
在 nginx 代码仓库目录下新建一个测试配置文件 objs/nginx.conf, 内容如下:
# vim: set ft=nginx et: daemon off;# default on pid objs/nginx.pid; error_log stderr notice; load_module objs/ngx_http_hello_module.so; events { } http { access_log objs/access.log; server { listen 8080 default_server; return 200 ''testn''; } }
在 nginx 代码仓库目录下使用如下命令测试运行 nginx。
objs/nginx -p ''$PWD'' -c objs/nginx.conf
可看到 nginx 启动并打印日志 , 按 Ctrl+C 后 nginx 退出 。 此时我们的模块还是空模块 , 没有发挥任何作用 。
Nginx 配置指令 - 世界你好
当我们学习一种新的开发技术时 , 第一个程序通常是 ''hello world'': 打印一条 ''hello world'' 语句 , 向世界问声好 。 第一次接触 nginx 开发时 , 我们不得不花时间做一些准备工作 。 现在 , 终于是时候张开双臂 , 说一声 ''世界你好'' 了 。
推荐阅读
- |万向肖风:区块链的商业突破不是从 C 端开始,而是从开发者开始
- 华为开发者联盟|华为课堂|华为帐号如何保护您的帐号安全?
- 品谷农产品|专业的软件开发流程,应该是怎样的呢?
- AI人工智能|“眼健康黑科技” AI智能眼科检测仪来了!展锐虎贲T710开发板等你来盘!
- 智慧医疗|“眼健康黑科技” AI智能眼科检测仪来了!展锐虎贲T710开发板等你来盘!
- 智能电视|苹果正在开发带有A12x和A14x芯片的Apple TV
- IBM|百年IBM再度迎来历史性变革 拆分基础设施服务部门全力押宝云计算
- 互联网分析师于斌|鸿蒙搜索和EMUI11!华为开发者大会回顾
- cnBeta|前苹果工程师/自动修正创造者开发首款App:名为Up Spell的文字游戏
- 化学奖|女科学家获2020年诺贝尔化学奖,她们开发了“基因剪刀”
