OpenResty Lua脚本实现IP地址地理位置查询
使用Lua脚本在OpenResty中实现了根据IP地址查询地理位置信息的功能。通过调用'resty.maxminddb'库来解析MaxMind公司提供的'GeoLite2-City'数据库。如果查询成功,将返回包含完整地理位置信息的JSON格式数据,并且可以根据传入的参数查询特定节点的值。如果查询失败,将会记录错误日志。
content_by_lua_block{
local cjson = require 'cjson'
local geo = require 'resty.maxminddb'
if not geo.initted() then
geo.init('/home/wwwroot/openrestry_nginx/GeoLite2-City.mmdb')
end
local res,err = geo.lookup(ngx.var.arg_ip or ngx.var.remote_addr) --support ipv6 e.g. 2001:4860:0:1001::3004:ef68
if not res then
ngx.log(ngx.ERR,'failed to lookup by ip ,reason:',err)
end
ngx.say('full :',cjson.encode(res))
if ngx.var.arg_node then
ngx.say('node name:',ngx.var.arg_node,' ,value:', cjson.encode(res[ngx.var.arg_node] or {}))
end
}
原文地址: https://www.cveoy.top/t/topic/njUU 著作权归作者所有。请勿转载和采集!