Hello!

On Fri, Dec 30, 2016 at 02:36:00PM +0100, Witold Filipczyk wrote:

> Hi,
> 
> there is map:
> map $http_host $hosts {
>   hostnames;
>   default 0;
>   .example.com 1;
>   .example.net 1;
>   ...
>   .example.org 1;
> }
> 
> How to read the value of $hosts in C module code?

If you only need a single variable, most effective approach is to 
use indexed variables.  The ngx_http_get_variable_index() function 
is used to obtain an index during configuration parsing / module 
initialization, and ngx_http_get_indexed_variable() to obtain a 
value at runtime.  E.g., memcached module uses this to access 
$memcached_key variable, see here:

http://hg.nginx.org/nginx/file/tip/src/http/modules/ngx_http_memcached_module.c#l716
http://hg.nginx.org/nginx/file/tip/src/http/modules/ngx_http_memcached_module.c#l243

More universal approach is to use complex values.  Complex values 
can contain arbitrary combinations of variables and static 
strings.  During configuration parsing complex values are compiled 
using ngx_http_compile_complex_value() 
(ngx_http_set_complex_value_slot can do it automatically if there 
is a dedicated configuration directive), and then 
ngx_http_complex_value() can be used to obtain a value.  E.g., map 
itself uses complex value to handle the first parameter, 
"$http_host" in your case, see here:

http://hg.nginx.org/nginx/file/tip/src/http/modules/ngx_http_map_module.c#l209
http://hg.nginx.org/nginx/file/tip/src/http/modules/ngx_http_map_module.c#l120

> How to make it right, that's mean do not evaluate it more than once per 
> request?

Map results are automatically cached by nginx, much like all 
variables not explicitly declared as non-cacheable, so you don't 
really need to worry.  On the other hand, usually it's a good idea 
to remember the value obtained in your module data if you are 
going to use it again.

-- 
Maxim Dounin
http://nginx.org/
_______________________________________________
nginx-devel mailing list
[email protected]
http://mailman.nginx.org/mailman/listinfo/nginx-devel

Reply via email to