Welcome! Log In Create A New Profile

Advanced

Re: How to read variable in C code?

Maxim Dounin
December 30, 2016 09:44PM
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
nginx-devel@nginx.org
http://mailman.nginx.org/mailman/listinfo/nginx-devel
Subject Author Views Posted

How to read variable in C code?

Witold Filipczyk 541 December 30, 2016 08:38AM

Re: How to read variable in C code?

Maxim Dounin 415 December 30, 2016 09:44PM



Sorry, you do not have permission to post/reply in this forum.

Online Users

Guests: 182
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready