I created a lua script to reverse proxy requests.
I want to set http code from upstreams to ngx.status.
Currently we do like below.
===
local sock, err = ngx_socket_tcp()
local bytes, err = sock:send(req)
if err == "timeout" then
ngx.status = ngx.HTTP_GATEWAY_TIMEOUT
end
With this we can return 504 error in case we get "timeout" from upstream.
But what I want to do is to reply the http status code from upstream to the client.
Concretely I created script below.
===
function error_proc( loglevel, msg )
ngx.log(loglevel, msg)
if msg == "timeout" then
ngx.status = ngx.HTTP_GATEWAY_TIMEOUT
end
end
local host = ngx.var.target_host
local port = ngx.var.target_port
local timeout = ngx.var.target_timeout
if not port then
port = 80
end
local ssl = ngx.var.target_ssl
if not ssl then
ssl = no
end
local http = require "resty.http"
local httpc = http.new()
httpc:set_timeout(timeout)
ngx.log(ngx.DEBUG, "Connecting to " .. host .. ngx.var.request_uri)
local ok, err = httpc:connect(host, port)
if not ok then
error_proc(ngx.ERR, err)
return
end
if ssl == "on" then
ngx.log(ngx.DEBUG, "Conducting ssl handshake")
local session, err = httpc:ssl_handshake{server_name=host}
if err then
error_proc(ngx.ERR, err)
return
end
end
ngx.log(ngx.DEBUG, "Sending request to "..host)
local res, err = httpc:proxy_request()
if err then
error_proc(ngx.ERR, err)
return
end
ngx.log(ngx.DEBUG, "Transferring request from "..host.." to "..ngx.var.remote_addr)
httpc:proxy_response(res)
httpc:set_keepalive()