Skip to content

Commit 8ab3b88

Browse files
authored
Merge pull request #34 from RunnningPig/master
feat: add lookup path support
2 parents 0aaa4fc + 2b1b7b8 commit 8ab3b88

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

lib/resty/maxminddb.lua

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ local ffi_cast = ffi.cast
2121
local ffi_gc = ffi.gc
2222
local C = ffi.C
2323

24+
local tab_isarray = require ('table.isarray')
25+
local tab_nkeys = require ('table.nkeys')
26+
2427
local _M ={}
2528
_M._VERSION = '1.3.3'
2629
local mt = { __index = _M }
@@ -312,7 +315,7 @@ local function _dump_entry_data_list(entry_data_list,status)
312315
return entry_data_list,status,result
313316
end
314317

315-
function _M.lookup(ip)
318+
function _M.lookup(ip, lookup_path)
316319

317320
if not initted then
318321
return nil, "not initialized"
@@ -337,8 +340,30 @@ function _M.lookup(ip)
337340
end
338341

339342
local entry_data_list = ffi_cast('MMDB_entry_data_list_s **const',ffi_new("MMDB_entry_data_list_s"))
343+
local status
344+
345+
if lookup_path then
346+
if not tab_isarray(lookup_path) then
347+
return nil, 'lookup path expected array'
348+
end
340349

341-
local status = maxm.MMDB_get_entry_data_list(result.entry,entry_data_list)
350+
local lookup_path_len = tab_nkeys(lookup_path)
351+
local entry_data = ffi_cast('MMDB_entry_data_s *const', ffi_new("MMDB_entry_data_s"))
352+
local path = ffi_new('const char * [?]', lookup_path_len+1, lookup_path) -- +1 for null termination
353+
path[lookup_path_len] = ffi.NULL
354+
355+
status = maxm.MMDB_aget_value(result.entry, entry_data, path)
356+
if status == MMDB_SUCCESS then
357+
if entry_data.offset == 0 then
358+
return nil, 'no data found at the lookup path'
359+
end
360+
local entry = ffi_new("MMDB_entry_s", {mmdb=mmdb, offset=entry_data.offset})
361+
status = maxm.MMDB_get_entry_data_list(entry, entry_data_list)
362+
end
363+
364+
else
365+
status = maxm.MMDB_get_entry_data_list(result.entry,entry_data_list)
366+
end
342367

343368
if status ~= MMDB_SUCCESS then
344369
return nil,'get entry data failed: ' .. mmdb_strerror(status)

0 commit comments

Comments
 (0)