本文是學習《深入理解nginx -- 模塊開發與架構解析》的讀書筆記
nginx的模塊分為4個大類型的模塊:
事件模塊
HTTP模塊
郵件代理相關的mail模塊
其他模塊
開發HTTP模塊流程
這里的HTTP模塊是最簡單最經常編寫的模塊,開發一個完整的簡單的HTTP模塊需要下面幾個步驟(以模塊名為ngx_http_mytest_module為例):
1 編寫config文件(這是為了讓nginx在configure過程能找到編寫的模塊)
下面是編寫具體的模塊代碼結構
2 編寫模塊結構 ngx_http_mytest_module
這個是模塊結構,其中起的作用是:
定義了模塊的上下文結構
定義了模塊命令結構
3 編寫模塊上下文結構 ngx_http_mytest_module_ctx
這個結構的意思就是nginx在觸發了模塊運行的時候,如何處理已經在其他http,server,location定義過的上下文
4 編寫模塊命令結構 ngx_http_mytest_commands
這個結構的意思就是nginx在配置文件中觸發了哪些命令,其中指定了:
觸發命令的回調函數
5 觸發命令的回調函數 ngx_http_mytest
這個回調函數中可以設置對http請求的具體處理方法
6 對http請求的具體處理方法 ngx_http_mytest_handler
這個方法的參數中可以獲取http請求結構,並且可以設置http返回
至此,一個http模塊就可以完成了。
對應的各個步驟說明:
1 編寫config文件
示例:
ngx_addon_name=ngx_http_mytest_module
HTTP_MODULES="$HTTP_MODULES ngx_http_mytest_module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_mytest_module.c"
HTTP_MODULES是設置HTTP需要加載的模塊列表,在具體編譯的時候會生成modules的數組,然后根據數組的先后順序一個一個加載
2 ngx_http_mytest_module的結構類型是ngx_module_t
它的結構說明看:
https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/core/ngx_conf_file.h
里面的ngx_module_s的結構
最主要記得是要設置上下文結構ctx和命令集commands
3 某塊上下文ngx_http_mytest_module_ctx的結構類型是ngx_http_module_t
它的結構說明看:
https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/http/ngx_http_config.h
這個結構是如果需要的話在讀取,重載配置文件的時候定義的8個階段
create_main_conf
create_srv_conf
create_loc_conf
preconfiguration
init_main_conf
merge_srv_conf
merge_loc_conf
postconfiguration
4 ngx_http_mytest_commands 是一個ngx_command_s的數組
ngx_command_s的結構說明看:
它的結構說明看:
https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/core/ngx_conf_file.h
里面碰到的set回調函數,這個回調函數可以使用nginx預設的14個解析配置方法,或者使用自定義的方法
14個預設的解析配置方法有:
ngx_conf_set_flag_slot
ngx_conf_set_str_slot
ngx_conf_set_str_array_slot
ngx_conf_set_keyval_slot
ngx_conf_set_num_slot
ngx_conf_set_size_slog
ngx_conf_set_off_slot
ngx_conf_set_msec_slot
ngx_conf_set_sec_slot
ngx_conf_set_bufs_slot
ngx_conf_set_enum_slot
ngx_conf_set_bitmask_slot
ngx_conf_set_acccess_slot
ngx_conf_set_path_slot
5 觸發命令的回調函數的解析配置方法格式如下:
char *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
如果使用了上面的14個解析配置方法,就可以不用自己寫這個方法了
如果是自己寫這個配置解析方法,就需要寫第六步
ngx_http_mytest_handler
它的函數定義如下:
static ngx_init_t ngx_http_mytest_handler(ngx_http_request_t *r)
使用ngx_http_request_t指針輸入
在ngx_http_request指針中也可以設置HTTP返回
它的結構說明看:
https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/http/ngx_http_request.h
一個具體的例子:
https://github.com/jianfengye/MyWorks/tree/master/nginx_module_mytest