We want to change the value of an incoming header in case it matches a specific value

Hello,

We want to change the value of an incoming header in case it matches a specific value.

And we have tried a few things but we were not succesfull.

In our last tries we have used a goto template like:
ex:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: api-version-header
spec:
  headers:
    customRequestHeaders:
      User-Agent: |-
        {{ if eq .Request.Header.Get "Content-Type" "My Custom User Agent" }}
          custom-value-1
        {{ else }}
          custom-value-2
        {{ end }}

But when we are trying requests we are getting a 500 error message.
{"level":"debug","msg":"'500 Internal Server Error' caused by: net/http: invalid header field value "{{ if eq .Request.Header.Get \"Content-Type\" \"My Custom User Agent\" }}\n custom-value-1\n{{ else }}\n custom-value-2\n{{ end }}" for key User-Agent","time":"2023-02-22T15:03:10Z"}

But if put only the value without the if , then it works, ex:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: api-version-header
spec:
  headers:
    customRequestHeaders:
      User-Agent: |-
          custom-value-1

Can't we add logical conditions like if in the temaplate ?

If not , is there is any other way to set a specific value on a request header depending on the value of the request header ?

Thanks.

I don’t think that is possible. If I remember correctly the go template strings are just evaluated during startup, you can’t create „dynamic“ variables.

At least I haven’t seen anything like it during the last half year in this community forum.

Is anyone aware of a plugin that can help with the above ?

Or if someone know another strategy to change the value of a header based on the header value ?

Different approach: I think the routers rule can use headers, even with RegExp. So you could setup different routers with different re-write middleware, depending on headers.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.