Create a Reverse Proxy with Golang

Zhimin Wen
3 min readMar 31, 2024
Image by joffi from Pixabay

To let IBM API connect work properly, I need to supply the client ID in the request header based the user name or the client certificate, then redirect the traffic to it. It sounds a task for the dedicated reverse proxy software Nginx or Traefik to perform. However, let’s explore to achieve that with Golang.

Single Host Reverse Proxy

Thanks to Golang standard library, a out of box single host reverse proxy can be easily implemented,

rp := httputil.NewSingleHostReverseProxy(targetUrl)
rp.ServeHTTP(w, r)

This code is to be inserted in the standard HTTP handler. The “single host” here refers to the functionality more towards to reverse proxy, no load balancing feature is provided.

It fits my requirement perfectly.

Reverse Proxy with Updated Header

I will implement a HTTP handler, read the client certificate and based on the CN name to select a Client ID value, update the it in the HTTP header and redirect the traffic to the target URL.

Give the following sample configuration.

mapping:
- name: client1-app1
certCN: user1
clientID: 2a3977e9c4dd4631c9233f2e9387a103

- name: client2-app1
certCN: user2
clientID: 939f15e518e75d3c251a1245141c1c48…

--

--