[njs] Allow access to nginx vars via the njs $v variable

Ronan Jezequel ronan.jezequel at gmail.com
Wed May 4 09:29:48 UTC 2016


# HG changeset patch
# User Ronan Jezequel <ronan.jezequel at gmail.com>
# Date 1462351563 -28800
#      Wed May 04 16:46:03 2016 +0800
# Node ID 00b51c1bd9c3b92173528a109473a5cc865f507f
# Parent  1c50334fbea6441d2d8740b56f881eb77290af42
Allow access to nginx vars via njs $v variable (eg: $v.geoip_city)

diff -r 1c50334fbea6 -r 00b51c1bd9c3 nginx/ngx_http_js_module.c
--- a/nginx/ngx_http_js_module.c Thu Apr 14 18:23:09 2016 +0300
+++ b/nginx/ngx_http_js_module.c Wed May 04 16:46:03 2016 +0800
@@ -95,6 +95,8 @@
     njs_value_t *value, void *obj, uintptr_t data);
 static njs_ret_t ngx_http_js_ext_get_remote_address(njs_vm_t *vm,
     njs_value_t *value, void *obj, uintptr_t data);
+static njs_ret_t ngx_http_js_ext_get_var(njs_vm_t *vm,
+    njs_value_t *value, void *obj, uintptr_t data);
 static njs_ret_t ngx_http_js_ext_get_header_in(njs_vm_t *vm,
njs_value_t *value,
     void *obj, uintptr_t data);
 static njs_ret_t ngx_http_js_ext_foreach_header_in(njs_vm_t *vm, void *obj,
@@ -366,6 +368,18 @@
       NULL,
       NULL,
       0 },
+
+    { nxt_string("$v"),
+      NJS_EXTERN_OBJECT,
+      NULL,
+      0,
+      ngx_http_js_ext_get_var,
+      NULL,
+      NULL,
+      NULL,
+      NULL,
+      NULL,
+      0 },
 };


@@ -939,6 +953,38 @@


 static njs_ret_t
+ngx_http_js_ext_get_var(njs_vm_t *vm, njs_value_t *value, void *obj,
+    uintptr_t data)
+{
+    nxt_str_t                 *v;
+    ngx_http_request_t        *r;
+
+    ngx_str_t                 name;
+    ngx_uint_t                hash;
+    ngx_http_variable_value_t *val;
+
+    v = (nxt_str_t*)data;
+    if (!v) {
+        return njs_string_create(vm, value, NULL, 0, 0);
+    }
+
+    name.len = v->len;
+    name.data = (u_char *) v->data;
+    hash = ngx_hash_key (v->data, v->len);;
+
+    r = (ngx_http_request_t *) obj;
+    val = ngx_http_get_variable( r, &name, hash);
+
+    if( val && !val->not_found && val->valid)
+    {
+      return njs_string_create(vm, value, val->data, val->len, 0);
+    }
+
+    return njs_string_create(vm, value, NULL, 0, 0);
+}
+
+
+static njs_ret_t
 ngx_http_js_ext_get_remote_address(njs_vm_t *vm, njs_value_t *value, void *obj,
     uintptr_t data)
 {



More information about the nginx-devel mailing list