树叶云nginx教程:Nginx 示例: hello handler 模块

示例: hello handler 模块

在前面已经看到了这个 hello handler module 的部分重要的结构。该模块提供了 2 个配置指令,仅可以出现在 location 指令的作用域中。这两个指令是 hello_string, 该指令接受一个参数来设置显示的字符串。如果没有跟参数,那么就使用默认的字符串作为响应字符串。

另一个指令是 hello_counter,如果设置为 on,则会在响应的字符串后面追加 Visited Times:的字样,以统计请求的次数。

这里有两点注意一下:

  1. 对于 flag 类型的配置指令,当值为 off 的时候,使用 ngx_conf_set_flag_slot 函数,会转化为 0,为on,则转化为非 0。
  2. 另外一个是,我提供了 merge_loc_conf 函数,但是却没有设置到模块的上下文定义中。这样有一个缺点,就是如果一个指令没有出现在配置文件中的时候,配置信息中的值,将永远会保持在 create_loc_conf 中的初始化的值。那如果,在类似 create_loc_conf 这样的函数中,对创建出来的配置信息的值,没有设置为合理的值的话,后面用户又没有配置,就会出现问题。

下面来完整的给出 ngx_http_hello_module 模块的完整代码。

    #include <ngx_config.h>
    #include <ngx_core.h>
    #include <ngx_http.h>

    typedef struct
    {
        ngx_str_t hello_string;
        ngx_int_t hello_counter;
    }ngx_http_hello_loc_conf_t;

    static ngx_int_t ngx_http_hello_init(ngx_conf_t *cf);

    static void *ngx_http_hello_create_loc_conf(ngx_conf_t *cf);

    static char *ngx_http_hello_string(ngx_conf_t *cf, ngx_command_t *cmd,
        void *conf);
    static char *ngx_http_hello_counter(ngx_conf_t *cf, ngx_command_t *cmd,
        void *conf);

    static ngx_command_t ngx_http_hello_commands[] = {
       { 
            ngx_string("hello_string"),
            NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS|NGX_CONF_TAKE1,
            ngx_http_hello_string,
            NGX_HTTP_LOC_CONF_OFFSET,
            offsetof(ngx_http_hello_loc_conf_t, hello_string),
            NULL },

        { 
            ngx_string("hello_counter"),
            NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
            ngx_http_hello_counter,
            NGX_HTTP_LOC_CONF_OFFSET,
            offsetof(ngx_http_hello_loc_conf_t, hello_counter),
            NULL },               

        ngx_null_command
    };

    /* 
    static u_char ngx_hello_default_string[] = "Default String: Hello, world!";
    */
    static int ngx_hello_visited_times = 0; 

    static ngx_http_module_t ngx_http_hello_module_ctx = {
        NULL,                          /* preconfiguration */
        ngx_http_hello_init,           /* postconfiguration */

        NULL,                          /* create main configuration */
        NULL,                          /* init main configuration */

        NULL,                          /* create server configuration */
        NULL,                          /* merge server configuration */

        ngx_http_hello_create_loc_conf, /* create location configuration */
        NULL                            /* merge location configuration */
    };

    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
    };

    static ngx_int_t
    ngx_http_hello_handler(ngx_http_request_t *r)
    {
        ngx_int_t    rc;
        ngx_buf_t   *b;
        ngx_chain_t  out;
        ngx_http_hello_loc_conf_t* my_conf;
        u_char ngx_hello_string[1024] = {0};
        ngx_uint_t content_length = 0;

        ngx_log_error(NGX_LOG_EMERG, r->connection->log, 0, "ngx_http_hello_handler is called!");

        my_conf = ngx_http_get_module_loc_conf(r, ngx_http_hello_module);
        if (my_conf->hello_string.len == 0 )
        {
            ngx_log_error(NGX_LOG_EMERG, r->connection->log, 0, "hello_string is empty!");
            return NGX_DECLINED;
        }

        if (my_conf->hello_counter == NGX_CONF_UNSET
            || my_conf->hello_counter == 0)
        {
            ngx_sprintf(ngx_hello_string, "%s", my_conf->hello_string.data);
        }
        else
        {
            ngx_sprintf(ngx_hello_string, "%s Visited Times:%d", my_conf->hello_string.data, 
                ++ngx_hello_visited_times);
        }
        ngx_log_error(NGX_LOG_EMERG, r->connection->log, 0, "hello_string:%s", ngx_hello_string);
        content_length = ngx_strlen(ngx_hello_string);

        /* we response to 'GET' and 'HEAD' requests only */
        if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) {
            return NGX_HTTP_NOT_ALLOWED;
        }

        /* discard request body, since we don't need it here */
        rc = ngx_http_discard_request_body(r);

        if (rc != NGX_OK) {
            return rc;
        }

        /* set the 'Content-type' header */
        /*
         *r->headers_out.content_type.len = sizeof("text/html") - 1;
         *r->headers_out.content_type.data = (u_char *)"text/html";
                 */
        ngx_str_set(&r->headers_out.content_type, "text/html");

        /* send the header only, if the request type is http 'HEAD' */
        if (r->method == NGX_HTTP_HEAD) {
            r->headers_out.status = NGX_HTTP_OK;
            r->headers_out.content_length_n = content_length;

            return ngx_http_send_header(r);
        }

        /* allocate a buffer for your response body */
        b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
        if (b == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        /* attach this buffer to the buffer chain */
        out.buf = b;
        out.next = NULL;

        /* adjust the pointers of the buffer */
        b->pos = ngx_hello_string;
        b->last = ngx_hello_string + content_length;
        b->memory = 1;    /* this buffer is in memory */
        b->last_buf = 1;  /* this is the last buffer in the buffer chain */

        /* set the status line */
        r->headers_out.status = NGX_HTTP_OK;
        r->headers_out.content_length_n = content_length;

        /* send the headers of your response */
        rc = ngx_http_send_header(r);

        if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
            return rc;
        }

        /* send the buffer chain of your response */
        return ngx_http_output_filter(r, &out);
    }

    static void *ngx_http_hello_create_loc_conf(ngx_conf_t *cf)
    {
        ngx_http_hello_loc_conf_t* local_conf = NULL;
        local_conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_hello_loc_conf_t));
        if (local_conf == NULL)
        {
            return NULL;
        }

        ngx_str_null(&local_conf->hello_string);
        local_conf->hello_counter = NGX_CONF_UNSET;

        return local_conf;
    } 

    /*
    static char *ngx_http_hello_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
    {
        ngx_http_hello_loc_conf_t* prev = parent;
        ngx_http_hello_loc_conf_t* conf = child;

        ngx_conf_merge_str_value(conf->hello_string, prev->hello_string, ngx_hello_default_string);
        ngx_conf_merge_value(conf->hello_counter, prev->hello_counter, 0);

        return NGX_CONF_OK;
    }*/

    static char *
    ngx_http_hello_string(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
    {

        ngx_http_hello_loc_conf_t* local_conf;

        local_conf = conf;
        char* rv = ngx_conf_set_str_slot(cf, cmd, conf);

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "hello_string:%s", local_conf->hello_string.data);

        return rv;
    }

    static char *ngx_http_hello_counter(ngx_conf_t *cf, ngx_command_t *cmd,
        void *conf)
    {
        ngx_http_hello_loc_conf_t* local_conf;

        local_conf = conf;

        char* rv = NULL;

        rv = ngx_conf_set_flag_slot(cf, cmd, conf);

        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "hello_counter:%d", local_conf->hello_counter);
        return rv;    
    }

    static ngx_int_t
    ngx_http_hello_init(ngx_conf_t *cf)
    {
        ngx_http_handler_pt        *h;
        ngx_http_core_main_conf_t  *cmcf;

        cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

        h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers);
        if (h == NULL) {
            return NGX_ERROR;
        }

        *h = ngx_http_hello_handler;

        return NGX_OK;
    }

通过上面一些介绍,我相信大家都能对整个示例模块有一个比较好的理解。唯一可能感觉有些理解困难的地方在于ngx_http_hello_handler 函数里面产生和设置输出。但其实大家在本书的前面的相关章节都可以看到对 ngx_buf_t 和 request 等相关数据结构的说明。如果仔细看了这些地方的说明的话,应该对这里代码的实现就比较容易理解了。因此,这里不再赘述解释。

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/155200.html<

(0)
运维的头像运维
上一篇2025-03-15 08:10
下一篇 2025-03-15 08:11

相关推荐

  • AlphaNine美国怎么样?AlphaNine美国官网入口

    AlphaNine 美国作为 2026 年高性能计算与边缘 AI 领域的领军品牌,其核心优势在于通过自研异构计算架构实现了 40% 的能效比提升,是解决企业级数据延迟与算力瓶颈的首选方案,尤其在 2026 年中美科技博弈背景下,其合规性与本土化服务能力成为关键决策点,AlphaNine 美国技术架构与 2026……

    2026-05-02
    0
  • AviarHostVPS测评,实测体验,AviarHostVPS怎么样,AviarHostVPS好用吗

    AviarHostVPS 在 2026 年实测中展现出极高的性价比与网络稳定性,是中小型企业搭建海外业务及开发者进行轻量级应用部署的理想选择,尤其适合关注AviarHostVPS 价格与海外服务器免备案场景的用户,在云计算市场高度内卷的 2026 年,VPS 服务商的筛选标准已从单纯的“低价”转向“性能密度”与……

    2026-05-02
    0
  • hypervmart美国是什么?hypervmart美国官网入口

    2026 年 Hypervmart 美国站已全面接入 AI 智能选品与跨境物流自动化系统,成为中小卖家切入北美市场的首选低成本独立站解决方案,其核心优势在于“零库存 + 高转化”的闭环模式,随着 2026 年全球跨境电商进入“精细化运营”深水区,Hypervmart 美国站凭借其对北美消费者行为的深度洞察,在独……

    2026-05-02
    0
  • hypervmart是什么,hypervmart官网入口

    hypervmart 在 2026 年是否值得投资?核心结论:是,但需精准匹配供应链场景hypervmart 作为 2026 年跨境零售与 B2B 融合的新兴平台,其核心价值在于利用 AI 驱动的供应链优化技术,为中小卖家提供低于行业平均 15% 的履约成本,但成功与否高度依赖卖家对“跨境物流时效”与“海外仓选……

    2026-05-02
    0
  • RAKsmart独立服务器2026年测评,CN2 GIA实测数据与性能表现,CN2 GIA服务器到底怎么样,CN2 GIA独立服务器推荐

    RAKsmart 独立服务器在 2026 年已确立为连接中国内地与全球的高性能网络枢纽,其 CN2 GIA 线路实测延迟稳定在 35ms 以内,吞吐量突破 900Mbps,是跨境业务场景下兼顾稳定性与性价比的优选方案,核心网络性能深度解析2026 年 CN2 GIA 线路实测数据在 2026 年的网络架构中,R……

    2026-05-02
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注