我爱编程

Nginx编写Http模块

2017-05-09  本文已影响0人  Spike_3154

HTTP模块的调用

基本数据结构

typedef struct {
    size_t len;
    u_char * data;
}ngx_str_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;

其内存分布图如下所示


将自己的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_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.jianshu.com/p/d7a783de09dd

处理用户请求

在出现mytest 配置项的时候, ngx_http_mytest 方法被调用, 这时候, 将ngx_http_core_loc_conf_t 结构的handler 成员指定为ngx_http_mytest_handler。 在HTTP 框架接收完HTTP请求的头部之后, 会调用handler指向的方法, 用来处理用户请求。

    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_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);
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 或者类似的处理方法中是不可以有耗时很长的操作的

上一篇 下一篇

猜你喜欢

热点阅读