Build a locally trusted HTTPs server with Golang & mkcert in 20 mins
Golang is a statically typed, compiled programming language developed by Google. We have been using Golang as the backend API server running in docker & orchestrated by Kubernetes. The compilation of Golang program is fast, and is easy to compile it for different OS platforms.
Today, our task is to build a simple HTTPS server.
Before diving into building our own HTTPS server, you may also take a look at ngrok, localtunnel and etc. Ngrok is a popular option that allows you to expose a web server running on your local machine to the internet. For free account, there's limitation on the bandwidth that you can use. Ngrok is useful to use to test site that needs to be accessible from internet, for example, Google captcha. Nevertheless running your local HTTPS server with locally trusted cert give you absolute freedom to do whatever you wanted.
The pain of running your HTTPS server is that you have to generate a locally trusted certificates, and you also have to configure your browser to trust the SSL certificates, since it is not in its trusted list of root store. Thanks to mkcert project, it solves this problem with just a single command line. Mkcert creates and installs a local CA in the system root store, then generates locally-trusted certificates.
To install mkcert
## macOS
brew install mkcert
brew install nss # if you use Firefox
## Ubuntu
sudo apt install libnss3-tools
brew install mkcert
Once it is installed you can generate the certificate with (for example, said the domain to use is test.iw.com.
mkcert test.iw.com
This will generate two files
test.iw.com-key.pem (SSL key)
test.iw.com.pem (SSL certificate)
Configure your /etc/hosts to indicate that test.iw.com should be resolved locally. Add this line127.0.0.1 test.iw.com to the bottom of that file. With this, we are ready to build a simple golang HTTPS file server. The golang will serve current directory as a File Server. You can specify the directory path and filename of the certificate as arguments.
To build the program,
go build main.go
To run the program,
./main -d your-ssl-dir -c your-crt-pem-filename
You can now browse
https://test.iw.com
Note: if your directory contains index.html then it will be rendered (instead of showing the directory file list).
The source code is also available at the github.
Thanks for reading. Feedbacks & comments is welcomed.
Posted on Dec 07, 2020
Leave a comment or suggestion below