@@ -50,4 +50,58 @@ ngx_http_echo(ngx_conf_t *f,ngx_command_t *cmd , void *conf)
5050 clcf -> handle = ngx_http_echo_handler ; //修改核心模块配置(也就是当前location),将其handler替换为我们自己定义的ngx_http_echo_handler
5151 ngx_conf_set_str_slot (cf ,cmf ,conf );
5252 return NGX_CONF_OK ;
53+ }
54+
55+ //创建合并配置信息 定义模块Context
56+ /**
57+ * 定义ngx_http_module_t类型的结构体变量 命名规则为ngx_http_[module-name]_module_ctx,这个结构主要用于定义各个Hook函数
58+ *
59+ * 可以看到一共有8个Hook注入点,分别会在不同时刻被Nginx调用,由于我们的模块仅仅用于location域,这里将不需要的注入点设为NULL即可。
60+ *
61+ * ngx_http_echo_create_loc_conf ngx_http_echo_merge_loc_conf 这两个函数会被Nginx自动调用。注意这里的命名规则:ngx_http_[module-name]_[create|merge]_[main|srv|loc]_conf。
62+ */
63+ static ngx_http_module_t ngx_http_echo_module_ctx = {
64+ NULL , /* preconfiguration */
65+ NULL , /* postconfiguration */
66+ NULL , /* create main configuration */
67+ NULL , /* init main configuration */
68+ NULL , /* create server configuration */
69+ NULL , /* merge server configuration */
70+ ngx_http_echo_create_loc_conf , /* create location configration */
71+ ngx_http_echo_merge_loc_conf /* merge location configration */
72+ };
73+
74+ /**
75+ * 初始化一个配置结构体
76+ * @param cf
77+ * @return
78+ */
79+ static char *
80+ ngx_http_echo_create_loc_conf (ngx_conf_t * cf )
81+ {
82+ ngx_http_echo_loc_conf_t * conf ;
83+ conf = ngx_pcalloc (cf -> pool , sizeof (ngx_http_echo_loc_conf_t )); //gx_pcalloc用于在Nginx内存池中分配一块空间,是pcalloc的一个包装
84+ if (conf == NULL ) {
85+ return NGX_CONF_ERROR ;
86+ }
87+ conf -> ed .len = 0 ;
88+ conf -> ed .data = NULL ;
89+ return conf ;
90+ }
91+ /**
92+ * 将其父block的配置信息合并到此结构体 实现了配置的继承
93+ * @param cf
94+ * @param parent
95+ * @param child
96+ * @return ngx status code
97+ *
98+ * ngx_conf_merge_str_value不是一个函数,而是一个宏,其定义在https://github.com/nginx/nginx/blob/master/src/core/ngx_conf_file.h#L205中
99+ */
100+ static char *
101+ ngx_http_echo_merge_loc_conf (ngx_conf_t * cf , void * parent , void * child )
102+ {
103+ ngx_http_echo_loc_conf_t * prev = parent ;
104+ ngx_http_echo_loc_conf_t * conf = child ;
105+ ngx_conf_merge_str_value (conf -> ed , prev -> ed , '"' );
106+ return NGX_CONF_OK ;
53107}
0 commit comments