本地回覆修改
HTTP 連線管理器支援修改本地回覆,這是由 Envoy 本身傳回的回應。
功能
本地回覆內容修改
可以自訂 Envoy 傳回的本地回應內容。可以指定 mappers 清單。每個 mapper 必須有一個 filter。它可能具有以下重寫規則:一個 status_code 規則來重寫回應碼、一個 headers_to_add 規則來新增/覆寫/附加回應 HTTP 標頭、一個 body 規則來重寫本地回覆主體,以及一個 body_format_override 來指定回應主體格式。Envoy 會依照指定的順序檢查每個 mapper
,直到第一個符合為止。如果符合 mapper
,則會套用其所有重寫規則。
LocalReplyConfig 的範例
mappers:
- filter:
status_code_filter:
comparison:
op: EQ
value:
default_value: 400
runtime_key: key_b
headers_to_add:
- header:
key: "foo"
value: "bar"
append_action: OVERWRITE_IF_EXISTS_OR_ADD
status_code: 401
body:
inline_string: "not allowed"
在以上範例中,如果 status_code 為 400,則會將其重寫為 401,回應主體會重寫為「not allowed」。
本地回覆格式修改
可以自訂回應主體的內容類型。如果未指定,則內容類型為 plain/text。有兩個 body_format
欄位;一個是 body_format 欄位,位於 LocalReplyConfig 訊息中,另一個則是 mapper
中的 body_format_override 欄位。後者僅在其 mapper 符合時才會使用。如果沒有任何符合的 mapper,或是符合的 mapper 沒有指定 body_format
,則會使用前者。
本地回覆格式可以指定為 SubstitutionFormatString。它支援 text_format 和 json_format。
選擇性地,可以透過 content_type 欄位進一步修改 content-type。如果未指定,則 text_format 的預設 content-type 為 text/plain
,而 json_format 的預設 content-type 則為 application/json
。
具有 body_format
欄位的 LocalReplyConfig 範例。
mappers:
- filter:
status_code_filter:
comparison:
op: EQ
value:
default_value: 400
runtime_key: key_b
status_code: 401
body_format_override:
text_format: "<h1>%LOCAL_REPLY_BODY% %REQ(:path)%</h1>"
content_type: "text/html; charset=UTF-8"
- filter:
status_code_filter:
comparison:
op: EQ
value:
default_value: 500
runtime_key: key_b
status_code: 501
body_format:
text_format: "%LOCAL_REPLY_BODY% %RESPONSE_CODE%"
在以上範例中,第一個 mapper
內有一個 body_format_override
,其篩選器會比對 status_code == 400
。它會透過將 %LOCAL_REPLY_BODY% 與 :path
請求標頭串連,以純文字格式產生回應主體。它僅在比對到第一個 mapper 時才會使用。在設定檔的底部以及與欄位 mappers
相同的層級,有一個 body_format
。當沒有比對到任何 mapper,或比對到的 mapper 沒有指定其自己的 body_format_override
時,會使用此欄位。