跳到主要内容

响应 x-request-id

背景

有时希望在响应头中返回请求头中的 x-request-id,以便于跟踪请求,这时我们可以利用 EnvoyFilter 来实现。

EnvoyFilter

response-request-id.yaml
apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
name: response-request-id
namespace: istio-system # istio-system 表示针对所有命名空间生效
spec:
workloadSelector: # 选中所有 ingressgateway
labels:
istio: ingressgateway # 所有 ingressgateway 都带此 label
configPatches:
- applyTo: HTTP_FILTER
match:
context: GATEWAY
listener:
filterChain:
filter:
name: "envoy.filters.network.http_connection_manager"
subFilter:
name: "envoy.filters.http.router"
patch:
operation: INSERT_BEFORE
value:
name: envoy.lua
typed_config:
"@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
inlineCode: |
function envoy_on_request(handle)
local metadata = handle:streamInfo():dynamicMetadata()
local headers = handle:headers()
local rid = headers:get("x-request-id")
if rid ~= nil then
metadata:set("envoy.filters.http.lua", "req.x-request-id", rid)
end
end
function envoy_on_response(handle)
local metadata = handle:streamInfo():dynamicMetadata():get("envoy.filters.http.lua")
local rid = metadata["req.x-request-id"]
if rid ~= nil then
handle:headers():add("x-request-id", rid)
end
end

效果

$ curl -I https://imroc.cc/istio
HTTP/2 200
server: istio-envoy
date: Wed, 15 Nov 2023 03:39:31 GMT
content-type: text/html
content-length: 37698
last-modified: Sat, 14 Oct 2023 01:02:42 GMT
etag: "6529e8b2-9342"
accept-ranges: bytes
x-envoy-upstream-service-time: 5
x-request-id: 712fd33d-5dd8-441b-aac7-0280de975a85
vary: Accept-Encoding