gpt4 book ai didi

http - 使用 Nginx Lua 模块写入文件

转载 作者:可可西里 更新时间:2023-11-01 16:40:49 29 4
gpt4 key购买 nike

我正在试验 Nginx Lua module 。目前,我的目标只是将某些 HTTP 响应保存到磁盘上的本地文件中。

阅读一些教程后,我的理解是我可以使用 body_filter_by_lua 来做到这一点指示。我的方法只是在 nginx.conf 中嵌入一些 Lua 代码。文件,从 ngx.arg 检索响应主体, 然后使用标准 Lua io将其写入磁盘的设施。

我以前从未用 Lua 编程过,但我用其他脚本语言(如 Python)进行过大量编程,所以我发现学习 Lua 的基础知识相当容易。

仍然,我的方法不起作用,nginx error.log表示问题是 file我打开的对象是nil .

这是我放在 nginx.conf 中的 Lua 代码文件(为清楚起见进行了编辑):

   location /foo {
proxy_pass http://my_upstream_proxy;
proxy_cache my_cache;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

body_filter_by_lua '
local resp_body = ngx.arg[1]
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end

local file = io.open("TEST.txt", "w+b")
file:write(resp_body)
file:close()
';
}

所以这里的想法是 nginx 会简单地将请求传递给代理,然后将响应正文写入本地文件。

我测试这个使用:

curl http://www.google.com --proxy http://localhost:80

但是 nginx 返回一个空回复。

所以我检查错误日志并看到:

2016/12/15 11:51:00 [error] 10056#0: *1 failed to run body_filter_by_lua*: body_filter_by_lua:9: attempt to index local 'file' (a nil value)
stack traceback:
body_filter_by_lua:9: in function <body_filter_by_lua:1> while sending to client, client: 127.0.0.1, server: test-server, request: "GET http://www.google.com/ HTTP/1.1", upstream: "http://69.187.22.138:82/", host: "www.google.com"

那为什么我的本地file变量 nil ?当我使用 bash 打开 Lua 控制台时,我能够打开/创建一个新的本地文件并向其中写入文本,而不会出现任何问题。

那我做错了什么?起初我认为这可能是一些权限问题,nginx 无法在当前工作目录中写入文件,但据我了解 nginx以根用户身份运行。我尝试了像 /home/myusername/NGINX.txt 这样的绝对路径, 它仍然失败并显示 nil文件。我无法得到关于为什么 file 的更具体的错误是nil .

那我做错了什么?

最佳答案

如果无法打开文件,io.open 将返回 nil。您可以检索错误消息:

local file, err = io.open("TEST.txt", "w+b")
if file == nil then
print("Couldn't open file: " .. err)
else
file:write(resp_body)
file:close()
end

关于http - 使用 Nginx Lua 模块写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169712/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com