Certmagic; Automagic HTTPS for Golang

Nov 30, 2019 | Golang

Certmagic is a Golang library which allows to user to easily and automatically setup HTTPS on their application. So easy, that it can be done within a single line of code. Sounds crazy, doesn’t it? Well, let’s give it a try and see how well it works. For this review, I will be hosting it on the subdomain certmagic of this site.

Setup

I am going to glance over the setting up of the actual domain for this post, but the important part of this is that I have DNS set up correctly, and have a remote Linux host setup and running. Now, I just need to deploy the code to this host and see what happens, here is the code I used.

package main

import(
	"net/http"

	"github.com/gorilla/mux"
	"github.com/mholt/certmagic"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
		w.Write([]byte("Hello world"))
	}).Methods("GET", "OPTIONS")
	certmagic.HTTPS([]string{"certmagic.modulesafari.com"}, router)
}

As you can see, the Go code is extremely simple, the call to Certmagic that initiates all of the logic to get the cert is a very simple one-liner, and can handle multiple domains.

Execution

So, I put this code on the server, compiled it, and then ran it. Within 10 seconds, it had already completed the acme-challenge and obtained a certificate. That is very impressive! I was expected to have the time to get a cup of coffee. I barely had time to get out of my chair.

golang certmagic output

Of course, I had to check in the browser to make sure, and behold, it’s alive!

certmagic browser https

So, would I use Certmagic in production Golang services? It depends. I don’t imagine this being an effective solution if you are behind a load balancer. It also won’t work automagically if you are behind Cloudflare, I tried. The place were it really shines is when you have a very small service that you want to be secure. It is great for when you just want it to work on its own and not have to worry about it. It is definitely worth checking out, which you can do here. Props to mholt for such a cool library!

linux ulimits

Learn how to set ulimit on Linux

Often times you will need to increase the maximum number of file descriptors in order to achieve proper functionality of your application. Perhaps you have a database or have run into the "Too many open files" error. In this tutorial, we will go over increasing this...
logrus

Logrus; a structured logger for Go

Logrus is a structured logger for Golang, which offers modularity, flexibility, and compatibility (github). Most projects can switch over to using logrus with a single Linux command. With an incredibly small learning curve and a plethora of extensions, logrus could be...