I've been using the Post-Function plugin in Kong Gateway to implement some custom logic.
Lately, a large part of it has become unnecessary, and I am left with the following configuration, which only sets a header (X-Foo-Bar) to a default value (some_hardcoded_default) when it is missing from the outgoing request:
plugins:
- name: post-function
config:
access:
- |
local foo_bar = kong.request.get_header("X-Foo-Bar")
if not foo_bar then
kong.service.request.set_header("X-Foo-Bar", "some_hardcoded_default")
end
How can I set a header in the upstream request, but only when it isn't already set?
Is there a Kong plugin which allows me to do it declaratively, instead of within a Lua script?
1 Answer 1
Yes, you can use Kong's request-transformer plugin.
Example:
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Foo-Bar:some_hardcoded_default"
The add operation will set the header only if it's not already set.
MRE (DecK)
File kong.yml
_format_version: "3.0"
services:
- name: example-service
url: http://httpbin.org
routes:
- name: example-route
paths:
- "/"
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Foo-Bar:some_hardcoded_default"
Run on Docker:
docker run --rm -it --name kong \
-e "KONG_DATABASE=off" \
-e "KONG_DECLARATIVE_CONFIG=/etc/kong/kong.yml" \
-v ./kong.yml:/etc/kong/kong.yml:ro \
-p 8000:8000 \
kong/kong-gateway
Test requests:
No header
X-Foo-Barprovided:curl localhost:8000/headersResult:
{ "headers": { "Accept": "*/*", "Host": "httpbin.org", "User-Agent": "curl/8.5.0", "X-Amzn-Trace-Id": "Root=1-68fb501e-656dc3f442a764241e81d0fa", "X-Foo-Bar": "some_hardcoded_default", "X-Forwarded-Host": "localhost", "X-Forwarded-Path": "/headers", "X-Kong-Request-Id": "e104f346f05c71495a245c0622541e06" } }Header
X-Foo-Barprovided:curl localhost:8000/headers -H "X-Foo-Bar: test"Result:
{ "headers": { "Accept": "*/*", "Host": "httpbin.org", "User-Agent": "curl/8.5.0", "X-Amzn-Trace-Id": "Root=1-68fb504d-33b193a82ada43577bf3863d", "X-Foo-Bar": "test", "X-Forwarded-Host": "localhost", "X-Forwarded-Path": "/headers", "X-Kong-Request-Id": "49399a011d655b176084f91ea8851159" } }
Custom Plugin Priority
If you specifically want to add the header just before forwarding the request to the upstream, you can use dynamic plugin ordering. Example:
_format_version: "3.0"
services:
- name: example-service
url: http://httpbin.org
routes:
- name: example-route
paths:
- "/"
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Foo-Bar:some_hardcoded_default"
ordering:
after:
access:
- post-function
NB: we set access phase because that's the one used by request-transformer: source code
Comments
Explore related questions
See similar questions with these tags.