Preparation of the Hello module

Source: Internet
Author: User
Tags define null
In order to learn high-performance concurrent server, we intend to study the implementation of Nginx. As it is customary to write a Hello World program at the beginning, the next step is to write a simple HTTP module in the Nginx framework to print "Hello World".

Defining the handling of Hello configuration items

First, we need to define a commands array to define the configuration file parameters for the module. Each array element is a ngx_command_t type, and the end of the arrays ends with Ngx_null_command.

Nginx will first traverse all modules when parsing a configuration item in the configuration file, for each module, by traversing the commands array. Each of the ngx_command_t structures defines a configuration item of interest to them. The structure is defined as follows:

struct ngx_command_s {    /* 配置项名称 */    ngx_str_t             name;    /* 指定配置项可以出现的位置 */    ngx_uint_t            type;    /* 出现了name中指定的配置项后,将会调用set方法处理配置项的参数 */char               *(*setvoid *conf);    ngx_uint_t            conf;    /* 在配置文件中的偏移量 */    ngx_uint_t            offset;    /* 配置项读取后的处理过程,必须是ngx_conf_post_t结构的指针 */void                 *post;};#define ngx_null_command  { ngx_null_string, 0, NULL, 0, 0, NULL }

After understanding the commands array, we define the handling of the Hello configuration item:

static ngx_command_t ngx_http_hello_commands[] = {    {   ngx_string("hello"),        NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,        ngx_http_hello,        NGX_HTTP_LOC_CONF_OFFSET,        0,        NULL },    ngx_null_command};

Where Ngx_http_hello is a set member in the ngx_command_t struct, Nginx calls the Ngx_http_hello method when a Hello configuration item appears in a configuration block. Here is the implementation of Ngx_http_hello:

staticcharvoid *conf){    ngx_http_core_loc_conf_t *clcf;    /* 首先找到hello配置项所属的配置块 */    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);    /* HTTP框架在处理用户请求进行到NGX_HTTP_CONTENT_PHASE阶段时     * 如果请求的主机域名、URI与hello配置项所在的配置块相匹配     * 则调用ngx_http_hello_handler方法处理这个请求     */    clcf->handler = ngx_http_hello_handler;    return NGX_CONF_OK;}

Defining the Hello Module

The way to define an HTTP module is as simple as defining a ngx_moodule_t structure as follows:

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

The Hello module will be added to the Ngx_modules global array at compile time.

This ngx_http_hello_commands is the process of the Hello configuration item we defined in the previous section.

Because we're defining an HTTP module, we type 're going to set it up NGX_HTTP_MODULE .

There is also an important member void* ctx , for the HTTP module, the CTX pointer must point to the ngx_http_module_t interface.

The HTTP framework defines the 8 stages described by the ngx_http_module_t interface when it reads and overloads the configuration file, and the HTTP framework invokes the corresponding method in ngx_http_module_t at each stage when it is started. If you do not need to do any work, you can define NULL. Because the Hello module does not need to do any work, it is defined as follows:

static ngx_http_module_t ngx_http_hello_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 */};

Handling User Requests

The last is to process the user request, here need a bit of HTTP knowledge, you can refer to the HTTP protocol primer. We process the user's request by implementing the method ngx_http_hello_handler , which is defined as follows:

static ngx_int_tngx_http_hello_handler(ngx_http_request_t *r)

The ngx_http_request_t structure contains all the information requested (such as methods, URIs, protocol version numbers and headers, etc.), in addition to many other members, such as memory pools, response headers, and so on.

Because we only deal with the Get method and the head method, we need to make the following judgments:

if (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD))) {        return NGX_HTTP_NOT_ALLOWED; }

Next, because we don't need the package body in the request, we need to discard the swap body as follows:

ngx_int_t rc = ngx_http_discard_request_body(r);if (rc != NGX_OK) {    return rc;}

The response package returned is then set, and the returned package contains only a "Hello world" string:

ngx_str_type = ngx_string("text/plain");ngx_str_response = ngx_string("Hello World");r->headers_out.status = NGX_HTTP_OK;r->headers_out.content_length_n = response.len;r->headers_out.content_type = type;

Finally, we send the packet header and the package body of the response package:

    rc = ngx_http_send_header(r);    if (rc == NGX_ERR || rc > NGX_OK || r->header_only) {        return rc;    }    ngx_buf_t *b;    b = ngx_create_temp_buf(r->pool, response.len);    if (b == NULL) {        return NGX_HTTP_INTERNAL_SERVER_ERROR;    }    ngx_memcpy(b->pos, response.data, response.len);    b->last = b->pos + response.len;    1;    ngx_chain_t out;    out.buf = b;    out.next = NULL;    /* send the buffer chain of your response */return ngx_http_output_filter(r, &out);

The complete code can be viewed here: hello_module

Compiling and running

Create a new file in the same directory as the code config and add a few lines:

ngx_addon_name=ngx_http_hello_moduleHTTP_MODULES="$HTTP_MODULES ngx_http_hello_module"NGX_ADDON_SRCS="$NGX_ADDON_SRCS$ngx_addon_dir/ngx_http_hello_module.c"

Then enter the source of Nginx root directory, run configure , remember to take the –add-module parameter, after the parameters of our own written HTTP module code is located in the path:

./configure --prefix=/usr/local/nginx --add-module=/code/nginx-1.8.0/src/http/hello_module

After the Configure run is complete, make compile with the command, and enter the installation after the compilation is successful make install .

Modify /usr/local/nginx/conf/nginx.conf , add:

http{    ...    server {        ...        location /hello {            hello;        }        ...    }    ...}

Run Nginx, and then IP/hello you can see the "Hello World string" displayed in the browser input.

Reference

"Deep understanding of Nginx"

The above describes the preparation of the Hello module, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.