TLS Clients and Servers
TLS Clients and Servers
Overview
TLS protects data in transit. In Go, crypto/tls sits under net/http and raw tls.Conn. Get certificate verification right; timeouts still apply.
HTTPS server (file certs)
srv := &http.Server{Addr: ":8443", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))Custom tls.Config
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
// Certificates: []tls.Certificate{cert},
// GetCertificate: ... // SNI
// ClientAuth: tls.RequireAndVerifyClientCert, // mTLS
}
ln, err := tls.Listen("tcp", ":8443", cfg)Client verification
tr := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
// RootCAs: pool, // private PKI
// InsecureSkipVerify: true, // NEVER in production
},
ForceAttemptHTTP2: true,
}
client := &http.Client{Transport: tr, Timeout: 10 * time.Second}mTLS sketch
Server: ClientAuth: tls.RequireAndVerifyClientCert + ClientCAs.
Client: Certificates: []tls.Certificate{clientCert}.
Pinning (careful)
Pinning SPKI hashes is brittle with rotation. Prefer public CA + short-lived certs or private PKI. If you pin, automate rotation.
Rules of thumb
| Do | Don’t |
|---|---|
| MinVersion TLS1.2+ | Skip verify to “fix CI” permanently |
| Timeouts on handshake path | Unlimited dial |
| Separate server/client certs for mTLS | Reuse one cert everywhere |
Try next
mkcertlocal certs; serve HTTPS.
- Client against bad name → verify error.
- Log peer cert CN on mTLS server.