HTTP模塊的調用
-
worker 進程會在一個for 循環里面反復調用事件模塊檢測網絡事件。
基本數據結構
- 對整形的封裝
ngx_int_t 封裝了有符號整形, 而 ngx_uint_t 封裝了無符號整形 - ngx_str_t
定義:
typedef struct {
size_t len;
u_char * data;
}ngx_str_t;
- ngx_list_t
鏈表容器,鏈表的元素是一個個數組
typedef struct ngx_list_part_s ngx_list_part_t;
struct ngx_list_part_s{
void * elts; // 指向數組的起始位置
ngx_unit_t nelts; // 標記數組中已經使用的容量
ngx_list_part_t * next;
};
typedef struct {
ngx_list_part_t * last; // 指向鏈表的最后一個數組的位置
ngx_list_part_t part; // 指向鏈表頭
size_t size; // 一個鏈表元素(ie, 數組節點)所包含的元素大小
ngx_uint_t nalloc; // 一個鏈表元素(ie, 數組節點)所包含的元素個數
ngx_pool_t * pool; // 內存池地址
}ngx_list_t;
其內存分布圖如下所示
ngx_table_elt_t
本質是一個鍵值對結構ngx_buf_t
, 是處理大數據的關鍵數據結構, 既應用于內存數據也應用于磁盤數據ngx_chain_t
一般與ngx_buf_t配合來使用,用來發送包體
將自己的HTTP模塊編譯到Nginx中
主要是配置好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模塊數據結構
- ngx_module_t:這個數據結構中, 我們最需要關注的是下面3個變量
ctx: 用于指向一類模塊的上下文結構體 (對于HTTP 模塊, ctx 指針必須指向 ngx_http_module_t 接口)
commands:,用于處理nginx.conf 文件中的配置項
type:用來表示模塊的類型(定義HTTP 模塊, 這個值應該設置為: NGX_HTTP_MODULE)
ngx_http_module_t接口
HTTP 框架在啟動的過程中會在每個階段中調用ngx_http_module_t 中相應的方法
commands 數組
用來定義模塊的配置文件參數, 數組中的每個元素都是 ngx_command_t 類型, 數組的結尾使用 ngx_null_command 來標記.
Nginx 解析配置文件的流程: 解析每個配置項的時候, 首先會遍歷所有的模塊,對于每個模塊而言, 通過遍歷commands 數組進行, 查找他所感興趣的配置項,個ngx_command_t 結構體定義了自己感興趣的一個配置項
定義一個Http模塊
這里有一個hello_world的例子
http://www.lxweimin.com/p/d7a783de09dd
處理用戶請求
在出現mytest 配置項的時候, ngx_http_mytest 方法被調用, 這時候, 將ngx_http_core_loc_conf_t 結構的handler 成員指定為ngx_http_mytest_handler。 在HTTP 框架接收完HTTP請求的頭部之后, 會調用handler指向的方法, 用來處理用戶請求。
- 處理方法的返回值
- 主要包含RFC 2616 規范中定義的返回碼, 以及Nginx 自身定義的HTTP返回碼
- 主要需要了解4個通用的返回碼:
- NGX_OK: 表示成功
- NGX_DECLINED: 繼續在NGX_HTTP_CONTENT_PHASE 階段, 尋找感興趣的HTTP 模塊來再次處理這個請求
- NGX_DONE: 表示到此為止, 同時HTTP 框架將暫時不再繼續執行這個請求的后續部分。事實上, 如果是keepalive類型的用戶請求, 就會保持這個http 連接, 然后把控制權返回給Nginx
- NGX_ERROR: 表示錯誤, 將終止請求
- 獲取URI 和 參數
- 請求的所有信息(方法, URI, 協議版本號和頭部等)都可以在傳入的ngx_http_request_t 類型的參數 r 中獲取。
- 可以通過r->method 這個整形成員與預定義的幾個宏進行比較, 從而獲取方法名
- URI, uri 成員指向用戶請求的 URI
- args, 指向用戶請求中的URI參數
- http_protocol 的data 成員指向用戶請求中HTTP 協議版本字符串的起始地址, len 成員為其字符串長度
- 獲取HTTP 頭部
- ngx_http_headers_in_t 類型的headers_in存儲已經解析過的HTTP 頭部
- 獲取HTTP 包體
- HTTP 包體的長度有可能非常大, 如果試圖一次性調用并讀完所有的包體, 可能導致nginx 的阻塞
- nginx 提供一個叫做 ngx_http_read_client_request_body的異步方法, 調用它只是說明要求Nginx開始連接請求的包體, 并不表示是否已經接收完畢。
- 如果 ngx_http_read_client_request_body是在ngx_http_mytest_handler處理方法中調用的話, 一般后者需要返回 NGX_DONE
- 而如果不想處理請求中的包體的時候, 可以調用 ngx_http_discard_request_body 方法將接收自客戶端的HTTP 包體丟棄掉
- 發送響應
- 使用api: ngx_http_send_header 即可發送響應
- 發送之前, 需要預先指定一下 headers_out 中的成員,如下
r->headers_out.status = NGX_HTTP_OK;
//響應包是有包體內容的,所以需要設置Content-Length長度
r->headers_out.content_length_n = response.len;
//設置Content-Type
r->headers_out.content_type = type;
- 將內存中的字符串作為包體發送
- 調用 ngx_http_output_filter 可以實現向客戶端發送HTTP 響應包體
- 發送的內容放在 ngx_buf_t 結構中, 并使用 ngx_chain_t 傳遞給 ngx_http_output_filter 方法,如下所示
//構造ngx_buf_t結構準備發送包體
ngx_buf_t *b;
b = ngx_create_temp_buf(r->pool, response.len);
if (b == NULL)
{
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
//將Hello World拷貝到ngx_buf_t指向的內存中
ngx_memcpy(b->pos, response.data, response.len);
//注意,一定要設置好last指針
b->last = b->pos + response.len;
//聲明這是最后一塊緩沖區
b->last_buf = 1;
//構造發送時的ngx_chain_t結構體
ngx_chain_t out;
//賦值ngx_buf_t
out.buf = b;
//設置next為NULL
out.next = NULL;
//最后一步發送包體,http框架會調用ngx_http_finalize_request方法
//結束請求
return ngx_http_output_filter(r, &out);
- 清理文件句柄
- nginx 通過異步方式將整個文件高效的發送給用戶, 但是需要在發送完畢之后, 關閉打開的文件句柄, 避免句柄泄露
- ngx_pool_cleanup_file 用于關閉文件句柄
-
ngx_pool_cleanup_t 結構
-
ngx_pool_cleanup_file_t 結構
- 使用ngx_pool_cleanup_add 添加, 并設置完上面兩個結構即可
- 支持用戶多線程下載和斷點續傳
r->allow_ranges = 1;
一個包含文件傳輸的代碼例子
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
static char *
ngx_http_mytest(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r);
static ngx_command_t ngx_http_mytest_commands[] =
{
{
ngx_string("mytest"),
NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_HTTP_LMT_CONF | NGX_CONF_NOARGS,
ngx_http_mytest,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL
},
ngx_null_command
};
static ngx_http_module_t ngx_http_mytest_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_module_t ngx_http_mytest_module =
{
NGX_MODULE_V1,
&ngx_http_mytest_module_ctx, /* module context */
ngx_http_mytest_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
};
static char *
ngx_http_mytest(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
//首先找到mytest配置項所屬的配置塊,clcf貌似是location塊內的數據
//結構,其實不然,它可以是main、srv或者loc級別配置項,也就是說在每個
//http{}和server{}內也都有一個ngx_http_core_loc_conf_t結構體
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
//http框架在處理用戶請求進行到NGX_HTTP_CONTENT_PHASE階段時,如果
//請求的主機域名、URI與mytest配置項所在的配置塊相匹配,就將調用我們
//實現的ngx_http_mytest_handler方法處理這個請求
clcf->handler = ngx_http_mytest_handler;
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r)
{
//必須是GET或者HEAD方法,否則返回405 Not Allowed
if (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD)))
{
return NGX_HTTP_NOT_ALLOWED;
}
//丟棄請求中的包體
ngx_int_t rc = ngx_http_discard_request_body(r);
if (rc != NGX_OK)
{
return rc;
}
ngx_buf_t *b;
b = ngx_palloc(r->pool, sizeof(ngx_buf_t));
//要打開的文件
u_char* filename = (u_char*)"/tmp/test.txt";
b->in_file = 1;
b->file = ngx_pcalloc(r->pool, sizeof(ngx_file_t));
b->file->fd = ngx_open_file(filename, NGX_FILE_RDONLY | NGX_FILE_NONBLOCK, NGX_FILE_OPEN, 0);
b->file->log = r->connection->log;
b->file->name.data = filename;
b->file->name.len = sizeof(filename) - 1;
if (b->file->fd <= 0)
{
return NGX_HTTP_NOT_FOUND;
}
//支持斷點續傳
r->allow_ranges = 1;
//獲取文件長度
if (ngx_file_info(filename, &b->file->info) == NGX_FILE_ERROR)
{
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
//設置緩沖區指向的文件塊
b->file_pos = 0;
b->file_last = b->file->info.st_size;
ngx_pool_cleanup_t* cln = ngx_pool_cleanup_add(r->pool, sizeof(ngx_pool_cleanup_file_t));
if (cln == NULL)
{
return NGX_ERROR;
}
cln->handler = ngx_pool_cleanup_file;
ngx_pool_cleanup_file_t *clnf = cln->data;
clnf->fd = b->file->fd;
clnf->name = b->file->name.data;
clnf->log = r->pool->log;
//設置返回的Content-Type。注意,ngx_str_t有一個很方便的初始化宏
//ngx_string,它可以把ngx_str_t的data和len成員都設置好
ngx_str_t type = ngx_string("text/plain");
//設置返回狀態碼
r->headers_out.status = NGX_HTTP_OK;
//響應包是有包體內容的,所以需要設置Content-Length長度
r->headers_out.content_length_n = b->file->info.st_size;
//設置Content-Type
r->headers_out.content_type = type;
//發送http頭部
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only)
{
return rc;
}
//構造發送時的ngx_chain_t結構體
ngx_chain_t out;
//賦值ngx_buf_t
out.buf = b;
//設置next為NULL
out.next = NULL;
//最后一步發送包體,http框架會調用ngx_http_finalize_request方法
//結束請求
return ngx_http_output_filter(r, &out);
}
注意點
處理方法必須是快速, 無阻塞的, ngx_http_mytest_handler 或者類似的處理方法中是不可以有耗時很長的操作的