Build a locally trusted HTTPs server with Golang & mkcert in 20 mins

Ken
IT Wonders Web

--

Golang is a statically typed, compiled programming language developed by Google. We have utilized Golang as the backend API server, operating within Docker and orchestrated by Kubernetes. The compilation process of Golang programs is swift, making it easy to compile for various operating system platform

Today, our objective is to construct a simple HTTPS server.

Before diving into the creation of our own HTTPS server, it’s beneficial to explore alternatives such as ngrok and localtunnel. Ngrok, a popular choice, enables you to expose a web server from your local machine to the internet. However, free accounts may have bandwidth limitations. Ngrok proves useful for testing sites requiring internet accessibility, such as Google Captcha. Neverthess, running your local HTTPS erver with locally trusted certificates provides absolute freedom for your desired configurations.

The challenge in running your HTTPS server lies in the need to generate locally trusted certificates. Additionally, configuring your browser to trust SSL certificates is necessary, as they may not be present in its trusted list of root stores. Thankfully, the mkcert project addresses this issue with just a few command lines. Mkcert establishes and installs a local Certificate Authority (CA) in the system root store, subsequently generating locally trusted certificates for the specified domain.

To install mkcert

## macOS
brew install mkcert
brew install nss # if you use Firefox
## Ubuntu
sudo apt install libnss3-tools
brew install mkcert
## Add mkcert to your local root CAs
mkcert -install

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 prepared to construct a simple Golang HTTPS file server. The golang application will serve the current directory as a File Server. You have the flexibility to specify the directory path and filename of the certificate and command-line 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 are welcomed.

This blog was originally written in this page.

--

--