Creating ACME certificates with Go
Daniel Nashed – 20 April 2025 08:25:24
"LEGO" is a full featured ACME implementation including DNS-01 challenges.
But if you just need a basic ACME functionality for HTTP-01 requests, there are modules available directly from Go.
"golang.org/x/crypto/acme/autocert" provides an easy to use interface, which works hand in hand with the Go web-server functionality.
The following simple program creates a certificate and starts a simple demo web-server.
This brings ACME directly into your application without any extra tools if you are working with Go.
Reference:
https://pkg.go.dev/golang.org/x/crypto/acme/autocert
package main
import (
"crypto/tls"
"log"
"net/http"
"os"
"net"
"strings"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
)
func main() {
szHostname, err := os.Hostname()
if err != nil {
log.Println ("Error getting hostname:", err)
return
}
szFQDN, err := net.LookupCNAME(szHostname)
if (err == nil) {
szHostname = strings.TrimSuffix (szFQDN, ".");
}
log.Println ("Local Hostname: ", szHostname)
manager := &autocert.Manager{
Cache: autocert.DirCache("certs"), // Local cert cache
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist (szHostname),
Client: &acme.Client{
DirectoryURL: "https://acme-staging-v02.api.letsencrypt.org/directory",
},
}
server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
GetCertificate: manager.GetCertificate,
},
Handler: http.HandlerFunc (func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte ("Hello, Staging HTTPS world!"))
}),
}
// Redirect HTTP to HTTPS
go func() {
log.Fatal (http.ListenAndServe (":80", manager.HTTPHandler(nil)))
}()
log.Println ("Starting HTTPS server with Let's Encrypt staging certs...")
log.Fatal (server.ListenAndServeTLS("", ""))
}
- Comments [0]