This week, I launched a new application, having bought a domain, setup a load balancer with an SSL certificate etc.
Unfortunately my new Go app didn’t have a feature to redirect the user from HTTP to HTTPS automatically, meaning that it was possible for the user to send data without it being encrypted.
I needed my Go app to detect when the user was accessing the system over HTTP and get them to use HTTPS instead so I created some middleware to do it.
This is straightforward if the Go app is handling SSL itself, but in my case, I had the extra complexity of using an AWS Elastic Load Balancer (ELB) to manage the SSL for me – meaning that the Go application just sees incoming traffic.
The AWS ELB adds a HTTP header called X-Forwarded-Scheme to request which I can use to determine whether the incoming request was HTTP or HTTPS. So I used the http://www.gorillatoolkit.org/pkg/handlers#ProxyHeaders middleware to collect the value and pass it to the
http.Request struct (
r.URL.Scheme) making my middleware work for both scenarios.
Since I always want people to use HTTPS to access the system, I also added a HSTS header which sets user’s browsers to automatically use HTTPS, even when presented with a HTTP URL in the future.
You can use it in your projects by the usual method of
go get github.com/a-h/hsts – work with me on it at https://github.com/a-h/hsts