diff --git a/apisix/core/table.lua b/apisix/core/table.lua index 4ad92caa104d2..942a7f3b438ab 100644 --- a/apisix/core/table.lua +++ b/apisix/core/table.lua @@ -59,6 +59,22 @@ function _M.set(tab, ...) end +function _M.try_read_attr(tab, ...) + local count = select('#', ...) + + for i = 1, count do + local attr = select(i, ...) + if type(tab) ~= "table" then + return nil + end + + tab = tab[attr] + end + + return tab +end + + -- only work under lua51 or luajit function _M.setmt__gc(t, mt) local prox = newproxy(true) diff --git a/apisix/plugins/skywalking.lua b/apisix/plugins/skywalking.lua index 26aeb60bff96a..348843e16f3b9 100644 --- a/apisix/plugins/skywalking.lua +++ b/apisix/plugins/skywalking.lua @@ -22,6 +22,7 @@ local math = math local select = select local type = type local require = require +local try_read_attr = core.table.try_read_attr local plugin_name = "skywalking" local metadata_schema = { @@ -103,20 +104,6 @@ function _M.log(conf, ctx) end -local function try_read_attr(t, ...) - local count = select('#', ...) - for i = 1, count do - local attr = select(i, ...) - if type(t) ~= "table" then - return nil - end - t = t[attr] - end - - return t -end - - function _M.init() if process.type() ~= "worker" and process.type() ~= "single" then return diff --git a/t/core/table.t b/t/core/table.t index 59c887538e7d1..0037ab5feae90 100644 --- a/t/core/table.t +++ b/t/core/table.t @@ -77,3 +77,31 @@ GET /t ok --- no_error_log [error] + + + +=== TEST 3: try_read_attr +--- config + location /t { + content_by_lua_block { + local core = require("apisix.core") + local try_read_attr = core.table.try_read_attr + + local t = {level1 = {level2 = "value"}} + + local v = try_read_attr(t, "level1", "level2") + + ngx.say(v) + + loval v2 = try_read_attr(t, "level1", "level3") + + ngx.say(v2) + } + } +--- request +GET /t +--- response_body +"value" +"" +--- no_error_log +[error]