天天看點

nginx的HTTP子產品編寫開發HTTP子產品流程對應的各個步驟說明:一個具體的例子:

本文是學習《深入了解nginx -- 子產品開發與架構解析》的讀書筆記

nginx的子產品分為4個大類型的子產品:

事件子產品

http子產品

郵件代理相關的mail子產品

其他子產品

這裡的http子產品是最簡單最經常編寫的子產品,開發一個完整的簡單的http子產品需要下面幾個步驟(以子產品名為ngx_http_mytest_module為例):

下面是編寫具體的子產品代碼結構

這個是子產品結構,其中起的作用是:

定義了子產品的上下文結構

定義了子產品指令結構

這個結構的意思就是nginx在觸發了子產品運作的時候,如何處理已經在其他http,server,location定義過的上下文

這個結構的意思就是nginx在配置檔案中觸發了哪些指令,其中指定了:

觸發指令的回調函數

這個回調函數中可以設定對http請求的具體處理方法

這個方法的參數中可以擷取http請求結構,并且可以設定http傳回

至此,一個http子產品就可以完成了。

示例:

ngx_addon_name=ngx_http_mytest_module 

http_modules="httpmodulesngxhttpmytestmodule"ngxaddonsrcs="httpmodulesngxhttpmytestmodule"ngxaddonsrcs="ngx_addon_srcs $ngx_addon_dir/ngx_http_mytest_module.c"

http_modules是設定http需要加載的子產品清單,在具體編譯的時候會生成modules的數組,然後根據數組的先後順序一個一個加載

它的結構說明看:

<a href="https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/core/ngx_conf_file.h">https://github.com/jianfengye/nginx-1.0.14_comment/blob/master/src/core/ngx_conf_file.h</a>

裡面的ngx_module_s的結構

最主要記得是要設定上下文結構ctx和指令集commands

這個結構是如果需要的話在讀取,重載配置檔案的時候定義的8個階段

create_main_conf 

create_srv_conf 

create_loc_conf 

preconfiguration 

init_main_conf 

merge_srv_conf 

merge_loc_conf 

postconfiguration

ngx_command_s的結構說明看:

裡面碰到的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

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/myworks/tree/master/nginx_module_mytest

繼續閱讀