2021-08-27 12:15:22 +00:00
|
|
|
include /etc/nginx/conf.d/include/init-optional-variables;
|
|
|
|
|
|
|
|
location / {
|
|
|
|
set $skylink "";
|
|
|
|
set $path $uri;
|
|
|
|
|
|
|
|
rewrite_by_lua_block {
|
2022-04-08 11:56:20 +00:00
|
|
|
local cjson = require("cjson")
|
2021-10-26 11:01:15 +00:00
|
|
|
local cache = ngx.shared.dnslink
|
|
|
|
local cache_value = cache:get(ngx.var.host)
|
2021-08-27 12:15:22 +00:00
|
|
|
|
2021-10-26 11:01:15 +00:00
|
|
|
if cache_value == nil then
|
|
|
|
local httpc = require("resty.http").new()
|
2021-08-27 12:15:22 +00:00
|
|
|
|
2021-10-26 11:01:15 +00:00
|
|
|
-- 10.10.10.55 points to dnslink-api service (alias not available when using resty-http)
|
|
|
|
local res, err = httpc:request_uri("http://10.10.10.55:3100/dnslink/" .. ngx.var.host)
|
2021-09-20 20:20:48 +00:00
|
|
|
|
2021-10-26 11:01:15 +00:00
|
|
|
if err or (res and res.status ~= ngx.HTTP_OK) then
|
|
|
|
-- check whether we can fallback to regular skylink request
|
|
|
|
local match_skylink = ngx.re.match(ngx.var.uri, "^/([a-zA-Z0-9-_]{46}|[a-z0-9]{55})(/.*)?")
|
|
|
|
|
|
|
|
if match_skylink then
|
|
|
|
ngx.var.skylink = match_skylink[1]
|
|
|
|
ngx.var.path = match_skylink[2] or "/"
|
|
|
|
else
|
|
|
|
ngx.status = (err and ngx.HTTP_INTERNAL_SERVER_ERROR) or res.status
|
|
|
|
ngx.header["content-type"] = "text/plain"
|
|
|
|
ngx.say(err or res.body)
|
|
|
|
ngx.exit(ngx.status)
|
|
|
|
end
|
2021-10-26 14:47:06 +00:00
|
|
|
else
|
2022-04-08 11:56:20 +00:00
|
|
|
local resolved = cjson.decode(res.body)
|
|
|
|
|
|
|
|
ngx.var.skylink = resolved.skylink
|
|
|
|
if resolved.sponsor then
|
|
|
|
ngx.req.set_header("Skynet-Api-Key", resolved.sponsor)
|
|
|
|
end
|
2021-10-26 14:44:06 +00:00
|
|
|
|
|
|
|
local cache_ttl = 300 -- 5 minutes cache expire time
|
2022-04-08 11:56:20 +00:00
|
|
|
cache:set(ngx.var.host, res.body, cache_ttl)
|
2021-09-20 20:20:48 +00:00
|
|
|
end
|
2021-08-27 12:15:22 +00:00
|
|
|
else
|
2022-04-08 11:56:20 +00:00
|
|
|
local resolved = cjson.decode(cache_value)
|
|
|
|
|
|
|
|
ngx.var.skylink = resolved.skylink
|
|
|
|
if resolved.sponsor then
|
|
|
|
ngx.req.set_header("Skynet-Api-Key", resolved.sponsor)
|
|
|
|
end
|
2021-08-27 12:15:22 +00:00
|
|
|
end
|
2021-10-26 11:01:15 +00:00
|
|
|
|
2022-03-10 08:55:24 +00:00
|
|
|
ngx.var.skylink = require("skynet.skylink").parse(ngx.var.skylink)
|
2021-08-27 12:15:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
include /etc/nginx/conf.d/include/location-skylink;
|
|
|
|
}
|