AddRequestHeader插件

AddRequestHeader插件可以在HTTP请求响应返回指定的若干状态码时,在响应头中增加请求头的内容。

前提条件

配置字段

名称

数据类型

填写要求

默认值

描述

status_codes

string array

必填

-

该参数要求输入一组特定的请求响应码(如200404503等),当请求返回的状态码是指定状态码之一时,响应头中将增加对应请求头内容。

patch_context

string

必填

-

插件的可用范围。有两个取值:

  • GATEWAY:插件将只能生效至网关。

  • ANY:插件可生效至网关与Sidecar。

配置示例

在请求成功时令网关返回请求头

通过配置如下参数,插件能够使网关在请求成功(返回响应码200)时在响应头中打印请求头信息

status_codes: 
  - "200"
patch_context: GATEWAY

选择插件的生效范围为网关生效,并选择生效至网关ingressgateway

  1. 测试返回200状态码。

    curl -H "user: test" -I {网关ip地址}/status/200

    预期输出:

    HTTP/1.1 200 OK
    host: 121.40.XXX.XX
    server: istio-envoy
    date: Thu, 16 Jun 2022 07:58:05 GMT
    content-type: text/html; charset=utf-8
    access-control-allow-origin: *
    access-control-allow-credentials: true
    content-length: 0
    x-envoy-upstream-service-time: 2
    accept: */*
    user: test
    x-forwarded-for: 10.0.0.130
    x-forwarded-proto: http
    x-envoy-internal: true
    x-request-id: 4e284975-fa1d-41c4-9676-9785c83e7385
    user-agent: curl/7.79.1

    可以看到,当网关返回200状态码时,响应头中带有了自定义请求头user: test

  2. 测试返回400状态码。

    curl -H "user: test" -I {网关ip地址}/status/400

    预期输出:

    HTTP/1.1 400 Bad Request
    server: istio-envoy
    date: Thu, 16 Jun 2022 07:58:09 GMT
    content-type: text/html; charset=utf-8
    access-control-allow-origin: *
    access-control-allow-credentials: true
    content-length: 0
    x-envoy-upstream-service-time: 9

    可以看到,返回400时,响应头中无请求头信息。

为特定服务配置请求返回400时返回请求头信息

AddRequestHeader插件除生效至网关外,也可生效至任意指定服务,此时patch_context参数需要配置为ANY。为插件配置以下参数:

status_codes: 
  - "400"
  - "503"
patch_context: ANY

其中,status_codes参数中可以任意添加其它常见的错误状态码。 选择插件的生效范围为工作负载生效,并选择生效至default命名空间下的Servicehttpbin。 执行一下命令,通过Sleep服务来直接向httpbin服务发起请求。

kubectl exec -it deploy/sleep -- curl -H "user: test" -I httpbin:8000/status/400

预期输出:

HTTP/1.1 400 Bad Request
host: httpbin:8000
server: envoy
date: Thu, 16 Jun 2022 08:**:** GMT
content-type: text/html; charset=utf-8
access-control-allow-origin: *
access-control-allow-credentials: true
content-length: 0
x-envoy-upstream-service-time: 13
accept: */*
user: test
x-forwarded-proto: http
x-request-id: 1780766e-8273-4703-8902-6a513eb6bcfc
x-envoy-attempt-count: 1
x-forwarded-client-cert: By=spiffe://cluster.local/ns/default/sa/httpbin;Hash=bb3ab9200f3ce3e1b53493ddf701838d6d3538167ff6613d2ec319d4872c8966;Subject="";URI=spiffe://cluster.local/ns/default/sa/sleep
user-agent: curl/7.83.1-DEV

可以看到,当httpbin服务返回400状态码时,响应头中带有了自定义请求头user: test