How to Deploy Free HTTPS with Go and Let’s Encrypt (Step‑by‑Step Guide)
This article explains why HTTPS is essential, compares third‑party and self‑managed TLS options, and provides a complete Go implementation using Let’s Encrypt’s autocert library, including code for certificate handling, HTTP‑to‑HTTPS redirection, DNS requirements, and caching strategies.
Why Use HTTPS?
HTTPS encrypts traffic between browsers and servers, protects passwords, improves page‑load speed, boosts SEO, and satisfies modern browsers that reject plain HTTP.
Using Third‑Party HTTPS Providers
Services such as CloudFlare offer free HTTPS proxying: configure your domain to use CloudFlare’s DNS, set the SSL mode to “Flexible”, enable “Always Use HTTPS”, and point the proxy to your server’s IP. Other providers (AWS, Google Cloud, etc.) also supply free TLS for hosted servers, and reverse‑proxy solutions like Caddy can add HTTPS support.
Direct HTTPS with Let’s Encrypt
Let’s Encrypt is a nonprofit CA that issues free certificates via an HTTP API, allowing automated renewal. The Go standard library provides two useful packages; the author prefers golang.org/x/crypto/acme/autocert, maintained by core Go developers.
const (
htmlIndex = `Welcome!`
inProduction = true
)
func handleIndex(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, htmlIndex)
}
func makeHTTPServer() *http.Server {
mux := &http.ServeMux{}
mux.HandleFunc("/", handleIndex)
return &http.Server{ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 120 * time.Second, Handler: mux}
}
func main() {
var httpsSrv *http.Server
if inProduction {
dataDir := "."
hostPolicy := func(ctx context.Context, host string) error {
allowedHost := "www.mydomain.com"
if host == allowedHost { return nil }
return fmt.Errorf("acme/autocert: only %s host is allowed", allowedHost)
}
httpsSrv = makeHTTPServer()
m := autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: hostPolicy, Cache: autocert.DirCache(dataDir)}
httpsSrv.Addr = ":443"
httpsSrv.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate}
go func() { log.Fatalf("httpsSrv.ListenAndServeTLS() failed with %s", httpsSrv.ListenAndServeTLS("", "")) }()
}
httpSrv := makeHTTPServer()
httpSrv.Addr = ":80"
log.Fatalf("httpSrv.ListenAndServe() failed with %s", httpSrv.ListenAndServe())
}Key points:
HTTPS uses port 443; you can run HTTP, HTTPS, or both.
The server will request a certificate from Let’s Encrypt if none is present.
Let’s Encrypt limits requests to 20 per week per domain, so caching certificates (e.g., with autocert.DirCache) is essential.
Caching can be backed by a file system, SQL database, or Redis.
Correct DNS Setup
Let’s Encrypt validates domain ownership via DNS challenges, so the domain must resolve to your server’s public IP. Local testing is difficult; tools like ngrok can expose a local server for validation.
Understanding HostPolicy
HostPolicy restricts which hostnames the server may obtain certificates for, preventing unnecessary requests to Let’s Encrypt.
Skipping HTTPS in Local Tests
When testing locally, avoid binding to port 443 and skip HTTPS startup; use a flag (e.g., inProduction) to control this behavior.
Redirecting HTTP to HTTPS
Once HTTPS is operational, redirect all HTTP traffic to HTTPS for security and SEO benefits.
func makeServerFromMux(mux *http.ServeMux) *http.Server {
return &http.Server{ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 120 * time.Second, Handler: mux}
}
func makeHTTPToHTTPSRedirectServer() *http.Server {
handleRedirect := func(w http.ResponseWriter, r *http.Request) {
newURI := "https://" + r.Host + r.URL.String()
http.Redirect(w, r, newURI, http.StatusFound)
}
mux := &http.ServeMux{}
mux.HandleFunc("/", handleRedirect)
return makeServerFromMux(mux)
}
func main() {
httpSrv := makeHTTPToHTTPSRedirectServer()
httpSrv.Addr = ":80"
fmt.Printf("Starting HTTP server on %s
", httpSrv.Addr)
log.Fatalf("httpSrv.ListenAndServe() failed with %s", httpSrv.ListenAndServe())
}Where Do Free Certificates Come From?
Certificates prove a site’s identity as well as encrypt traffic. Trusted Certificate Authorities (CAs) verify ownership, a process that costs money and manpower. To avoid monopolistic pricing, a handful of companies fund Let’s Encrypt, which automates issuance of free, domain‑validated certificates.
Author: SSLChina Source: FreeBuf.COM
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
