2016-12-15 136 views
1

我與Nginx Lua module試驗的文件。目前,我的目標僅僅是將某些HTTP響應保存到磁盤上的本地文件。寫入使用Nginx的Lua的模塊

閱讀一些教程後,我的理解是,我可以用body_filter_by_lua指令做到這一點。我的方法是簡單地在nginx.conf文件中嵌入一些Lua代碼,從ngx.arg中檢索響應主體,然後使用標準Lua io工具將其寫入磁盤。

我從來沒有在Lua編程之前,但我已經在其他腳本語言如Python編程廣泛,所以我發現它很容易學習的Lua的基本知識。

不過,我的方法不起作用,而nginx error.log表示問題是我打開的file對象是nil

這裏是Lua代碼我放在nginx.conf文件中(編輯爲清楚起見):

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以root身份運行。我嘗試了一個絕對路徑,如/home/myusername/NGINX.txt,但它仍然失敗,出現nil文件。我無法得到關於爲什麼filenil的更具體的錯誤。

那麼我做錯了什麼?

回答

0

不上的Lua但在我dabling的專家,我拿起某處包「io.open」調用「斷言」功能。 See docs on assert

local file = assert(io.open("TEST.txt", "w+b"), "Inaccessible file") 

這可能只是確認這是代碼失敗的地方。看着那行,我不知道該「B」模式是什麼「W + B」

您的意思是覆蓋在io.open("TEST.txt", "w")或追加在io.open("TEST.txt", "a")

如果您使用這些測試並仍然出現錯誤,則表示該文件實際上未被訪問。