diff --git a/README.markdown b/README.markdown index 8566006..1636580 100644 --- a/README.markdown +++ b/README.markdown @@ -134,6 +134,12 @@ It accepts a `opts` table argument. The following options are supported: * `no_recurse` a boolean flag controls whether to disable the "recursion desired" (RD) flag in the UDP request. Defaults to `false`. +* `tcp` + + an optional function to create a tcp socket. This allows using the library in contexts where the co-sockets are unavailable. Defaults to `ngx.socket.tcp`. +* `udp` + an optional function to create a udp socket. This allows using the library in contexts where the co-sockets are unavailable. Defaults to `ngx.socket.udp`. + [Back to TOC](#table-of-contents) diff --git a/lib/resty/dns/resolver.lua b/lib/resty/dns/resolver.lua index 6650aea..2719546 100644 --- a/lib/resty/dns/resolver.lua +++ b/lib/resty/dns/resolver.lua @@ -3,7 +3,6 @@ -- local socket = require "socket" local bit = require "bit" -local udp = ngx.socket.udp local rand = math.random local char = string.char local byte = string.byte @@ -18,7 +17,6 @@ local lshift = bit.lshift local insert = table.insert local concat = table.concat local re_sub = ngx.re.sub -local tcp = ngx.socket.tcp local log = ngx.log local DEBUG = ngx.DEBUG local unpack = unpack @@ -112,6 +110,9 @@ function _M.new(class, opts) local timeout = opts.timeout or 2000 -- default 2 sec + local udp = opts.udp or ngx.socket.udp + local tcp = opts.tcp or ngx.socket.tcp + local n = #servers local socks = {} diff --git a/t/sanity.t b/t/sanity.t index 8982454..2fffa31 100644 --- a/t/sanity.t +++ b/t/sanity.t @@ -5,7 +5,7 @@ use Cwd qw(cwd); repeat_each(2); -plan tests => repeat_each() * (3 * blocks()); +plan tests => repeat_each() * (3 * blocks()) - 2; my $pwd = cwd(); @@ -646,3 +646,50 @@ GET /t --- no_error_log [error] --- no_check_leak + + + +=== TEST 20: override socket functions +--- http_config eval: $::HttpConfig +--- config + location /t { + content_by_lua ' + local resolver = require "resty.dns.resolver" + + local r, err = + resolver:new { + nameservers = { "$TEST_NGINX_RESOLVER" }, + tcp = function(...) + ngx.say("tcp called") + return ngx.socket.tcp(...) + end, + udp = function(...) + ngx.say("udp called") + return ngx.socket.udp(...) + end, + } + if not r then + ngx.say("failed to instantiate resolver: ", err) + return + end + + local ans, err = r:query("google.com") + if not ans then + ngx.say("failed to query (udp): ", err) + return + end + local ans, err = r:tcp_query("google.com") + if not ans then + ngx.say("failed to query (tcp): ", err) + return + end + '; + } +--- request +GET /t +--- response +udp called +tcp called +--- no_error_log +[error] +--- no_check_leak