看起来您想要对数据进行 api 调用以运行决策和逻辑。这不是代理的全部内容。
nginx 的核心代理能力并不是为你想要做的事情而设计的。
可能的解决方法:扩展 nginx...
Nginx + PHP
您的 php 代码可以完成这项工作。
作为客户端连接到 Golang 服务器并对响应应用额外的逻辑。
<?php
$response = file_get_contents('https://go.example.com/getpath?file_id='.$_GET["id"]);
preg_match_all("/filePath: \"(.*?)\"/", $response, $filePath);
readfile($filePath[1][0]);
?>
location /getpath {
try_files /getpath.php;
}
这只是让它滚动的伪代码示例。
一些杂项观察/cmets:
- Golang 响应看起来不是有效的 json,如果是,请将 preg_match_all 替换为 json_decode。
- readfile 效率不高。考虑通过 302 响应来发挥创意。
Nginx + Lua
启用站点:
lua_package_path "/etc/nginx/conf.d/lib/?.lua;;";
server {
listen 80 default_server;
listen [::]:80 default_server;
location /getfile {
root /var/www/html;
resolver 8.8.8.8;
set $filepath "/index.html";
access_by_lua_file /etc/nginx/conf.d/getfile.lua;
try_files $filepath =404;
}
}
测试 lua 是否按预期运行:
getfile.lua (v1)
ngx.var.filepath = "/static/...";
简化 Golang 响应体,只返回一个平淡无奇的路径,然后用它来设置文件路径:
getfile.lua (v2)
local http = require "resty.http"
local httpc = http.new()
local query_string = ngx.req.get_uri_args()
local res, err = httpc:request_uri('https://go.example.com/getpath?file_id=' .. query_string["id"], {
method = "GET",
keepalive_timeout = 60,
keepalive_pool = 10
})
if res and res.status == ngx.HTTP_OK then
body = string.gsub(res.body, '[\r\n%z]', '')
ngx.var.filepath = body;
ngx.log(ngx.ERR, "[" .. body .. "]");
else
ngx.log(ngx.ERR, "missing response");
ngx.exit(504);
end
resty.http
mkdir -p /etc/nginx/conf.d/lib/resty
wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http_headers.lua" -P /etc/nginx/conf.d/lib/resty
wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http.lua" -P /etc/nginx/conf.d/lib/resty