KalyanChakravarthy.net

Thoughts, stories and ideas.

HTTPS server with Go + LetsEncrypt

Getting a HTTPS server started in Go using certificates from letsencrypt is incredibly easy. Just takes 3 lines of code.

Usage

The package autocert does this for you.

go get -d golang.org/x/crypto/acme/autocert 

Use it to constructs a new listener and start a server

l := autocert.NewListener("www.example.com)
s := &http.Server{}
s.Serve(l)

Full Source

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	"golang.org/x/crypto/acme/autocert"
)

func main() {
	// 1. proxy requests
	// 2. letsencrypt based https
	// 3. read-only mode

	addr := "kalyanchakravarthy.net"

	m := mux.NewRouter()
	m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		fmt.Fprintf(w, "Hello world")
	})

	s := &http.Server{
		Handler: m,
	}

	l := autocert.NewListener(addr)

	s.Serve(l)
}