Skip to content

Commit ff96b1f

Browse files
committed
perf(http_proxy): small optimization to avoid unnecessary allocation
1 parent ebe3e15 commit ff96b1f

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

gateway/src/apicast/http_proxy.lua

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
local format = string.format
22
local tostring = tostring
3+
local ngx = ngx
34
local ngx_get_method = ngx.req.get_method
45
local ngx_http_version = ngx.req.http_version
6+
local ngx_req_get_headers = ngx.req.get_headers
57

68
local resty_url = require "resty.url"
79
local url_helper = require('resty.url_helper')
@@ -49,9 +51,10 @@ local function forward_https_request(proxy_uri, uri, proxy_opts)
4951
local sock
5052
local opts = proxy_opts or {}
5153
local req_method = ngx_get_method()
52-
local encoding = ngx.req.get_headers()["Transfer-Encoding"]
54+
local headers = ngx_req_get_headers(0, true)
55+
local encoding = headers["Transfer-Encoding"]
5356
local is_chunked = encoding and encoding:lower() == "chunked"
54-
local content_type = ngx.req.get_headers()["Content-Type"]
57+
local content_type = headers["Content-Type"]
5558
local content_type_is_urlencoded = content_type and content_type:lower() == "application/x-www-form-urlencoded"
5659
local raw = false
5760

@@ -123,6 +126,7 @@ local function forward_https_request(proxy_uri, uri, proxy_opts)
123126
end
124127

125128
ngx.req.set_header("Content-Length", tostring(contentLength))
129+
headers["Content-Length"] = tostring(contentLength)
126130
end
127131
end
128132
end
@@ -131,16 +135,16 @@ local function forward_https_request(proxy_uri, uri, proxy_opts)
131135
-- header, otherwise the upstream won't be able to read the body as it expected chunk encoded
132136
-- body
133137
if is_chunked then
134-
ngx.req.set_header("Transfer-Encoding", nil)
138+
headers["Content-Length"] = nil
135139
end
136140
end
137141
end
138142

139143
local request = {
140144
uri = uri,
141-
method = ngx.req.get_method(),
142-
headers = ngx.req.get_headers(0, true),
143-
path = format('%s%s%s', ngx.var.uri, ngx.var.is_args, ngx.var.query_string or ''),
145+
method = req_method,
146+
headers = headers,
147+
path = (ngx.var.uri or '') .. (ngx.var.is_args or '') .. (ngx.var.query_string or ''),
144148
body = body,
145149
proxy_uri = proxy_uri,
146150
proxy_options = opts
@@ -194,7 +198,7 @@ function _M.request(upstream, proxy_uri)
194198
local proxy_auth
195199

196200
if proxy_uri.user or proxy_uri.password then
197-
proxy_auth = "Basic " .. ngx.encode_base64(concat({ proxy_uri.user or '', proxy_uri.password or '' }, ':'))
201+
proxy_auth = "Basic " .. ngx.encode_base64((proxy_uri.user or '') .. ":" .. (proxy_uri.password or ''))
198202
end
199203

200204
if uri.scheme == 'http' then -- rewrite the request to use http_proxy

0 commit comments

Comments
 (0)