Skip to content

HTTP/2, HTTPS, TLS & mTLS in Go; Benchmarking with wrk and h2load ​

"TLS allows client/server applications to communicate over the Internet in a way that is designed to prevent eavesdropping, tampering, and message forgery." — RFC 8446, "The Transport Layer Security (TLS) Protocol Version 1.3", Abstract (E. Rescorla, August 2018)

Summary: In Go, HTTPS is crypto/tls plus net/http: a tls.Config decides which certificates, versions, key exchanges and client-certificate policy a connection uses, ALPN picks HTTP/2 or HTTP/1.1 inside the handshake, and the standard library speaks HTTP/2 over TLS without extra code. This page covers the server and client side, mutual TLS, certificate issuance and rotation, the failure modes you will read in logs, and how to measure a TLS server honestly with wrk and h2load. Focus: tls.Config fields, MinVersion TLS 1.2 and TLS 1.3, cipher suites and curves (including the post-quantum hybrid X25519MLKEM768), PEM certificates and ListenAndServeTLS, mkcert for local development, ACME, Let's Encrypt and autocert, ALPN and automatic HTTP/2, h2c and http.Protocols, HTTP/3 with quic-go, TLS termination at a proxy versus in Go, HTTP to HTTPS redirects and HSTS, mTLS on both sides with ClientAuth, ClientCAs, VerifyConnection and SPIFFE identities, rotation with GetCertificate and GetConfigForClient, tls.Dial, why InsecureSkipVerify is dangerous, session tickets and 0-RTT, OCSP stapling, Encrypted Client Hello, debugging with openssl s_client, curl -v, GODEBUG and key logs, server timeouts under load, and benchmarking with wrk, h2load, hey, oha and vegeta. Learning goal: Stand up an HTTPS service that negotiates HTTP/2, verifies its peers, renews its certificates without a restart, reads a handshake failure and knows which side caused it, and produce a benchmark whose numbers you can defend.

This page owns TLS and HTTP/2 as the Go standard library and its satellite modules expose them. It does not re-teach its neighbours: the HTTP server and client basics, routing and timeouts in context are in net/http, hashing, HMAC and symmetric and asymmetric primitives in hashing & crypto, graceful shutdown and signals in OS Processes, Signals & Graceful Shutdown, cancellation and deadlines in context, how TLS works on the wire and how to operate certificates in general in TLS in practice and Cryptography fundamentals, the history of HTTP/1.1, HTTP/2 and HTTP/3 as protocols in HTTP evolution, service-to-service identity as an architecture in mTLS service security, PKI and secrets management in Cryptography, TLS, PKI & secrets, and load balancer placement in Load balancing. Rate limiting and tail latency under overload are in Rate limiting in Go and Latency budgets & tail latency.

Facts below were checked against the Go 1.27 standard-library source on go.dev (crypto/tls, net/http, crypto/x509, net/http/pprof; pkg.go.dev returns 403 to scripted fetches), the Go 1.6, 1.8, 1.12, 1.13, 1.14, 1.15, 1.17, 1.18, 1.21 to 1.27 release notes, the golang.org/x/net/http2 and h2c sources, golang.org/x/crypto/acme/autocert, the quic-go documentation, RFC 8446, RFC 9113, RFC 7301, RFC 6797 and RFC 8470, the Let's Encrypt documentation, Mozilla's TLS guidelines (version 6.0 JSON), the wrk, wrk2, vegeta, hey and oha READMEs and the h2load manual. Snippets declare go 1.24 (they use http.Protocols, http.HTTP2Config, t.Context() and b.Loop, all 1.24) and pin golang.org/x/crypto v0.46.0, a release whose go.mod still says 1.24 (v0.54.0 and later declare 1.25). They were compiled, vetted and tested with Go 1.27.4 on macOS; the demo program, curl and openssl outputs in the lab are real. wrk and h2load are not installed on the build machine, so their outputs are marked "expected, not run".

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why a plain HTTP server is not enoughWhy it exists
Which Go release added whatWhere it comes from
A before/after client and serverGo
TLS in crypto/tls, tls.Config (Server, Client, Conn)TLS in crypto/tls
MinVersion TLS 1.2/1.3Versions
cipher suites, curves, post-quantum key exchangeCipher suites and curves
certificates and keys (PEM), ListenAndServeTLSCertificates and keys
local dev certs (mkcert)Local dev certificates
autocert (golang.org/x/crypto/acme/autocert) and ACME, Let's EncryptACME and autocert
HTTP/2 (enabled by default over TLS, h2c, golang.org/x/net/http2, settings, server push removed), ALPNHTTP/2 in Go, HTTP/2 mechanics (push: browsers dropped it, http.Pusher remains), h2c
HTTP/3 (quic-go, not stdlib)HTTP/3
TLS termination at proxy vs in GoTLS termination
redirect 80→443, HSTSRedirect and HSTS
mTLS server side (ClientAuth RequireAndVerifyClientCert, ClientCAs, VerifyPeerCertificate, VerifyConnection, SAN/SPIFFE identity)mTLS server side, Workload identity
mTLS client side (Certificates, RootCAs)mTLS client side
certificate rotation (GetCertificate, GetConfigForClient)Rotation
tls.Dial, probing a hosttls.Dial
InsecureSkipVerify dangersInsecureSkipVerify
session resumption/tickets, 0-RTTSession resumption
OCSP stapling, revocation, CRLsOCSP stapling
Encrypted Client Hello (Go 1.23/1.24)Encrypted Client Hello
crypto/tls debugging (openssl s_client, curl -v, GODEBUG), key logsDebugging
server timeouts under load (Slowloris, handshake timeouts, limits)Server timeouts under load
benchmarking with wrk and h2load (flags, interpreting latency percentiles, keep-alive)Benchmarking
vegeta/hey/oha comparisonOther load tools
GOMAXPROCS and connections, file descriptors, pprof while benchmarkingTuning and profiling
Verbatim error messages and what they meanMechanics
The classic problems and fixesSolving the classic problems
What to use whenChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Laravel, Nginx and PHP-FPM comparisonFor PHP/Laravel developers

Everything in one minute ​

The stack, bottom to top. Every row is unpacked in the concept catalogue.

LayerWhat happensGo APIPlain words
TCPA reliable byte stream is openednet.Dial, net.Listen"A phone line"
TLS handshakeVersions, key exchange, certificate checked, keys derivedtls.Config, tls.Server, tls.Client"Show ID, agree on a secret"
ALPNThe application protocol is agreed inside the handshakeConfig.NextProtos, ConnectionState.NegotiatedProtocol"Which language do we speak: h2 or http/1.1?"
HTTP/2 or HTTP/1.1Requests and responses on the protected streamnet/http"The conversation"
(Alternative) QUICTLS 1.3 inside UDP, HTTP/3 on topgithub.com/quic-go/quic-go/http3"A different phone line"

The tls.Config fields you will touch.

FieldSideDefaultPlain words
Certificates, GetCertificate, GetConfigForClientServernone: one of them is requiredWhich certificate to show
MinVersion / MaxVersionBothTLS 1.2 / TLS 1.3Oldest and newest protocol version allowed
CipherSuitesBothsafe list, may changeTLS 1.0 to 1.2 suites only; TLS 1.3 suites are fixed
CurvePreferencesBothincludes X25519MLKEM768 since Go 1.24Which key exchanges are enabled
NextProtosBothset by net/httpALPN list in order of preference
ClientAuth, ClientCAsServerNoClientCertDemand and verify client certificates
RootCAs, ServerNameClientsystem roots, host from the URLWhom to trust and which name to check
Certificates / GetClientCertificateClientnoneThe client's own certificate for mTLS
VerifyPeerCertificate, VerifyConnectionBothnilYour own checks after the built-in ones
InsecureSkipVerifyClientfalseTurn verification off (dangerous)
SessionTicketsDisabled, SetSessionTicketKeysServertickets on, keys rotated dailySession resumption
KeyLogWriterBothnilWrite secrets for Wireshark (debugging only)
EncryptedClientHelloKeys / EncryptedClientHelloConfigListServer / clientnilEncrypted Client Hello

HTTP versions in Go.

ProtocolTransportNeedsIn the standard library?Switch
HTTP/1.1TCP (+ TLS)nothingYesServer.Protocols, Transport.Protocols
HTTP/2 over TLS (h2)TCP + TLS + ALPNa TLS config that does not disable itYes, automatic since Go 1.6same, or GODEBUG=http2server=0
HTTP/2 without TLS (h2c)TCPprior knowledge or upgradeYes since Go 1.24 (UnencryptedHTTP2)Protocols.SetUnencryptedHTTP2
HTTP/3 (h3)UDP + QUICa QUIC libraryNo: github.com/quic-go/quic-gohttp3.Server

The load tools in one row each.

ToolProtocolsModelPercentilesPick it when
wrkHTTP/1.1Closed loop, threads and connections--latencyMaximum raw throughput on one box
wrk2HTTP/1.1Open loop, constant rate -RCorrected for coordinated omissionHonest latency at a fixed rate
h2loadh2, h2c, HTTP/1.1, h3Closed loop, -c clients, -m streams, optional --rpsmin, max, mean, sd, median, p95, p99HTTP/2 specifics: streams, header compression, TLS resumption
heyHTTP/1.1, HTTP/2Closed loop, -c workers, optional -q per workerDistribution and histogramA quick check from a laptop
ohaHTTP/1.1, HTTP/2, -p parallel streamsClosed loop, optional -q with --latency-correctionYesA friendly TUI, HTTP/2 aware
vegetaHTTP/1.1, -http2, h2cOpen loop, constant -rateYes, plus histogramsFixed arrival rate, reports you can replay

The errors you will read.

TextWhereMeaningFirst fix
x509: certificate signed by unknown authority (macOS: certificate is not trusted)clientThe client does not trust the issuerAdd the CA to RootCAs; do not skip verification
x509: certificate is valid for a.example, not b.exampleclientName not in the SANReissue with the right SAN or fix ServerName
tls: failed to verify certificate: ...clientWrapper around the x509 reasonRead the wrapped error
http: TLS handshake error from 10.0.0.5:5124: remote error: tls: bad certificateserver logThe client rejected your certificateLook at the client's error
tls: client didn't provide a certificateserver logmTLS required, none sentGive the client a certificate
http: server gave HTTP response to HTTPS clientclienthttps:// to a plain portFix the scheme or the port
Client sent an HTTP request to an HTTPS server.HTTP 400 body (the log says client sent an HTTP request to an HTTPS server)http:// to a TLS portFix the scheme or add a redirect listener
tls: client requested unsupported application protocolsserver logALPN lists do not intersectAlign NextProtos

Why it exists ​

A plain HTTP request travels through routers, Wi-Fi access points and proxies that can read it, change it and replay it. Passwords, session cookies and API tokens in the clear are an invitation. TLS fixes three things at once: confidentiality (nobody on the path can read the bytes), integrity (nobody can change them unnoticed) and authenticity (the server proves it owns the name you asked for, and with mutual TLS the client proves who it is). Go makes the whole stack a library, so a production-grade HTTPS server is a handful of lines and no external web server is required, which is both its strength and its danger: the defaults are good, but the shortcuts (InsecureSkipVerify, no timeouts, certificates read once at boot) are one line each.

HTTP/2 exists because HTTP/1.1 needs many connections to do many things at once, and each of those connections pays for its own TLS handshake. HTTP/2 multiplexes many requests as streams over one connection, compresses headers with HPACK, and in practice runs only over TLS, so in Go the two topics travel together.

Plain HTTP/1.1HTTPS with HTTP/2
Readable and modifiable on the pathEncrypted and integrity protected
No proof of who answeredCertificate chain and name verified
One request at a time per connection, so clients open several connectionsMany concurrent streams on one connection
Cheap to start, no certificatesA handshake per connection, certificates to issue, renew and rotate
Easy to debug with tcpdumpNeeds curl -v, openssl s_client or a key log to read
Nothing to configuretls.Config, timeouts, ALPN, rotation, benchmarks that include the handshake

An everyday picture. A courier delivering a sealed parcel. The sealed bag is encryption. The courier showing a company badge that you can check against the company's public register is the certificate and the CA. A building that also requires the courier to be on its approved list before opening the door is mutual TLS. Resuming a session is the courier who already visited this morning being waved through with a stamp (the ticket) instead of showing the badge again. HTTP/2 is that courier delivering twenty parcels in one trip instead of twenty trips.

Three common misunderstandings, up front ​

  1. "HTTPS means the server is trustworthy." It means the connection is encrypted and that the certificate matches the name in the URL. A phishing site has a perfectly valid certificate for its own name.
  2. "InsecureSkipVerify: true just turns off the annoying error." It turns off the authentication half of TLS, so an attacker on the path can present any certificate and read everything. The traffic is still encrypted, but to the wrong party.
  3. "HTTP/2 is faster, so benchmark it with wrk." wrk speaks HTTP/1.1 only. A benchmark of an HTTP/2 server needs h2load, oha --http2, hey with an HTTP/2 URL or vegeta -http2, and it has to say how many connections and streams it used.

Where it comes from ​

SSL was Netscape's protocol; TLS standardised its successors. TLS 1.2 (RFC 5246) added modern authenticated encryption; TLS 1.3 (RFC 8446, August 2018, which obsoletes RFC 5246) removed the weak options, cut the handshake to one round trip and encrypted most of it. HTTP/2 (RFC 7540, May 2015, now RFC 9113) grew out of SPDY, and browsers implement it only over TLS; RFC 9113 says "Implementations of HTTP/2 MUST use TLS version 1.2 [TLS12] or higher for HTTP/2 over TLS". ALPN (RFC 7301) was added so that the choice between HTTP/1.1 and HTTP/2 costs no extra round trip: its introduction says it is "desirable to accomplish this negotiation without adding network round-trips". Let's Encrypt and the ACME protocol (RFC 8555, March 2019) made certificates free and automatic.

Go releaseWhat changed for this chapterSource
1.6 (Feb 2016)"Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS."go.dev/doc/go1.6
1.8 (Feb 2017)http.Pusher (HTTP/2 server push), Server.Shutdowngo.dev/doc/go1.8
1.12 / 1.13TLS 1.3 opt-in, then on by defaultgo.dev/doc/go1.12, go1.13
1.15CommonName no longer used as a host name; SANs are requiredgo.dev/doc/go1.15
1.17Cipher suite order handled by crypto/tls; Config.CipherSuites order ignoredgo.dev/doc/go1.17
1.18Clients default to TLS 1.2 minimumgo.dev/doc/go1.18
1.21SessionState, WrapSession/UnwrapSession ticket hooks; QUICConn; ErrSchemeMismatchgo.dev/doc/go1.21
1.22Servers default to TLS 1.2 minimum; RSA key exchange without ECDHE no longer offeredgo.dev/doc/go1.22
1.23Client-side Encrypted Client Hello; 3DES removed from defaults; LoadX509KeyPair fills Certificate.Leafgo.dev/doc/go1.23
1.24X25519MLKEM768 default; server-side ECH; Server.Protocols, Transport.Protocols, HTTP2Config, unencrypted HTTP/2go.dev/doc/go1.24
1.25Container-aware GOMAXPROCS; ConnectionState.CurveID; GetEncryptedClientHelloKeys; SHA-1 signatures disallowed in TLS 1.2; servers prefer the highest common versiongo.dev/doc/go1.25
1.26SecP256r1MLKEM768 and SecP384r1MLKEM1024 hybrids on by default; HTTP2Config.StrictMaxConcurrentRequestsgo.dev/doc/go1.26
1.27HTTP/2 server honours RFC 9218 priorities; ConnectionState.LocalCertificate; tls10server, tlsrsakex, tls3des, tlsunsafeekm, x509keypairleaf GODEBUG settings removedgo.dev/doc/go1.27

Go ​

Before ​

The shortcut every team writes the first time a test environment uses a certificate nobody trusts: turn verification off. The client works and the encrypted channel exists, but the client no longer checks who is on the other end. The test proves a server holding a certificate from an unknown CA, for a different name, is happily accepted.

go
// Package before shows the shortcut that silently removes TLS's main promise.
package before

import (
	"crypto/tls"
	"net/http"
	"time"
)

// NewClient "fixes" the error "x509: certificate signed by unknown authority"
// by turning verification off. Traffic is still encrypted, but to whoever
// answered: a proxy, a rogue Wi-Fi hotspot, an attacker with any certificate.
func NewClient() *http.Client {
	return &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // DANGEROUS
		},
	}
}
go
package before_test

import (
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/before"
	"academy/http2-https-tls-mtls/pki"
)

// A server holding a certificate from a CA nobody trusts, for the wrong name.
func rogueServer(t *testing.T) *httptest.Server {
	t.Helper()
	rogueCA, err := pki.NewAuthority("rogue ca")
	if err != nil {
		t.Fatal(err)
	}
	cert, err := rogueCA.IssueServer(time.Hour, []string{"evil.example.test"})
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "send your password here")
	}))
	srv.TLS = tlsConfigWith(cert)
	srv.StartTLS()
	t.Cleanup(srv.Close)
	return srv
}

func TestInsecureClientTalksToAnyone(t *testing.T) {
	srv := rogueServer(t)
	resp, err := before.NewClient().Get(srv.URL)
	if err != nil {
		t.Fatalf("the insecure client should accept the rogue certificate: %v", err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	if string(body) != "send your password here" {
		t.Fatalf("body = %q", body)
	}
}

After ​

The same conversation done properly: the server config states its policy (MinVersion, ALPN list) and leaves cipher suites and curves to Go; the client verifies against an explicit RootCAs pool and sets ForceAttemptHTTP2 because a custom TLSClientConfig otherwise switches HTTP/2 off. The tests prove the verified client gets HTTP/2 over TLS 1.3, an unknown CA is rejected with *tls.CertificateVerificationError, and the wrong server name is rejected with x509.HostnameError.

go
// Package after configures TLS the way a service should: verify the peer,
// set an explicit floor, keep the library's defaults for everything else.
package after

import (
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"time"
)

// ServerConfig is a server-side tls.Config. MinVersion is spelled out so the
// policy is visible in code review; CipherSuites and CurvePreferences stay
// nil so Go keeps choosing current defaults for you.
func ServerConfig(cert tls.Certificate) *tls.Config {
	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		MinVersion:   tls.VersionTLS12,
		NextProtos:   []string{"h2", "http/1.1"},
	}
}

// NewClient verifies the server against roots (nil means the system pool).
// ForceAttemptHTTP2 is required because a custom TLSClientConfig otherwise
// disables HTTP/2 on http.Transport.
func NewClient(roots *x509.CertPool) *http.Client {
	return &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig:     &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12},
			ForceAttemptHTTP2:   true,
			TLSHandshakeTimeout: 5 * time.Second,
		},
	}
}
go
package after_test

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/after"
	"academy/http2-https-tls-mtls/pki"
)

func start(t *testing.T) (*httptest.Server, *pki.Authority) {
	t.Helper()
	ca, err := pki.NewAuthority("test ca")
	if err != nil {
		t.Fatal(err)
	}
	cert, err := ca.IssueServer(time.Hour, []string{"api.example.test"}, []byte{127, 0, 0, 1})
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, r.Proto+" "+tls.VersionName(r.TLS.Version)+" "+r.TLS.NegotiatedProtocol)
	}))
	srv.TLS = after.ServerConfig(cert)
	srv.EnableHTTP2 = true
	srv.StartTLS()
	t.Cleanup(srv.Close)
	return srv, ca
}

func TestVerifiedClientGetsHTTP2OverTLS13(t *testing.T) {
	srv, ca := start(t)
	resp, err := after.NewClient(ca.Pool()).Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	if got, want := string(body), "HTTP/2.0 TLS 1.3 h2"; got != want {
		t.Fatalf("body = %q, want %q", got, want)
	}
}

func TestUnknownCAIsRejected(t *testing.T) {
	srv, _ := start(t)
	_, err := after.NewClient(nil).Get(srv.URL) // system roots do not contain our test CA
	var cve *tls.CertificateVerificationError
	if !errors.As(err, &cve) {
		t.Fatalf("want *tls.CertificateVerificationError, got %T: %v", err, err)
	}
	t.Logf("verification error: %v", cve.Err)
}

func TestWrongServerNameIsRejected(t *testing.T) {
	srv, ca := start(t)
	c := after.NewClient(ca.Pool())
	c.Transport.(*http.Transport).TLSClientConfig.ServerName = "other.example.test"
	_, err := c.Get(srv.URL)
	var hostErr x509.HostnameError
	if !errors.As(err, &hostErr) || !strings.Contains(hostErr.Error(), "other.example.test") {
		t.Fatalf("want x509.HostnameError naming the wrong host, got %T: %v", err, err)
	}
}

The certificates in these tests come from a throwaway CA in pki, built only from crypto/x509, so no files and no network are needed:

go
// Package pki builds a tiny in-memory certificate authority for demos and
// tests. It is not a production CA: no revocation, no name constraints.
package pki

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"math/big"
	"net"
	"net/url"
	"time"
)

// Authority is a self-signed ECDSA P-256 CA.
type Authority struct {
	Cert *x509.Certificate
	Key  *ecdsa.PrivateKey
}

func serial() *big.Int {
	n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		panic(err)
	}
	return n
}

// NewAuthority creates a CA valid for 24 hours.
func NewAuthority(commonName string) (*Authority, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          serial(),
		Subject:               pkix.Name{CommonName: commonName},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		IsCA:                  true,
		BasicConstraintsValid: true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		return nil, err
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &Authority{Cert: cert, Key: key}, nil
}

// Pool returns a cert pool that trusts only this authority.
func (a *Authority) Pool() *x509.CertPool {
	p := x509.NewCertPool()
	p.AddCert(a.Cert)
	return p
}

func (a *Authority) issue(tmpl *x509.Certificate) (tls.Certificate, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return tls.Certificate{}, err
	}
	tmpl.SerialNumber = serial()
	tmpl.KeyUsage = x509.KeyUsageDigitalSignature
	der, err := x509.CreateCertificate(rand.Reader, tmpl, a.Cert, &key.PublicKey, a.Key)
	if err != nil {
		return tls.Certificate{}, err
	}
	leaf, err := x509.ParseCertificate(der)
	if err != nil {
		return tls.Certificate{}, err
	}
	return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, nil
}

// IssueServer returns a server-auth leaf. Names go into the SAN extension;
// Go ignores the Common Name for host name checks (since Go 1.15).
func (a *Authority) IssueServer(ttl time.Duration, dns []string, ips ...net.IP) (tls.Certificate, error) {
	return a.issue(&x509.Certificate{
		Subject:     pkix.Name{CommonName: "server"},
		NotBefore:   time.Now().Add(-time.Minute),
		NotAfter:    time.Now().Add(ttl),
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		DNSNames:    dns,
		IPAddresses: ips,
	})
}

// IssueClient returns a client-auth leaf whose identity is a SPIFFE-style
// URI SAN such as spiffe://example.test/ns/prod/sa/orders.
func (a *Authority) IssueClient(ttl time.Duration, spiffeID string) (tls.Certificate, error) {
	u, err := url.Parse(spiffeID)
	if err != nil {
		return tls.Certificate{}, err
	}
	return a.issue(&x509.Certificate{
		Subject:     pkix.Name{CommonName: "client"},
		NotBefore:   time.Now().Add(-time.Minute),
		NotAfter:    time.Now().Add(ttl),
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		URIs:        []*url.URL{u},
	})
}

// PEM encodes a certificate chain and its ECDSA key as two PEM blocks,
// the format tls.LoadX509KeyPair and ListenAndServeTLS read from disk.
func PEM(c tls.Certificate) (certPEM, keyPEM []byte, err error) {
	for _, der := range c.Certificate {
		certPEM = append(certPEM, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...)
	}
	keyDER, err := x509.MarshalPKCS8PrivateKey(c.PrivateKey)
	if err != nil {
		return nil, nil, err
	}
	keyPEM = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
	return certPEM, keyPEM, nil
}

The Go angle ​

Go ships a complete TLS 1.0 to 1.3 implementation written in Go (crypto/tls), a certificate parser and verifier (crypto/x509), and an HTTP server and client that negotiate HTTP/2 through it with no additional code. There is no OpenSSL, no separate "web server" binary and no module to install for the common case; ListenAndServeTLS is the whole API. The price of a pure-Go stack is that you get Go's policy decisions: a conservative, short list of cipher suites you cannot reorder (Go 1.17 made the library own the order), post-quantum hybrid key exchange on by default since Go 1.24, no 0-RTT, no TLS compression, no renegotiation by default, and no OpenSSL-style ssl_ciphers string. Most of that is a feature; it also means TLS behaviour changes with the Go version you build with, so the release notes belong in your upgrade checklist (the timeline above is that checklist for this chapter).

The concept catalogue ​

TLS in crypto/tls Must-know ​

In plain words: crypto/tls wraps a net.Conn so that what you write is encrypted and what you read is decrypted and authenticated. A tls.Config is the policy: which certificate to show, which versions to accept, whom to trust.

Common misunderstanding: "I can tweak tls.Config while the server runs." The documentation is explicit: "After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it." To change policy per connection, return a new config from GetConfigForClient; to swap certificates use GetCertificate (Rotation); to start from an existing config, Clone() it.

Definition: tls.Server(conn, cfg) and tls.Client(conn, cfg) wrap an existing connection; tls.Listen and tls.NewListener produce a listener whose Accept returns *tls.Conn; tls.Dial, tls.DialWithDialer and tls.Dialer.DialContext open an outgoing one. The handshake is lazy: "Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically." net/http calls HandshakeContext itself, bounded by a timeout (timeouts). After the handshake, Conn.ConnectionState() reports what was negotiated.

NeedAPINotes
HTTPS server in one linehttp.ListenAndServeTLS(addr, certFile, keyFile, handler)No timeouts: fine for a demo only
HTTPS server you controlsrv := &http.Server{TLSConfig: cfg, ...}; srv.ListenAndServeTLS("", "")Empty file names when the config already has a certificate source
Raw TLS listener (a protocol that is not HTTP)tls.Listen("tcp", addr, cfg)Fails at start if Certificates, GetCertificate and GetConfigForClient are all empty
Wrap an accepted connectiontls.Server(rawConn, cfg)You call Handshake or just read
Outgoing raw TLStls.Dialer{Config: cfg}.DialContext(ctx, "tcp", addr)Context-aware; tls.Dial is not
What was negotiatedconn.ConnectionState() / r.TLS in a handlerVersion, CipherSuite, NegotiatedProtocol, DidResume, PeerCertificates, VerifiedChains, ServerName

Real scenario: a handler that logs r.TLS.Version, tls.CipherSuiteName(r.TLS.CipherSuite) and r.TLS.NegotiatedProtocol for every request tells you in a week which of your clients still speak TLS 1.2 or HTTP/1.1, before you raise MinVersion.

go
// Package h2server is an HTTPS server that reports which protocol it spoke.
package h2server

import (
	"crypto/tls"
	"encoding/json"
	"net/http"
	"time"
)

// Info is what the /whoami handler returns.
type Info struct {
	Proto      string `json:"proto"`       // HTTP/1.1 or HTTP/2.0
	TLSVersion string `json:"tls_version"` // TLS 1.2 or TLS 1.3
	ALPN       string `json:"alpn"`        // h2 or http/1.1
	Cipher     string `json:"cipher"`
	SNI        string `json:"sni"`
	Resumed    bool   `json:"resumed"`
}

// Whoami reports the negotiated protocol and TLS parameters. r.TLS is nil
// when the request did not arrive over TLS.
func Whoami(w http.ResponseWriter, r *http.Request) {
	info := Info{Proto: r.Proto}
	if r.TLS != nil {
		info.TLSVersion = tls.VersionName(r.TLS.Version)
		info.ALPN = r.TLS.NegotiatedProtocol
		info.Cipher = tls.CipherSuiteName(r.TLS.CipherSuite)
		info.SNI = r.TLS.ServerName
		info.Resumed = r.TLS.DidResume
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(info)
}

// New builds a production-shaped server. With a non-nil TLSConfig, calling
// ListenAndServeTLS("", "") enables HTTP/2 automatically (Go 1.6+ for
// http.Server); the HTTP2 field (Go 1.24) tunes it without x/net/http2.
func New(addr string, h http.Handler, cfg *tls.Config) *http.Server {
	return &http.Server{
		Addr:              addr,
		Handler:           h,
		TLSConfig:         cfg,
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       90 * time.Second,
		HTTP2: &http.HTTP2Config{
			MaxConcurrentStreams:         100,
			PermitProhibitedCipherSuites: false,
		},
	}
}
go
package h2server_test

import (
	"crypto/tls"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/after"
	"academy/http2-https-tls-mtls/h2server"
	"academy/http2-https-tls-mtls/pki"
)

func get(t *testing.T, srv *httptest.Server, ca *pki.Authority, protos func(*http.Protocols)) h2server.Info {
	t.Helper()
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{RootCAs: ca.Pool()},
		Protocols:       new(http.Protocols),
	}
	protos(tr.Protocols)
	defer tr.CloseIdleConnections()
	resp, err := (&http.Client{Transport: tr, Timeout: 5 * time.Second}).Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	var info h2server.Info
	if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
		t.Fatal(err)
	}
	return info
}

func TestALPNPicksTheProtocol(t *testing.T) {
	ca, _ := pki.NewAuthority("test ca")
	cert, _ := ca.IssueServer(time.Hour, nil, []byte{127, 0, 0, 1})
	srv := httptest.NewUnstartedServer(http.HandlerFunc(h2server.Whoami))
	srv.TLS = after.ServerConfig(cert)
	srv.EnableHTTP2 = true
	srv.StartTLS()
	defer srv.Close()

	h2 := get(t, srv, ca, func(p *http.Protocols) { p.SetHTTP2(true) })
	if h2.Proto != "HTTP/2.0" || h2.ALPN != "h2" {
		t.Fatalf("h2 client got %+v", h2)
	}
	h1 := get(t, srv, ca, func(p *http.Protocols) { p.SetHTTP1(true) })
	// An HTTP/1-only client sends no ALPN extension, so the negotiated
	// protocol is empty: the server falls back to HTTP/1.1.
	if h1.Proto != "HTTP/1.1" || h1.ALPN != "" {
		t.Fatalf("h1 client got %+v", h1)
	}
	if h1.TLSVersion != "TLS 1.3" || h2.TLSVersion != "TLS 1.3" {
		t.Fatalf("expected TLS 1.3 by default, got %s / %s", h1.TLSVersion, h2.TLSVersion)
	}
}

func TestNewServerDefaults(t *testing.T) {
	s := h2server.New(":8443", http.NotFoundHandler(), nil)
	if s.ReadHeaderTimeout == 0 || s.IdleTimeout == 0 {
		t.Fatal("a server without ReadHeaderTimeout/IdleTimeout is a slowloris target")
	}
	if s.HTTP2 == nil || s.HTTP2.MaxConcurrentStreams != 100 {
		t.Fatalf("HTTP2 config not applied: %+v", s.HTTP2)
	}
}

Versions: MinVersion TLS 1.2/1.3 Must-know ​

In plain words: The version is the generation of the protocol. TLS 1.3 is faster (one round trip) and has no weak options; TLS 1.2 is still needed for old clients; TLS 1.0 and 1.1 are retired.

Common misunderstanding: "I must set MinVersion and MaxVersion to be secure." Not setting MaxVersion is right: "By default, the maximum version supported by this package is used, which is currently TLS 1.3." Setting MaxVersion: tls.VersionTLS12 is how people accidentally disable TLS 1.3 (and with it the post-quantum key exchange). Setting MinVersion explicitly is good documentation even though the default is already TLS 1.2: "By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the minimum supported by this package."

Definition: tls.VersionTLS12 (0x0303) and tls.VersionTLS13 (0x0304); tls.VersionName(v) renders "TLS 1.3" (Go 1.21). Defaults by release: clients default to TLS 1.2 from Go 1.18; servers from Go 1.22; Go 1.27 removed the tls10server GODEBUG that restored the old server default. Go 1.25 added that servers "prefer the highest supported protocol version, even if it isn't the client's most preferred protocol version".

SettingEffectUse it when
nothingTLS 1.2 to 1.3The default is correct for public services
MinVersion: VersionTLS13Rejects TLS 1.2 clientsInternal service to service, modern clients only; Mozilla's "modern" profile
MinVersion: VersionTLS12Same as default, explicitPublic web; Mozilla's "intermediate" profile
MaxVersion: VersionTLS12No TLS 1.3, no post-quantumOnly to work around a broken middlebox, temporarily
MinVersion: VersionTLS10 / 11LegacyOnly a documented exception for hardware you cannot update

Mozilla's TLS guidelines (version 6.0, JSON from ssl-config.mozilla.org) list TLSv1.3 for "modern" and TLSv1.2 plus TLSv1.3 for "intermediate", with HSTS max-age 63072000 (two years) and OCSP stapling on for both.

text
real log lines from the lab demo (TLS 1.3 negotiated by default):
  curl --http2     -> {"proto":"HTTP/2.0","tls_version":"TLS 1.3","alpn":"h2", ...}
  openssl -tls1_2  -> Protocol: TLSv1.2, Cipher: ECDHE-ECDSA-AES128-GCM-SHA256

Real scenario: a payment partner can only do TLS 1.2. You keep MinVersion: tls.VersionTLS12 on the public listener and set MinVersion: tls.VersionTLS13 on the internal mTLS listener, where you control every client.

Cipher suites and curves Important ​

In plain words: A cipher suite is the recipe of algorithms for one TLS 1.2 connection; the "curve" (really: key exchange group) is how the two sides agree a secret. Go picks good ones for you.

Common misunderstanding: "I should set CipherSuites to harden the server." For TLS 1.3 you cannot: "Note that TLS 1.3 ciphersuites are not configurable". For TLS 1.0 to 1.2 the field only chooses which suites are enabled, not their order: since Go 1.17 "the order of the Config.CipherSuites field is now ignored". Go sorts by security, performance and hardware support; a server without AES hardware, or a client that prefers ChaCha20, gets ChaCha20 (the lab's curl negotiated TLS_CHACHA20_POLY1305_SHA256, openssl negotiated TLS_AES_128_GCM_SHA256, against the same server). PreferServerCipherSuites is deprecated and ignored.

Definition: tls.CipherSuites() returns the suites Go implements that have no known weakness; tls.InsecureCipherSuites() returns the rest (RC4, 3DES, static-RSA key exchange, CBC with SHA-256). Only ECDHE suites are on by default for TLS 1.2 (Go 1.22 stopped offering suites without ECDHE; 3DES left the defaults in 1.23). Config.CurvePreferences selects key exchanges; since Go 1.24 "The order of Config.CurvePreferences is now ignored, and the contents are only used to determine which key exchanges to enable".

Group (curve)KindDefault sinceNotes
X25519, CurveP256, CurveP384, CurveP521Classical ECDHElong agoX25519 and P-256 cover almost every client
X25519MLKEM768Hybrid: X25519 + ML-KEM-768 (post-quantum)Go 1.24 (tlsmlkem=0 reverts)Larger ClientHello (crypto/mlkem documents EncapsulationKeySize768 = 1184 bytes for the ML-KEM-768 key)
SecP256r1MLKEM768, SecP384r1MLKEM1024Hybrid with NIST curvesGo 1.26 (tlssecpmlkem=0 reverts)For FIPS-flavoured environments
MLKEM1024Pure ML-KEMopt in, Go 1.27Add it to CurvePreferences yourself
TLS 1.2 suite familySecure list?Note
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 and the 256-bit, ECDSA and RSA, CHACHA20_POLY1305 variantsYesThe set Mozilla's intermediate profile names
TLS_ECDHE_*_WITH_AES_*_CBC_SHAYes (for compatibility)Enabled by default; CBC with SHA-1
TLS_RSA_WITH_AES_128_GCM_SHA256 and other static RSANo: InsecureCipherSuitesNo forward secrecy; off by default
TLS_RSA_WITH_3DES_EDE_CBC_SHA, RC4No3DES default off since 1.23; tls3des=1 re-enabled it until Go 1.27 removed the setting

Real scenario: a pen-test report says "server supports CBC cipher suites". The honest answer is to show Config.CipherSuites set to the six AEAD suites from Mozilla's intermediate profile (a legitimate use of the field) and to note that TLS 1.3 connections are unaffected. A report that says "server prefers client order" can be ignored: Go decides.

go
// Package tlsinfo is the crypto/tls debugging toolbox: dial with a deadline,
// print what was negotiated, list the cipher suites Go knows, log session
// secrets for Wireshark.
package tlsinfo

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"time"
)

// Describe renders the negotiated parameters of a connection.
func Describe(cs tls.ConnectionState) string {
	return fmt.Sprintf("version=%s cipher=%s alpn=%q sni=%q resumed=%t peer_certs=%d",
		tls.VersionName(cs.Version), tls.CipherSuiteName(cs.CipherSuite),
		cs.NegotiatedProtocol, cs.ServerName, cs.DidResume, len(cs.PeerCertificates))
}

// Probe is the Go equivalent of `openssl s_client -connect host:port`: a TLS
// handshake with a deadline, returning the connection state. tls.Dialer
// takes a context (tls.Dial does not), so use it in services.
func Probe(ctx context.Context, addr string, cfg *tls.Config) (tls.ConnectionState, error) {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	d := tls.Dialer{NetDialer: &net.Dialer{Timeout: 3 * time.Second}, Config: cfg}
	conn, err := d.DialContext(ctx, "tcp", addr)
	if err != nil {
		return tls.ConnectionState{}, err
	}
	defer conn.Close()
	return conn.(*tls.Conn).ConnectionState(), nil
}

// Suite is one row of the cipher suite table.
type Suite struct {
	Name     string
	Versions []string
	Insecure bool
}

// Suites lists every suite crypto/tls implements, secure first. TLS 1.3 suites
// appear with Versions == ["TLS 1.3"] and cannot be configured: Config.CipherSuites
// only affects TLS 1.0 to 1.2.
func Suites() []Suite {
	var out []Suite
	add := func(cs []*tls.CipherSuite, insecure bool) {
		for _, s := range cs {
			var vs []string
			for _, v := range s.SupportedVersions {
				vs = append(vs, tls.VersionName(v))
			}
			out = append(out, Suite{Name: s.Name, Versions: vs, Insecure: insecure})
		}
	}
	add(tls.CipherSuites(), false)
	add(tls.InsecureCipherSuites(), true)
	return out
}

// KeyLog returns a Config.KeyLogWriter that writes the NSS key log format
// (the same file curl and browsers write for SSLKEYLOGFILE). Load it into
// Wireshark under Preferences > Protocols > TLS > (Pre)-Master-Secret log
// filename to decrypt a capture. Never enable it in production: the secrets
// decrypt every recorded packet of those connections.
func KeyLog(w io.Writer) io.Writer { return w }
go
package tlsinfo_test

import (
	"bytes"
	"crypto/tls"
	"net"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pki"
	"academy/http2-https-tls-mtls/tlsinfo"
)

func server(t *testing.T) (*httptest.Server, *pki.Authority) {
	t.Helper()
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	srv := httptest.NewUnstartedServer(http.NotFoundHandler())
	srv.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, NextProtos: []string{"h2", "http/1.1"}}
	srv.EnableHTTP2 = true
	srv.StartTLS()
	t.Cleanup(srv.Close)
	return srv, ca
}

func TestProbeReportsVersionCipherAndALPN(t *testing.T) {
	srv, ca := server(t)
	cs, err := tlsinfo.Probe(t.Context(), srv.Listener.Addr().String(), &tls.Config{
		RootCAs: ca.Pool(), ServerName: "api.example.test", NextProtos: []string{"h2"},
	})
	if err != nil {
		t.Fatal(err)
	}
	got := tlsinfo.Describe(cs)
	for _, want := range []string{"version=TLS 1.3", `alpn="h2"`, `sni="api.example.test"`, "resumed=false", "peer_certs=1"} {
		if !strings.Contains(got, want) {
			t.Errorf("Describe = %q, missing %q", got, want)
		}
	}
	t.Log(got)
}

func TestKeyLogWriterReceivesSecrets(t *testing.T) {
	srv, ca := server(t)
	var log bytes.Buffer
	_, err := tlsinfo.Probe(t.Context(), srv.Listener.Addr().String(), &tls.Config{
		RootCAs: ca.Pool(), ServerName: "api.example.test", KeyLogWriter: tlsinfo.KeyLog(&log),
	})
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(log.String(), "CLIENT_HANDSHAKE_TRAFFIC_SECRET") {
		t.Fatalf("key log = %q", log.String())
	}
}

func TestSuiteTable(t *testing.T) {
	var tls13, insecure int
	for _, s := range tlsinfo.Suites() {
		if len(s.Versions) == 1 && s.Versions[0] == "TLS 1.3" {
			tls13++
		}
		if s.Insecure {
			insecure++
		}
	}
	if tls13 != 3 {
		t.Errorf("TLS 1.3 suites = %d, want 3 (AES-128-GCM, AES-256-GCM, ChaCha20-Poly1305)", tls13)
	}
	if insecure == 0 {
		t.Error("InsecureCipherSuites should list the suites Go refuses to offer by default")
	}
}

Certificates and keys (PEM) Must-know ​

In plain words: A certificate is a signed statement that this public key belongs to these names. The private key never leaves your server. PEM is the text format: base64 between -----BEGIN CERTIFICATE----- lines.

Common misunderstanding: "The Common Name is the host name." Not for Go since 1.15: "The deprecated, legacy behavior of treating the CommonName field on X.509 certificates as a host name when no Subject Alternative Names are present is now disabled by default." The names must be in the SAN extension (DNSNames, IPAddresses). Another one: "certFile can be just the leaf." For a CA-signed certificate ListenAndServeTLS wants "the concatenation of the server's certificate, any intermediates, and the CA's certificate"; a leaf without its intermediate can fail in clients that do not fetch missing intermediates; Go's verifier uses only the chain the server sent plus its configured pools.

Definition: tls.LoadX509KeyPair(certFile, keyFile) reads two PEM files and, from Go 1.23, populates Certificate.Leaf; tls.X509KeyPair(certPEM, keyPEM) does the same from memory. Config.Certificates is a list of chains: "The first certificate compatible with the peer's requirements is selected automatically", but "if there are multiple Certificates, and they don't have the optional field Leaf set, certificate selection will incur a significant per-handshake performance cost" (Go 1.23 sets Leaf for you; set it yourself when you build the struct by hand). Key types: ECDSA P-256 is the efficient default (smaller, faster handshakes than RSA-2048); RSA remains the compatibility choice; Ed25519 is supported by Go but not by all public CAs and clients. Go caps RSA keys in peer certificates at 8192 bits (tlsmaxrsasize GODEBUG).

text
 step  who          what
 1     you           openssl req / certbot / mkcert  -> server.key + server.crt (leaf)
 2     you           cat server.crt intermediate.crt > fullchain.pem
 3     Go            tls.LoadX509KeyPair("fullchain.pem", "server.key")   -> Certificate{Leaf set}
 4     handshake     server sends the configured chain (leaf + intermediates; the trust anchor MAY be omitted)
 5     client        builds a path to a root it trusts, checks dates, EKU serverAuth, SAN vs ServerName
FileContentsPermissions
server.keyPrivate key, PKCS#8 PRIVATE KEY or EC PRIVATE KEY0600, owned by the service user, never in the image or the repo
fullchain.pemLeaf then intermediatesPublic
ca.crtThe CA you trust for mTLS or private servicesPublic

Real scenario: the pki helper in the snippets writes exactly these files (pki.PEM) so tests and the lab can exercise ListenAndServeTLS(certFile, keyFile) on real PEM.

Local dev certificates: mkcert and friends Must-know ​

In plain words: For https://localhost you want a certificate your browser trusts without clicking through warnings. mkcert makes a private CA, installs it in your machine's trust store and issues certificates from it.

Common misunderstanding: "I will just use a self-signed certificate and InsecureSkipVerify in dev." That trains the whole team to ship the shortcut and hides every certificate bug until production. The mkcert README: "Using certificates from real certificate authorities (CAs) for development can be dangerous or impossible (for hosts like example.test, localhost or 127.0.0.1), but self-signed certificates cause trust errors."

Definition: mkcert -install creates the local CA and adds it to the system and Firefox trust stores; mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1 writes example.com+5.pem and example.com+5-key.pem. The README warns: "the rootCA-key.pem file that mkcert automatically generates gives complete power to intercept secure requests from your machine. Do not share it."

OptionTrusted by browsersSetupBest for
mkcertYes, after mkcert -installOne commandLocal development of a browser-facing app
In-code CA (the pki package)No, you pass RootCAsNoneUnit and integration tests
openssl req -x509 -newkey ... self-signedNoOne commandThrowaway experiments with curl --cacert
Let's Encrypt stagingNo (untrusted root)Real domainTesting the ACME flow itself
Let's Encrypt productionYesReal domain, public DNSAnything on the internet

For Go tests the best practice is the in-code CA: generate on start, never touch the OS trust store, and the server uses httptest.NewUnstartedServer + StartTLS() with your own tls.Config (see after_test.go).

ACME, Let's Encrypt and autocert Must-know ​

In plain words: ACME is the protocol a program uses to ask a certificate authority for a certificate, prove it controls the domain, and get it automatically, again every couple of months. Let's Encrypt is the free CA that made it normal. autocert is Go's built-in ACME client that does this inside your server.

Common misunderstanding: "autocert with HostPolicy left nil is the convenient default." The source says why not: "If nil, all hosts are currently allowed. This is not recommended, as it opens a potential attack where clients connect to a server by IP address and pretend to be asking for an incorrect host name. Manager will attempt to obtain a certificate for that host, incorrectly, eventually reaching the CA's rate limit for certificate requests and making it impossible to obtain actual certificates." Equally: no Cache means a restart re-orders every certificate: "Otherwise your server is very likely to exceed the certificate issuer's request rate limits."

Definition: golang.org/x/crypto/acme/autocert.Manager "obtains and refreshes certificates automatically using "tls-alpn-01" or "http-01" challenge types". Manager.TLSConfig() returns a tls.Config with GetCertificate set and NextProtos of h2, http/1.1 and acme-tls/1, so HTTP/2 and the tls-alpn-01 challenge both work on port 443. Manager.HTTPHandler(fallback) answers http-01 challenges on port 80 and passes everything else to the fallback (your redirect). Renewal starts "at the lesser of 30 days or 1/3 of the certificate lifetime" unless RenewBefore says otherwise.

ACME challengeWhereWildcardsNeedsautocert
http-01Port 80, /.well-known/acme-challenge/TOKENNoPort 80 reachable from the internetYes, via HTTPHandler
tls-alpn-01Port 443, ALPN acme-tls/1NoPort 443 reachable; your Go server terminates TLSYes, built into TLSConfig
dns-01A _acme-challenge TXT recordYesDNS provider APINo: use certbot, lego or Caddy
Let's Encrypt factValueSource
Default certificate lifetime90 days; renew every 60LE FAQ
Six-day certificatesShort-lived option, first issued Feb 2025LE blog
New certificates per registered domain50 every 7 daysLE rate limits
Staging endpointhttps://acme-staging-v02.api.letsencrypt.org/directory: untrusted, higher limitsLE staging docs
OCSPResponders turned off on 6 August 2025 (CRLs instead)LE blog
text
 first request for api.example.com after start-up
 1  client ClientHello SNI=api.example.com
 2  Manager.GetCertificate -> HostPolicy ok -> not in Cache
 3  Manager -> ACME order, tls-alpn-01 or http-01 challenge, CA validates from several vantage points
 4  CA issues certificate -> Manager stores it in DirCache -> handshake continues (first request is slow)
 5  later handshakes: served from memory; renewal in the background 30 days before expiry

Real scenario: a small SaaS on one VM: autocert.Manager{HostPolicy: HostWhitelist("app.example.com"), Cache: DirCache("/var/lib/app/certs")}, :80 for challenges and a redirect, :443 from m.TLSConfig(). The cache directory is on a persistent volume, because a container that loses it on every deploy re-orders and eventually hits "50 certificates per registered domain per 7 days". Behind more than one replica, use a shared Cache implementation (the interface has Get, Put, Delete) or terminate TLS at a proxy.

go
// Package acmecfg wires golang.org/x/crypto/acme/autocert into net/http.
package acmecfg

import (
	"net/http"
	"time"

	"golang.org/x/crypto/acme"
	"golang.org/x/crypto/acme/autocert"
)

// StagingDirectory is Let's Encrypt's staging ACME endpoint: same protocol,
// untrusted certificates, far higher rate limits. Develop against it.
const StagingDirectory = "https://acme-staging-v02.api.letsencrypt.org/directory"

// NewManager returns a certificate manager for the listed hosts only.
// Never leave HostPolicy nil: any client that connects by IP or with a made-up
// SNI would make you ask the CA for certificates and burn your rate limit.
// A persistent Cache (DirCache) is what keeps restarts from re-ordering
// certificates.
func NewManager(cacheDir, email string, staging bool, hosts ...string) *autocert.Manager {
	m := &autocert.Manager{
		Prompt:      autocert.AcceptTOS,
		Cache:       autocert.DirCache(cacheDir),
		HostPolicy:  autocert.HostWhitelist(hosts...),
		Email:       email,
		RenewBefore: 30 * 24 * time.Hour,
	}
	if staging {
		m.Client = &acme.Client{DirectoryURL: StagingDirectory}
	}
	return m
}

// Servers returns the :443 server (TLS from the manager, which also answers
// tls-alpn-01 challenges and advertises h2) and the :80 server (answers
// http-01 challenges, redirects everything else).
func Servers(m *autocert.Manager, app http.Handler, redirect http.Handler) (https, plain *http.Server) {
	https = &http.Server{
		Addr:              ":https",
		Handler:           app,
		TLSConfig:         m.TLSConfig(),
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       90 * time.Second,
	}
	plain = &http.Server{
		Addr:              ":http",
		Handler:           m.HTTPHandler(redirect),
		ReadHeaderTimeout: 5 * time.Second,
	}
	return https, plain
}
go
package acmecfg_test

import (
	"net/http"
	"net/http/httptest"
	"slices"
	"testing"

	"academy/http2-https-tls-mtls/acmecfg"
)

func TestHostPolicyRefusesUnknownNames(t *testing.T) {
	m := acmecfg.NewManager(t.TempDir(), "ops@example.test", true, "www.example.test")
	if err := m.HostPolicy(t.Context(), "www.example.test"); err != nil {
		t.Fatalf("listed host rejected: %v", err)
	}
	if err := m.HostPolicy(t.Context(), "198.51.100.7"); err == nil {
		t.Fatal("a bare IP must not trigger certificate orders")
	}
}

func TestTLSConfigAdvertisesH2AndTheALPNChallenge(t *testing.T) {
	m := acmecfg.NewManager(t.TempDir(), "ops@example.test", true, "www.example.test")
	https, plain := acmecfg.Servers(m, http.NotFoundHandler(), http.NotFoundHandler())
	if !slices.Equal(https.TLSConfig.NextProtos, []string{"h2", "http/1.1", "acme-tls/1"}) {
		t.Fatalf("NextProtos = %v", https.TLSConfig.NextProtos)
	}
	if https.TLSConfig.GetCertificate == nil || plain.Handler == nil {
		t.Fatal("servers are not wired")
	}
}

func TestPlainHandlerFallsBackToTheRedirect(t *testing.T) {
	m := acmecfg.NewManager(t.TempDir(), "ops@example.test", true, "www.example.test")
	_, plain := acmecfg.Servers(m, http.NotFoundHandler(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "https://www.example.test/", http.StatusPermanentRedirect)
	}))
	rec := httptest.NewRecorder()
	plain.Handler.ServeHTTP(rec, httptest.NewRequest("GET", "http://www.example.test/", nil))
	if rec.Code != http.StatusPermanentRedirect {
		t.Fatalf("non-challenge request got %d", rec.Code)
	}
}

HTTP/2 in Go: ALPN and the automatic switch Must-know ​

In plain words: When a client connects it lists the protocols it speaks (h2, http/1.1) inside the TLS handshake; the server answers with one. In Go you do nothing: HTTP/2 is enabled by default over TLS, an http.Server that serves TLS offers h2 first, and http.Transport asks for it.

Common misunderstanding: "I have to import golang.org/x/net/http2 to get HTTP/2." Not since Go 1.6: "Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS." The opposite trap is more common: a client or server that silently stopped doing HTTP/2 because of how it was configured.

Definition: ALPN (RFC 7301) is a TLS extension: the client sends application_layer_protocol_negotiation in the ClientHello, the server returns its choice in EncryptedExtensions (TLS 1.3). In Go, Config.NextProtos is the list "in order of preference"; if there is no overlap "the connection will fail" (server log: tls: client requested unsupported application protocols); if the client sends no ALPN, "the connection will succeed and ConnectionState.NegotiatedProtocol will be empty", which is how HTTP/1-only clients look (the test in h2server asserts it).

SituationHTTP/2 on?Why
srv.ListenAndServeTLS(cert, key), no TLSConfigYesServeTLS adds h2 and http/1.1 to NextProtos through adjustNextProtos
srv.TLSConfig set with certificates, then ListenAndServeTLS("", "")YesSame path; your NextProtos is adjusted, not replaced
srv.Serve(tls.NewListener(l, cfg)), srv.TLSConfig nil, cfg.NextProtos contains "h2"YesGo 1.6 compatibility rule in shouldConfigureHTTP2ForServe; Serve documents "HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos"
srv.Serve(tls.NewListener(l, cfg)), srv.TLSConfig nil, cfg has certificates onlyNoNothing advertises h2 in ALPN, so clients negotiate HTTP/1.1 (the dispatch exists but is never selected)
srv.Serve(tls.NewListener(l, cfg)) and srv.TLSConfig set without "h2" in NextProtosNoThe server only configures HTTP/2 here when its TLSConfig mentions h2
srv.TLSNextProto = map[...]{} (non-nil, no h2 key)NoThe historical off switch; Server.Protocols is the modern one
GODEBUG=http2server=0NoUnless TLSNextProto has an h2 entry
http.Client with the default transportYesDefaultTransport sets ForceAttemptHTTP2: true
http.Transport{TLSClientConfig: ..., DialContext: ...}No"By default, use of any those fields conservatively disables HTTP/2"
the same with ForceAttemptHTTP2: trueYesWhat after.NewClient does
Transport.Protocols with only SetHTTP1(true)NoThe explicit Go 1.24 way to pin HTTP/1.1

Per request, the Go Request carries the result: r.Proto is HTTP/2.0 or HTTP/1.1, r.TLS.NegotiatedProtocol is h2, http/1.1 or empty.

text
 ALPN on a real Go server (lab, curl 8.7 and openssl 3.6)
 curl --http2      client offers h2,http/1.1  -> "ALPN: server accepted h2"   -> proto HTTP/2.0
 curl --http1.1    client offers http/1.1     -> alpn "http/1.1"             -> proto HTTP/1.1
 openssl -alpn h2                              -> "ALPN protocol: h2"
 openssl (no -alpn)                            -> "No ALPN negotiated"       -> HTTP/1.1 only

Real scenario: after adding DialContext for a custom resolver, a service's outbound calls to an HTTP/2 API double their connection count and handshake CPU. Nothing failed; the transport quietly fell back to HTTP/1.1 because ForceAttemptHTTP2 was missing. Log resp.Proto once per host in a debug build to catch this.

HTTP/2 mechanics: streams, SETTINGS, flow control, push, rapid reset Important ​

In plain words: One TCP connection carries many requests at once as numbered streams, headers are compressed, and each side tells the other how much it is willing to receive. A busy HTTP/2 server has few connections with many streams each, where an HTTP/1.1 server has many connections with one request each.

Common misunderstanding: "HTTP/2 removes head-of-line blocking." It removes it at the HTTP layer only. TCP still delivers bytes in order, so one lost packet stalls every stream on that connection; that is the reason HTTP/3 moved to QUIC.

Definition: The pieces you tune in Go sit in http.Server.HTTP2 and http.Transport.HTTP2 (an *http.HTTP2Config, Go 1.24; before that, golang.org/x/net/http2.Server and http2.Transport fields).

Knob (http.HTTP2Config field)RFC 9113 setting or behaviourDefaultWhen to change it
MaxConcurrentStreamsSETTINGS_MAX_CONCURRENT_STREAMS ("recommended ... no smaller than 100")"at least 100" in net/http; 250 in x/net/http2Lower it to bound per-connection work; raise it for gRPC fan-out
MaxReadFrameSizeSETTINGS_MAX_FRAME_SIZE (protocol default 16,384 octets)"A valid value is between 16KiB and 16MiB"; x/net/http2 advertises 1 MiBLarge uploads
MaxDecoderHeaderTableSize / MaxEncoderHeaderTableSizeSETTINGS_HEADER_TABLE_SIZE (HPACK dynamic table)4,096 bytes both sides (x/net initialHeaderTableSize); valid below 4 MiBHuge cookie or JWT headers
MaxReceiveBufferPerConnection / MaxReceiveBufferPerStreamFlow-control windows (initial 65,535 octets)Server (x/net): 1 MiB / 1 MiB. Client: connection 1<<30, stream 4 MiB (transportDefaultConnFlow, transportDefaultStreamFlow); valid at least 64 KiB / below 4 MiBThroughput on high-latency links
SendPingTimeout and PingTimeoutPING health checkoff; 15 sDetect half-dead connections behind NAT
WriteByteTimeoutClose if nothing can be writtenoffSlow-read clients
PermitProhibitedCipherSuitesThe HTTP/2 cipher blacklist (INADEQUATE_SECURITY)falseAlmost never
CountErrorPer-error counter hooknilExport HTTP/2 error metrics
StrictMaxConcurrentRequests (client, Go 1.26)Wait instead of opening another connection at the stream limitfalseCap connections to one upstream
Server.DisableClientPriority (Go 1.27)RFC 9218 priority signalsfalse (priorities honoured)Restore round-robin

The HTTP/2 server also uses http.Server.IdleTimeout for idle connections (the x/net implementation falls back to IdleTimeout, then ReadTimeout).

Server push is effectively over. Go 1.8 added http.Pusher, and the handler type is still there. Browsers dropped the feature: "support of HTTP/2 Server Push will be disabled by default in Chrome 106 and other Chromium-based browsers", with 103 Early Hints and <link rel=preload> as the alternatives. Do not build on Pusher; send a 103 or let the client preload.

HTTP/2 Rapid Reset. In October 2023 an attack that opens streams and immediately resets them made servers do unbounded work: Go's advisory GO-2023-2102 (CVE-2023-39325) says resetting "allows the attacker to create a new request while the existing one is still executing". The fix bounded simultaneously executing handlers to the stream limit, shipped in Go 1.21.3 (and 1.20.10) and golang.org/x/net v0.17.0. Lesson: keep MaxConcurrentStreams finite, keep Go current, and watch CountError.

text
 one HTTP/2 connection, three streams in flight (client -> server unless noted)
 1  HEADERS  stream 1  GET /a
 2  HEADERS  stream 3  GET /b
 3  HEADERS  stream 5  POST /c          DATA stream 5 (flow-control window shrinks)
 4  <- HEADERS stream 3  200            <- DATA stream 3 (b finished first: no head-of-line blocking at HTTP level)
 5  <- WINDOW_UPDATE stream 5, then <- HEADERS/DATA stream 1 and 5
 6  <- GOAWAY  (graceful shutdown: no new streams, in-flight ones finish)

Real scenario: a gRPC gateway multiplexes 600 concurrent calls to one backend over a single HTTP/2 connection. With the default of about 100 streams per connection the Go client opens extra connections (unless StrictMaxConcurrentRequests); with the server's MaxConcurrentStreams set to 1000 it stays on one. Either is correct; the point is that you chose it.

h2c: HTTP/2 without TLS Important ​

In plain words: The same HTTP/2 protocol over a plain TCP connection. Browsers never do it; service-to-service traffic behind a TLS-terminating proxy often does, and gRPC without TLS is h2c.

Common misunderstanding: "I need golang.org/x/net/http2/h2c for this." That package is now marked deprecated: "Unencrypted HTTP/2 is now supported directly by the net/http package", and h2c.NewHandler is "Deprecated: Set the http.Server Protocols field to use unencrypted HTTP/2 instead." The Go 1.24 release notes: "When Server.Protocols contains UnencryptedHTTP2, the server will accept HTTP/2 connections on unencrypted ports. The server can accept both HTTP/1 and unencrypted HTTP/2 on the same port."

Definition: http.Protocols has SetHTTP1, SetHTTP2 (over TLS) and SetUnencryptedHTTP2 (h2c). On the client, "When Transport.Protocols contains UnencryptedHTTP2 and does not contain HTTP1, the transport will use unencrypted HTTP/2 for http:// URLs" (prior knowledge: the client sends the HTTP/2 preface immediately, the server must accept it). RFC 9113 marks the old Upgrade: h2c mechanism obsolete; use prior knowledge.

ModeHow the client startsGo serverGo client
h2 over TLSALPN h2 in the handshakeautomaticautomatic
h2c prior knowledgeSends the connection preface at onceProtocols.SetUnencryptedHTTP2(true)Transport.Protocols with only UnencryptedHTTP2
h2c upgrade (Upgrade: h2c)Starts as HTTP/1.1 and upgradeslegacy x/net/http2/h2c onlynot recommended
go
// Package unencrypted serves and calls HTTP/2 without TLS (h2c) using only
// net/http. Go 1.24 added Server.Protocols and Transport.Protocols; the old
// golang.org/x/net/http2/h2c package is deprecated in favour of them.
package unencrypted

import (
	"net/http"
	"time"
)

// NewServer accepts HTTP/1.1 and prior-knowledge HTTP/2 on the same plain
// TCP port. Use it behind a TLS-terminating proxy or on a loopback or
// service-mesh link; never on the open internet.
func NewServer(addr string, h http.Handler) *http.Server {
	p := new(http.Protocols)
	p.SetHTTP1(true)
	p.SetUnencryptedHTTP2(true)
	return &http.Server{
		Addr:              addr,
		Handler:           h,
		Protocols:         p,
		ReadHeaderTimeout: 5 * time.Second,
	}
}

// NewClient speaks HTTP/2 over a plain connection ("prior knowledge"): it
// sends the HTTP/2 preface straight away, so the server must understand it.
func NewClient() *http.Client {
	p := new(http.Protocols)
	p.SetUnencryptedHTTP2(true)
	return &http.Client{
		Timeout:   5 * time.Second,
		Transport: &http.Transport{Protocols: p},
	}
}
go
package unencrypted_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"academy/http2-https-tls-mtls/unencrypted"
)

func TestH2CAndHTTP1ShareOnePort(t *testing.T) {
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%s tls=%v", r.Proto, r.TLS != nil)
	}))
	srv.Config = unencrypted.NewServer("", srv.Config.Handler)
	srv.Start()
	defer srv.Close()

	for _, tc := range []struct {
		name   string
		client *http.Client
		want   string
	}{
		{"h2c prior knowledge", unencrypted.NewClient(), "HTTP/2.0"},
		{"plain HTTP/1.1", srv.Client(), "HTTP/1.1"},
	} {
		resp, err := tc.client.Get(srv.URL)
		if err != nil {
			t.Fatalf("%s: %v", tc.name, err)
		}
		resp.Body.Close()
		if resp.Proto != tc.want {
			t.Errorf("%s: proto = %s, want %s", tc.name, resp.Proto, tc.want)
		}
	}
}

Real scenario: an Nginx or cloud load balancer terminates TLS and forwards to Go over h2c so gRPC works end to end without certificates on every pod. The risk is the "plain" in plain: do it only on a network you already trust, and prefer mTLS between services otherwise.

HTTP/3 and QUIC: quic-go, not the standard library Good to know ​

In plain words: HTTP/3 runs over QUIC, a UDP-based transport with TLS 1.3 built in, so a lost packet stalls only one stream and a phone can change networks without reconnecting.

Common misunderstanding: "Go 1.24 has Protocols.SetHTTP3." It does not. http.Protocols has an unexported HTTP/3 bit that the standard library uses only to test against golang.org/x/net/internal/http3; there is no public switch, and ListenAndServeTLS on a server whose protocols include HTTP/3 returns "http: Server.Protocols contains HTTP3, but Server does not support HTTP/3". Production HTTP/3 in Go is github.com/quic-go/quic-go/http3: HTTP/3 is quic-go, not stdlib.

Definition: quic-go "also supports HTTP/3 (RFC 9114)". Its docs show http3.Server{Handler, Addr, TLSConfig: http3.ConfigureTLSConfig(&tls.Config{}), QUICConfig} and ListenAndServe(). ConfigureTLSConfig "configures the GetConfigForClient such that the correct ALPN value for HTTP/3 is used" (h3). Browsers discover HTTP/3 through the Alt-Svc response header on an HTTP/1.1 or HTTP/2 connection (RFC 9114 section 3.1.1), which quic-go's SetQUICHeaders writes. Its HTTP/3 server enables 0-RTT at the QUIC layer by default, unlike Go's crypto/tls over TCP.

text
 how a browser gets to HTTP/3
 1  TCP+TLS to :443, ALPN h2            (every first visit; UDP may be blocked)
 2  response header   Alt-Svc: h3=":443"; ma=86400     (quic-go: server.SetQUICHeaders(w.Header()))
 3  next request: UDP :443, QUIC handshake (TLS 1.3 inside), ALPN h3
 4  if UDP fails, fall back to step 1 silently
ConcernHTTP/2 over TCPHTTP/3 over QUIC
TransportTCPUDP
Loss on one streamStalls the connectionStalls that stream only
HandshakeTCP then TLS 1.3: 2 RTT before the first request byte1 RTT, 0-RTT possible on resume
Go standard libraryYesNo
FirewallsPort 443/TCP everywherePort 443/UDP often blocked on corporate networks
Toolingcurl --http2, h2loadcurl --http3, h2load --h3

Real scenario: a media API serves mobile clients on bad networks. HTTP/3 is worth trying there, behind a CDN or proxy that terminates QUIC (Cloudflare, Caddy, Envoy), with Go still speaking HTTP/2 or h2c to the origin. Running quic-go in the Go process makes sense when you own the edge.

TLS termination at proxy vs in Go Must-know ​

In plain words: Somebody has to hold the private key and do the handshake. Either a proxy or load balancer in front (Nginx, Envoy, HAProxy, an AWS ALB, Cloudflare) or your Go process.

Common misunderstanding: "If a load balancer does TLS, my service needs no TLS thinking." The service still needs to know the original scheme and client address (it will see plain HTTP from the proxy), must not trust X-Forwarded-* headers from anyone but the proxy, and may need TLS or mTLS on the inside hop for compliance.

Definition: the four shapes in the diagram: terminate at the proxy and speak plain HTTP or h2c to Go (A); terminate and re-encrypt (B); pass TLS through at layer 4 so Go terminates (C); mutual TLS between services (D).

Where does TLS end? Four common shapesA Terminate at the proxyClientProxy / LB (certs)Go (HTTP)TLSplain, h2cB Terminate and re-encryptClientProxy / LB (certs)Go (TLS)TLSTLS againC Pass through (L4)ClientTCP LB (SNI only)Go (certs)one TLS session, client to GoD mTLS service to serviceGo service A (cert)Go service B (cert)both sides prove identityA: simplest; the proxy renews certs; Go sees the client IP only via X-Forwarded-For or PROXY protocol.B: encrypted inside the network too; two certificate sets to manage.C: Go owns certs and ALPN; the load balancer cannot route on paths or headers.D: zero trust inside the cluster; often done by a mesh sidecar instead of application code.
QuestionProxy terminates (A or B)Go terminates (C or D)
Who renews certificates?The proxy or platform (ACM, Caddy, cert-manager)Your code: autocert or a reloader (Rotation)
HTTP/2 to the clientProxy decides; Go may see HTTP/1.1 or h2cGo negotiates it directly
HTTP/3Proxy can add itYou run quic-go
Client IPX-Forwarded-For or PROXY protocolr.RemoteAddr is the client
Client certificate (mTLS)Proxy verifies, passes identity in a header (trust the hop!)r.TLS.VerifiedChains holds the verified chains (PeerCertificates is only what the client sent)
Layer 7 routing, WAF, cachingYesNo
Plain text inside the networkYes in ANo
CPU for handshakesOn the proxyOn your pods

Real scenario: an ALB terminates TLS with an ACM certificate and forwards HTTP to pods; the service trusts X-Forwarded-Proto only because the pod's security group accepts traffic from the ALB alone. For a payments service, the team picks B instead and issues pod certificates from an internal CA, so the in-VPC hop is encrypted too.

HTTP to HTTPS redirect and HSTS Must-know ​

In plain words: People type example.com or follow an old http:// link. Port 80 answers with a redirect to HTTPS (redirect 80→443), and HSTS tells the browser to skip port 80 next time.

Common misunderstanding: "A redirect to HTTPS secures the site." The first request is still plain and can be intercepted; only HSTS (a header on the HTTPS response) makes the browser upgrade by itself afterwards, and HSTS preload lists remove even that first request.

Definition: HSTS (RFC 6797) is the response header Strict-Transport-Security: max-age=63072000; includeSubDomains[; preload]. max-age is seconds; includeSubDomains covers every subdomain, so check them all first; preload is a promise to browser vendors via hstspreload.org and is hard to undo. Send it only over HTTPS. The redirect should use 308 Permanent Redirect (keeps the method), take the host from configuration, not from the Host header (otherwise your server can be used as an open redirect), and keep path and query.

text
 1  GET http://example.com/pay?id=7     (port 80)
 2  <- 308 Location: https://example.com/pay?id=7
 3  GET https://example.com/pay?id=7    (port 443)
 4  <- 200   Strict-Transport-Security: max-age=63072000; includeSubDomains
 5  next visit: browser rewrites http:// to https:// before sending anything
go
// Package redirect moves port 80 traffic to HTTPS and tells browsers to
// stop trying plain HTTP (HSTS, RFC 6797).
package redirect

import (
	"net/http"
	"strconv"
)

// ToHTTPS redirects every request to https://canonicalHost + the original
// path and query. canonicalHost is configuration, not r.Host: echoing the
// Host header lets an attacker bounce users to any site through your server.
// 308 keeps the method and body (a POST stays a POST); 301 would turn it
// into a GET in most clients.
func ToHTTPS(canonicalHost string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "https://"+canonicalHost+r.URL.RequestURI(), http.StatusPermanentRedirect)
	})
}

// HSTS adds Strict-Transport-Security to responses that arrived over TLS.
// Browsers ignore the header on plain HTTP, and sending it there is noise.
// Start with a short maxAge, raise it once every subdomain really serves
// HTTPS, and add preload only after reading hstspreload.org.
func HSTS(maxAgeSeconds int, includeSubDomains, preload bool) func(http.Handler) http.Handler {
	v := "max-age=" + strconv.Itoa(maxAgeSeconds)
	if includeSubDomains {
		v += "; includeSubDomains"
	}
	if preload {
		v += "; preload"
	}
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.TLS != nil {
				w.Header().Set("Strict-Transport-Security", v)
			}
			next.ServeHTTP(w, r)
		})
	}
}
go
package redirect_test

import (
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"testing"

	"academy/http2-https-tls-mtls/redirect"
)

func TestRedirectKeepsPathQueryAndIgnoresHostHeader(t *testing.T) {
	h := redirect.ToHTTPS("www.example.test")
	req := httptest.NewRequest(http.MethodPost, "http://attacker.test/pay?id=7", nil)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != http.StatusPermanentRedirect {
		t.Fatalf("status = %d, want 308", rec.Code)
	}
	if got, want := rec.Header().Get("Location"), "https://www.example.test/pay?id=7"; got != want {
		t.Fatalf("Location = %q, want %q", got, want)
	}
}

func TestHSTSOnlyOverTLS(t *testing.T) {
	h := redirect.HSTS(63072000, true, false)(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))

	plain := httptest.NewRecorder()
	h.ServeHTTP(plain, httptest.NewRequest("GET", "http://www.example.test/", nil))
	if v := plain.Header().Get("Strict-Transport-Security"); v != "" {
		t.Fatalf("header on plain HTTP: %q", v)
	}

	secure := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "https://www.example.test/", nil)
	req.TLS = &tls.ConnectionState{}
	h.ServeHTTP(secure, req)
	if got, want := secure.Header().Get("Strict-Transport-Security"), "max-age=63072000; includeSubDomains"; got != want {
		t.Fatalf("header = %q, want %q", got, want)
	}
}

Real scenario: roll HSTS out in stages: max-age=300 for a day, then a week, then a year and two years once every subdomain, including the forgotten legacy.example.com, serves valid HTTPS. A single plain-HTTP-only subdomain plus includeSubDomains is a self-inflicted outage.

mTLS, server side Must-know ​

In plain words: In ordinary TLS only the server shows ID. In mutual TLS the server also asks the client for a certificate and refuses to talk to anyone who cannot present one signed by a CA the server trusts. It is the standard way for one backend service to know that the caller is another service of yours, not just "someone with a token".

Common misunderstanding: "Setting ClientAuth to something other than NoClientCert turns mTLS on." Only RequireAndVerifyClientCert both requires a certificate and verifies it. RequestClientCert asks but "does not require that the client send any certificates" and does not verify the chain; RequireAnyClientCert requires one "but that certificate is not required to be valid"; VerifyClientCertIfGiven verifies a certificate if the client sends one ("If the client does send a certificate it is required to be valid") but accepts a client that sends none. A second trap: if ClientCAs is nil the verifier gets Roots: nil, and for x509.VerifyOptions "If nil, the system roots or the platform verifier are used", so any client certificate chaining to a public CA would pass the chain check. Always set ClientCAs to your own pool.

Definition: Config.ClientAuth is the policy, Config.ClientCAs the pool "that servers use if required to verify a client certificate". Go verifies the client chain with KeyUsages: ExtKeyUsageClientAuth, so a client certificate needs the clientAuth extended key usage. After the built-in checks, VerifyPeerCertificate(rawCerts, verifiedChains) and then VerifyConnection(ConnectionState) run; the second is the right place for authorisation.

ClientAuth valueAsks for a certRejects no certVerifies the chainUse
NoClientCert (default)NoNoNoOrdinary HTTPS
RequestClientCertYesNoNoRare: inspect optional certs yourself
RequireAnyClientCertYesYesNoYou verify everything in VerifyPeerCertificate (custom PKI)
VerifyClientCertIfGivenYesNoIf presentOptional mTLS, for example admin paths
RequireAndVerifyClientCertYesYesYesNormal mTLS
CallbackRuns whenResumed connectionsRight for
VerifyPeerCertificateAfter built-in verification"This callback is not invoked on resumed connections"Extra chain checks (pins, policy OIDs)
VerifyConnectionAfter VerifyPeerCertificate"This callback will run for all connections, including resumptions, regardless of InsecureSkipVerify or ClientAuth settings."Authorisation, allow lists, anything that must never be skipped

Go 1.21 made resumption stricter for exactly this reason: "Servers now skip verifying client certificates (including not running Config.VerifyPeerCertificate) for resumed connections, besides checking the expiration time." So an identity check in VerifyPeerCertificate is silently bypassed by a client that resumes a session; the same warning covers configs returned by GetConfigForClient. Put authorisation in VerifyConnection.

text
 what each side sees (lab demo -mtls and mtls_test.go, real)
 no certificate          client: remote error: tls: certificate required      server: tls: client didn't provide a certificate
 cert from another CA    client: remote error: tls: unknown certificate authority
                         server: tls: failed to verify certificate: x509: certificate signed by unknown authority
 right CA, wrong ID      client: remote error: tls: bad certificate           server: your VerifyConnection error text
 curl, no certificate    curl: (56) ..., exit 56
 curl --cert --key       spiffe://example.test/ns/prod/sa/orders

In TLS 1.3 the client finishes its half of the handshake before the server validates the client certificate, so the rejection reaches the client as an alert on its first read, not as an error from the dial. Tests and health checks must read once before declaring success.

go
// Package mtls is mutual TLS on both sides: the server demands and verifies a
// client certificate, then authorises the workload identity inside it.
package mtls

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"net/http"
	"time"
)

// SPIFFEID returns the single spiffe:// URI SAN of a certificate. SPIFFE
// X.509-SVIDs carry exactly one URI SAN; anything else is rejected.
func SPIFFEID(c *x509.Certificate) (string, error) {
	if len(c.URIs) != 1 || c.URIs[0].Scheme != "spiffe" {
		return "", errors.New("mtls: certificate must carry exactly one spiffe:// URI SAN")
	}
	return c.URIs[0].String(), nil
}

// ServerConfig requires and verifies a client certificate against clientCAs
// (authentication), then checks the SPIFFE ID against an allow list
// (authorisation). The check lives in VerifyConnection, not
// VerifyPeerCertificate, because VerifyConnection also runs on resumed
// connections.
func ServerConfig(cert tls.Certificate, clientCAs *x509.CertPool, allowed ...string) *tls.Config {
	allow := make(map[string]bool, len(allowed))
	for _, id := range allowed {
		allow[id] = true
	}
	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		MinVersion:   tls.VersionTLS12,
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    clientCAs,
		VerifyConnection: func(cs tls.ConnectionState) error {
			leaf, err := verifiedLeaf(cs)
			if err != nil {
				return err
			}
			id, err := SPIFFEID(leaf)
			if err != nil {
				return err
			}
			if !allow[id] {
				return fmt.Errorf("mtls: identity %q is not allowed", id)
			}
			return nil
		},
	}
}

// verifiedLeaf returns the leaf of the first verified chain.
// ConnectionState.PeerCertificates is merely what the peer sent;
// VerifiedChains is filled only when the chain was actually verified
// (ClientAuth: VerifyClientCertIfGiven or RequireAndVerifyClientCert).
func verifiedLeaf(cs tls.ConnectionState) (*x509.Certificate, error) {
	if len(cs.VerifiedChains) == 0 || len(cs.VerifiedChains[0]) == 0 {
		return nil, errors.New("mtls: no verified client certificate chain")
	}
	return cs.VerifiedChains[0][0], nil
}

// ClientConfig presents cert and trusts only roots for the server's name.
func ClientConfig(cert tls.Certificate, roots *x509.CertPool, serverName string) *tls.Config {
	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      roots,
		ServerName:   serverName,
		MinVersion:   tls.VersionTLS12,
	}
}

// NewClient wraps ClientConfig in an HTTP client with HTTP/2 enabled.
func NewClient(cfg *tls.Config) *http.Client {
	return &http.Client{
		Timeout:   5 * time.Second,
		Transport: &http.Transport{TLSClientConfig: cfg, ForceAttemptHTTP2: true},
	}
}

// Identity is a handler that returns the verified caller identity, read from
// r.TLS.VerifiedChains (not PeerCertificates).
func Identity(w http.ResponseWriter, r *http.Request) {
	if r.TLS == nil {
		http.Error(w, "TLS required", http.StatusUnauthorized)
		return
	}
	leaf, err := verifiedLeaf(*r.TLS)
	if err != nil {
		http.Error(w, "client certificate required", http.StatusUnauthorized)
		return
	}
	id, err := SPIFFEID(leaf)
	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	_, _ = w.Write([]byte(id))
}
go
package mtls_test

import (
	"crypto/tls"
	"crypto/x509"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/mtls"
	"academy/http2-https-tls-mtls/pki"
)

const (
	orders  = "spiffe://example.test/ns/prod/sa/orders"
	billing = "spiffe://example.test/ns/prod/sa/billing"
)

type env struct {
	srv *httptest.Server
	ca  *pki.Authority
}

func setup(t *testing.T) env {
	t.Helper()
	ca, err := pki.NewAuthority("internal ca")
	if err != nil {
		t.Fatal(err)
	}
	cert, err := ca.IssueServer(time.Hour, []string{"payments.internal.test"}, []byte{127, 0, 0, 1})
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewUnstartedServer(http.HandlerFunc(mtls.Identity))
	srv.TLS = mtls.ServerConfig(cert, ca.Pool(), orders) // only "orders" may call
	srv.EnableHTTP2 = true
	srv.Config.ErrorLog = log.New(io.Discard, "", 0) // keep expected handshake failures out of the test log
	srv.Config.ErrorLog = log.New(testLogWriter{t}, "server: ", 0)
	srv.StartTLS()
	t.Cleanup(srv.Close)
	return env{srv, ca}
}

func (e env) client(t *testing.T, ca *pki.Authority, id string) *http.Client {
	t.Helper()
	cert, err := ca.IssueClient(time.Hour, id)
	if err != nil {
		t.Fatal(err)
	}
	return mtls.NewClient(mtls.ClientConfig(cert, e.ca.Pool(), "payments.internal.test"))
}

func TestAllowedIdentityGetsThrough(t *testing.T) {
	e := setup(t)
	resp, err := e.client(t, e.ca, orders).Get(e.srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	if string(body) != orders {
		t.Fatalf("handler saw %q, want %q", body, orders)
	}
}

func TestValidCertificateWithTheWrongIdentityIsRefused(t *testing.T) {
	e := setup(t)
	_, err := e.client(t, e.ca, billing).Get(e.srv.URL)
	if err == nil {
		t.Fatal("billing has a valid certificate from our CA but is not on the allow list")
	}
	t.Logf("client sees: %v", err)
}

func TestCertificateFromAnotherCAIsRefused(t *testing.T) {
	e := setup(t)
	other, _ := pki.NewAuthority("other ca")
	cert, err := other.IssueClient(time.Hour, orders)
	if err != nil {
		t.Fatal(err)
	}
	cfg := mtls.ClientConfig(cert, e.ca.Pool(), "payments.internal.test")
	// A Go client only offers a certificate that matches the CA names in the
	// server's CertificateRequest, so with plain Certificates this cert would
	// not even be sent ("certificate required"). GetClientCertificate forces
	// it onto the wire, which is what a misconfigured or hostile client does.
	cfg.Certificates = nil
	cfg.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return &cert, nil }
	_, err = mtls.NewClient(cfg).Get(e.srv.URL)
	if err == nil {
		t.Fatal("a client certificate from an untrusted CA must fail even with the right SPIFFE ID")
	}
	t.Logf("client sees: %v", err)
}

func TestNoClientCertificateIsRefused(t *testing.T) {
	e := setup(t)
	cfg := mtls.ClientConfig(emptyCert(), e.ca.Pool(), "payments.internal.test")
	cfg.Certificates = nil
	// In TLS 1.3 the client finishes its handshake before the server
	// rejects it, so the error arrives with the first response read.
	_, err := mtls.NewClient(cfg).Get(e.srv.URL)
	if err == nil {
		t.Fatal("expected the server to demand a certificate")
	}
	t.Logf("client sees: %v", err)
}

// PeerCertificates is what the peer sent; only VerifiedChains proves the
// chain was verified. Identity and the allow list must read the latter.
func TestIdentityRequiresAVerifiedChain(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueClient(time.Hour, orders)
	unverified := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert.Leaf}}

	cfg := mtls.ServerConfig(tls.Certificate{}, ca.Pool(), orders)
	if err := cfg.VerifyConnection(*unverified); err == nil {
		t.Fatal("VerifyConnection accepted a certificate that has no verified chain")
	}

	req := httptest.NewRequest(http.MethodGet, "https://payments.internal.test/", nil)
	req.TLS = unverified
	rec := httptest.NewRecorder()
	mtls.Identity(rec, req)
	if rec.Code == http.StatusOK {
		t.Fatalf("Identity trusted an unverified PeerCertificates entry: %q", rec.Body.String())
	}

	verified := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert.Leaf}, VerifiedChains: [][]*x509.Certificate{{cert.Leaf, ca.Cert}}}
	if err := cfg.VerifyConnection(*verified); err != nil {
		t.Fatalf("verified chain rejected: %v", err)
	}
}
mTLS: authentication in the handshake, authorisation in your codeClient (service A)Certificates: leaf + key URI SAN spiffe://example.test/ ns/prod/sa/ordersRootCAs: trusts the CA that signed the serverServerName: payments.internal.testServer (service B)Certificates: leaf + keyClientAuth: RequireAndVerifyClientCertClientCAs: the CA allowed to sign clientsVerifyConnection: allow listClientHelloserver cert + CertificateRequestclient cert + CertificateVerify1 Chain valid and signedby ClientCAs? Not expired?ExtKeyUsage clientAuth?2 VerifyPeerCertificateoptional; NOT called on aresumed connection3 VerifyConnectionSPIFFE ID on the allow list?runs on resumption too4 Handlerr.TLS.PeerCertificates[0]is the verified leafFails closed: handshake aborted, no handlerno certificate: alert certificate requiredcert from another CA: alert unknown CAidentity not allowed: alert bad certificateEasy to get wrongRequestClientCert does not verify the chainvalid chain = authentication; add an allow listTLS 1.3: client sees rejection on its first read

Real scenario: an internal payments service listens with RequireAndVerifyClientCert, ClientCAs = the platform CA, and an allow list of three SPIFFE IDs (orders, refunds, reconciler). A compromised search pod holding a perfectly valid certificate from the same CA is refused at the handshake. Without the allow list it would have been trusted.

mTLS, client side Must-know ​

In plain words: The calling service shows its own certificate and verifies the server's, using its own list of trusted CAs.

Common misunderstanding: "The client only needs the client certificate." It needs both halves: Certificates (or GetClientCertificate) to present, and RootCAs to verify the server. If RootCAs is nil Go uses the host's roots, which will not contain your private CA, and if you "fix" the resulting error with InsecureSkipVerify you have built a client that authenticates itself to a server it does not verify. And a Go client offers a certificate from Certificates only if it matches the CA names in the server's CertificateRequest: a certificate from the wrong CA is usually not sent at all, and the client sees certificate required rather than unknown certificate authority (the test forces it onto the wire with GetClientCertificate).

Definition: tls.Config{Certificates: []tls.Certificate{clientCert}, RootCAs: pool, ServerName: "payments.internal.test", MinVersion: tls.VersionTLS12} inside http.Transport.TLSClientConfig. ServerName is both the SNI sent in the ClientHello and the name verified in the SAN; set it when you dial by IP or through a service address that is not in the certificate. GetClientCertificate lets the client choose or reload a certificate per handshake, "may be called multiple times for the same connection if renegotiation occurs or if TLS 1.3 is in use". An http.Transport needs ForceAttemptHTTP2: true once you supply TLSClientConfig.

Client fieldPurposeGotcha
Certificates / GetClientCertificateOur identityReload on rotation or reconnect forever with an expired cert
RootCAsWhom to trustnil means system roots, not "no verification"
ServerNameSNI and SAN checkWrong value gives x509.HostnameError
MinVersionFloorDefaults to TLS 1.2
ClientSessionCacheResumptionWithout it every connection is a full handshake
InsecureSkipVerifyDisable verificationDo not

Real scenario: a batch job uses one http.Client with a long-lived transport; the certificate expires at 02:00 and every later request fails with remote error: tls: expired certificate. A GetClientCertificate backed by the same Reloader as the server (Rotation) fixes it for every new connection. Shortening IdleConnTimeout alone does not: a reconnect would present the same expired entry from Certificates, so either use GetClientCertificate or rebuild the Transport with the new certificate. An established connection does not fail when its certificate later expires; only new handshakes are affected.

Workload identity: SAN, SPIFFE and what to authorise Important ​

In plain words: The certificate says who the caller is in its Subject Alternative Name. For services the name is not a person; it is something like spiffe://example.test/ns/prod/sa/orders ("service account orders in namespace prod").

Common misunderstanding: "The Common Name identifies the client." Use the SAN. Go ignores the CN for host names, and for workload identity the convention (SPIFFE X.509-SVID) puts exactly one URI in the SAN. The SPIFFE specification: "An X.509 SVID MUST contain exactly one URI SAN, and by extension, exactly one SPIFFE ID."

Definition: In Go the SAN lives in x509.Certificate: DNSNames, IPAddresses, EmailAddresses, URIs. mtls.SPIFFEID returns the single spiffe:// URI and rejects anything else. Authorisation is then ordinary code: a map or a policy lookup keyed by that ID, in VerifyConnection for a connection-level decision or in a handler/middleware for a per-route one (r.TLS.VerifiedChains[0][0] is the verified leaf; PeerCertificates is only what the peer sent, and VerifiedChains is filled only when ClientAuth verified it). Libraries: github.com/spiffe/go-spiffe (v2) "leverages the SPIFFE Workload API" and offers tlsconfig and spiffetls.Listen/Dial helpers (SPIRE is a SPIFFE implementation); a service mesh such as Linkerd ("Automatic mTLS" between meshed pods) or Istio can do the mutual TLS in a sidecar so the Go code sees plain HTTP.

Identity fieldExampleUse
DNS SANapi.example.testServer names; also service names inside a cluster
IP SAN127.0.0.1Dialling by IP (tests, appliances)
URI SAN (SPIFFE)spiffe://example.test/ns/prod/sa/ordersWorkload identity: who is calling
Email SANops@example.testHuman client certificates (VPN, admin)
Subject CNordersDisplay only

Real scenario: the refunds endpoint must be callable only by spiffe://example.test/ns/prod/sa/orders. A middleware reads the identity from r.TLS.VerifiedChains[0][0], compares it to the route's allowed set and returns 403 otherwise; the check is a few lines and is testable with httptest and pki.IssueClient exactly like mtls_test.go.

Certificate rotation: GetCertificate and GetConfigForClient Must-know ​

In plain words: Certificates expire (Let's Encrypt: after 90 days, and renewal is meant to happen every 60). If your server loads the certificate once at start-up, you either restart on every renewal or one day the site is down.

Common misunderstanding: "Mutating Config.Certificates when a new file appears is fine." The config must not be modified after use (see above), and doing it from another goroutine is a data race. The supported way is a callback.

Definition: Config.GetCertificate func(*ClientHelloInfo) (*Certificate, error) is called per handshake ("only be called if the client supplies SNI information or if Certificates is empty") and may return a different certificate per server name. Config.GetConfigForClient "is called after a ClientHello is received from a client. It may return a non-nil Config in order to change the Config that will be used to handle this connection": use it for per-host policy (different CAs, ClientAuth, versions). The returned config "may not be subsequently modified". A reload swaps an atomic.Pointer[tls.Certificate]; only a successfully parsed pair replaces the old one.

Rotate certificates without restarting the serverRenewal jobcertbot, ACME, Vaulttls.crt + tls.keynew mtimeReloader.WatchLoadX509KeyPairatomic.Pointerswap only on successparse error: keep the old certificate, report the errorHandshakes after the swapnew ClientHelloConfig.GetCertificate(hello)serves the NEW leafConnections opened before the swapkeep the OLD certificate until they close: long-lived HTTP/2 and gRPC connections can outlive itBound the age of old connections: server-side GOAWAY via Shutdown, or a MaxConnAge in your proxy,and renew well before expiry (autocert: 30 days or a third of the lifetime, whichever is less).
ApproachReload triggerProsCons
Restart on renewalProcess managerSimplestDrops connections; coordination
GetCertificate + file polling (the Reloader)mtime change every few secondsNo dependency; works with certbot and cert-manager (any tool that rewrites the files)Polling latency
GetCertificate + fsnotifyFile eventImmediatefsnotify's FAQ: editors and tools update files atomically, so "Watch the parent directory and use Event.Name to filter"; Kubernetes updates Secret volumes with a delay
autocert.ManagerInternalFully automaticPublic names only; ACME ports; cache needed
Signal (SIGHUP)Operator or hookExplicitEasy to forget, see signals
Service mesh sidecarMesh control planeApp code unchangedA different failure domain
go
// Package rotate serves renewed certificates without a restart.
package rotate

import (
	"context"
	"crypto/tls"
	"os"
	"sync/atomic"
	"time"
)

// Reloader holds the current certificate behind an atomic pointer.
// tls.Config.GetCertificate is called once per handshake, so a swap takes
// effect for the next new connection; existing connections keep the old one.
type Reloader struct {
	certFile, keyFile string
	current           atomic.Pointer[tls.Certificate]
	modTime           atomic.Int64
}

// New loads the pair once; a bad pair at start-up is a fatal error.
func New(certFile, keyFile string) (*Reloader, error) {
	r := &Reloader{certFile: certFile, keyFile: keyFile}
	if err := r.Reload(); err != nil {
		return nil, err
	}
	return r, nil
}

// Reload parses the files and swaps the pointer only if parsing succeeds, so
// a half-written file leaves the previous certificate in service.
func (r *Reloader) Reload() error {
	c, err := tls.LoadX509KeyPair(r.certFile, r.keyFile) // Go 1.23+: c.Leaf is set
	if err != nil {
		return err
	}
	if fi, err := os.Stat(r.certFile); err == nil {
		r.modTime.Store(fi.ModTime().UnixNano())
	}
	r.current.Store(&c)
	return nil
}

// GetCertificate plugs into tls.Config.GetCertificate.
func (r *Reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
	return r.current.Load(), nil
}

// Watch polls the certificate file's modification time (fsnotify is an
// alternative) and reloads when it changes. Errors go to onErr.
func (r *Reloader) Watch(ctx context.Context, every time.Duration, onErr func(error)) {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			fi, err := os.Stat(r.certFile)
			if err != nil || fi.ModTime().UnixNano() == r.modTime.Load() {
				continue
			}
			if err := r.Reload(); err != nil && onErr != nil {
				onErr(err)
			}
		}
	}
}

// PerSNI returns a GetConfigForClient that picks a whole tls.Config by the
// server name in the ClientHello: different certificates, different ClientAuth
// policy, different CAs per host. Unknown names get def.
func PerSNI(def *tls.Config, byName map[string]*tls.Config) func(*tls.ClientHelloInfo) (*tls.Config, error) {
	return func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
		if c, ok := byName[hello.ServerName]; ok {
			return c, nil
		}
		return def, nil
	}
}
go
package rotate_test

import (
	"context"
	"crypto/tls"
	"io"
	"net"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pki"
	"academy/http2-https-tls-mtls/rotate"
)

func write(t *testing.T, dir string, c tls.Certificate) (certFile, keyFile string) {
	t.Helper()
	certPEM, keyPEM, err := pki.PEM(c)
	if err != nil {
		t.Fatal(err)
	}
	certFile, keyFile = filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key")
	if err := os.WriteFile(certFile, certPEM, 0o600); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(keyFile, keyPEM, 0o600); err != nil {
		t.Fatal(err)
	}
	return certFile, keyFile
}

// serve accepts TLS connections and completes the handshake only.
func serve(t *testing.T, cfg *tls.Config) string {
	t.Helper()
	ln, err := tls.Listen("tcp", "127.0.0.1:0", cfg)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ln.Close() })
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				return
			}
			go func() {
				defer c.Close()
				c.SetDeadline(time.Now().Add(2 * time.Second))
				// Writing drives the handshake and, on success, delivers one byte,
				// so a client can tell "accepted" from "rejected" from "timed out".
				_, _ = c.Write([]byte("k"))
			}()
		}
	}()
	return ln.Addr().String()
}

func serial(t *testing.T, addr, name string, roots *tls.Config) string {
	t.Helper()
	cfg := roots.Clone()
	cfg.ServerName = name
	conn, err := tls.Dial("tcp", addr, cfg)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	return conn.ConnectionState().PeerCertificates[0].SerialNumber.String()
}

func TestReloadServesTheNewCertificateWithoutRestart(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	first, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	dir := t.TempDir()
	certFile, keyFile := write(t, dir, first)
	r, err := rotate.New(certFile, keyFile)
	if err != nil {
		t.Fatal(err)
	}
	addr := serve(t, &tls.Config{GetCertificate: r.GetCertificate, MinVersion: tls.VersionTLS12})
	client := &tls.Config{RootCAs: ca.Pool()}

	if got := serial(t, addr, "api.example.test", client); got != first.Leaf.SerialNumber.String() {
		t.Fatalf("before rotation: serial %s", got)
	}

	second, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	write(t, dir, second)
	if err := r.Reload(); err != nil {
		t.Fatal(err)
	}
	if got := serial(t, addr, "api.example.test", client); got != second.Leaf.SerialNumber.String() {
		t.Fatalf("after rotation: serial %s", got)
	}
}

func TestBrokenFileKeepsTheOldCertificate(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	first, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	dir := t.TempDir()
	certFile, keyFile := write(t, dir, first)
	r, _ := rotate.New(certFile, keyFile)
	if err := os.WriteFile(certFile, []byte("-----BEGIN CERTIFICATE-----\ntruncated"), 0o600); err != nil {
		t.Fatal(err)
	}
	if err := r.Reload(); err == nil {
		t.Fatal("a truncated PEM must not load")
	}
	addr := serve(t, &tls.Config{GetCertificate: r.GetCertificate})
	if got := serial(t, addr, "api.example.test", &tls.Config{RootCAs: ca.Pool()}); got != first.Leaf.SerialNumber.String() {
		t.Fatalf("the old certificate must stay in service, got serial %s", got)
	}
}

func TestWatchPicksUpAChangedFile(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	first, _ := ca.IssueServer(time.Hour, []string{"api.example.test"})
	dir := t.TempDir()
	certFile, keyFile := write(t, dir, first)
	r, _ := rotate.New(certFile, keyFile)
	ctx, cancel := context.WithCancel(t.Context())
	defer cancel()
	go r.Watch(ctx, 10*time.Millisecond, nil)

	second, _ := ca.IssueServer(time.Hour, []string{"api.example.test"})
	time.Sleep(20 * time.Millisecond) // make sure the mtime differs
	write(t, dir, second)
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		c, _ := r.GetCertificate(nil)
		if c.Leaf.SerialNumber.Cmp(second.Leaf.SerialNumber) == 0 {
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
	t.Fatal("Watch did not pick up the new certificate")
}

func TestPerSNIRequiresClientCertsOnlyForTheAdminHost(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	srvCert, _ := ca.IssueServer(time.Hour, []string{"www.example.test", "admin.example.test"}, net.ParseIP("127.0.0.1"))
	def := &tls.Config{Certificates: []tls.Certificate{srvCert}}
	admin := &tls.Config{
		Certificates: []tls.Certificate{srvCert},
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    ca.Pool(),
	}
	top := &tls.Config{
		Certificates:       []tls.Certificate{srvCert},
		GetConfigForClient: rotate.PerSNI(def, map[string]*tls.Config{"admin.example.test": admin}),
	}
	addr := serve(t, top)
	roots := &tls.Config{RootCAs: ca.Pool()}

	// www: no client certificate needed, and the server really answers.
	wc := roots.Clone()
	wc.ServerName = "www.example.test"
	conn0, err := tls.Dial("tcp", addr, wc)
	if err != nil {
		t.Fatal(err)
	}
	conn0.SetReadDeadline(time.Now().Add(2 * time.Second))
	if b, err := io.ReadAll(conn0); err != nil || string(b) != "k" {
		t.Fatalf("www host: got %q, %v", b, err)
	}
	conn0.Close()

	// admin: the client handshake completes first in TLS 1.3; the server's
	// rejection arrives as an alert on the first read. A read timeout or a
	// received byte would mean the policy was not enforced.
	cfg := roots.Clone()
	cfg.ServerName = "admin.example.test"
	conn, err := tls.Dial("tcp", addr, cfg)
	if err == nil {
		defer conn.Close()
		conn.SetReadDeadline(time.Now().Add(2 * time.Second))
		var n int
		n, err = conn.Read(make([]byte, 1))
		if err == nil {
			t.Fatalf("admin host served %d byte(s) without a client certificate", n)
		}
	}
	if !strings.Contains(err.Error(), "certificate required") && !strings.Contains(err.Error(), "bad certificate") {
		t.Fatalf("want a client-certificate alert, got %v", err)
	}
}

The tests prove four things: a rotated file is served to the next handshake without a restart, a truncated file keeps the old certificate in service, Watch notices a changed file, and PerSNI can demand client certificates for the admin host only. Existing connections keep the certificate they negotiated, so long-lived HTTP/2 and gRPC connections can outlive a certificate: end them with a periodic GOAWAY (proxy max connection age) or on shutdown (graceful shutdown).

Real scenario: a Kubernetes Secret mounted at /tls/ is updated by cert-manager every 60 days; Kubernetes propagates Secret updates to the volume after a delay. The reloader polls tls.crt every 10 seconds, calls Reload and logs the new serial and NotAfter. A Prometheus gauge of cert_not_after_seconds alerts when fewer than 14 days remain, which catches the day the renewal job itself breaks.

tls.Dial, tls.Dialer and probing a host Must-know ​

In plain words: Sometimes you are not doing HTTP: a database, an SMTP server, a custom protocol, or just "what certificate does that host serve and when does it expire?". tls.Dial opens a TCP connection and runs the client handshake.

Common misunderstanding: "tls.Dial has a timeout." tls.Dial uses a zero net.Dialer, so no timeout. Use a tls.Dialer whose NetDialer is a net.Dialer with a Timeout, call DialContext with a context deadline, or tls.DialWithDialer. The source note: "DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext".

Definition: tls.Dial(network, addr, cfg); if cfg.ServerName is empty it is taken from addr. Probe in tlsinfo is the Go equivalent of openssl s_client -connect host:port: handshake with a deadline, then ConnectionState(): version, suite, ALPN, peer chain (PeerCertificates[0].NotAfter for expiry monitoring), VerifiedChains, DidResume.

go
state, err := tlsinfo.Probe(ctx, "api.example.test:443", &tls.Config{NextProtos: []string{"h2"}})
if err == nil {
	leaf := state.PeerCertificates[0]
	fmt.Println(tlsinfo.Describe(state), "expires in", time.Until(leaf.NotAfter).Round(time.Hour))
}

Real scenario: a daily check dials every public hostname with Probe, exports time.Until(NotAfter) and fails the build if any certificate has fewer than 21 days left or negotiates below TLS 1.2. It needs no extra tooling beyond this file.

InsecureSkipVerify: the dangers and the alternatives Must-know ​

In plain words: It makes the client accept any certificate from anyone. The connection is still encrypted, to whoever answered.

Common misunderstanding: "It is fine inside our network" or "it is only for staging". The source comment: "If InsecureSkipVerify is true, crypto/tls accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to machine-in-the-middle attacks unless custom verification is used. This should be used only for testing or in combination with VerifyConnection or VerifyPeerCertificate." A flag that exists in staging is in production next quarter; the gosec linter has a rule for it (its README marks the pattern InsecureSkipVerify: true, // #nosec G402), but only if you run it.

Definition: InsecureSkipVerify skips chain and host name verification. The legitimate use is the second half of that sentence: skip the built-in verification and replace it with your own, as in pin, which checks the SHA-256 of the leaf's SubjectPublicKeyInfo in VerifyConnection (so it also runs on resumption).

Instead of...Do this
Unknown CA in testPut the CA in RootCAs (pki, mkcert, curl --cacert)
Self-signed device certificate you controlPin its key (pin.Config) or add it as the only root
Wrong name (dial by IP)Set ServerName to a name in the certificate, or add an IP SAN
Expired test certificateIssue short-lived certificates in the test setup
"Corporate proxy re-signs everything"Add the proxy's root to RootCAs
go
// Package pin is what to do instead of a bare InsecureSkipVerify: verify
// yourself. Pinning a public key is a legitimate use for a device or a
// self-signed internal service that you control end to end.
package pin

import (
	"bytes"
	"crypto/sha256"
	"crypto/tls"
	"errors"
)

// SPKIHash is the SHA-256 of a certificate's SubjectPublicKeyInfo. Print it
// with:  openssl x509 -in server.crt -pubkey -noout |
//
//	openssl pkey -pubin -outform DER | openssl dgst -sha256
func SPKIHash(rawSPKI []byte) [32]byte { return sha256.Sum256(rawSPKI) }

// Config skips the CA-based verification (InsecureSkipVerify) and replaces it
// with a check that the leaf certificate's public key matches the pin.
// VerifyConnection runs on every handshake, including resumed ones.
// Expiry and host name are NOT checked here; add them if you need them.
func Config(pin [32]byte) *tls.Config {
	return &tls.Config{
		MinVersion:         tls.VersionTLS12,
		InsecureSkipVerify: true, // we verify in VerifyConnection, below
		VerifyConnection: func(cs tls.ConnectionState) error {
			if len(cs.PeerCertificates) == 0 {
				return errors.New("pin: server sent no certificate")
			}
			got := sha256.Sum256(cs.PeerCertificates[0].RawSubjectPublicKeyInfo)
			if !bytes.Equal(got[:], pin[:]) {
				return errors.New("pin: server public key does not match the pinned hash")
			}
			return nil
		},
	}
}
go
package pin_test

import (
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pin"
	"academy/http2-https-tls-mtls/pki"
)

func TestPinnedKeyAcceptsOnlyThatServer(t *testing.T) {
	ca, _ := pki.NewAuthority("private ca nobody trusts")
	cert, _ := ca.IssueServer(time.Hour, []string{"device.example.test"}, []byte{127, 0, 0, 1})
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	srv.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
	srv.StartTLS()
	defer srv.Close()

	good := pin.SPKIHash(cert.Leaf.RawSubjectPublicKeyInfo)
	resp, err := (&http.Client{Transport: &http.Transport{TLSClientConfig: pin.Config(good)}}).Get(srv.URL)
	if err != nil {
		t.Fatalf("pinned server should be accepted: %v", err)
	}
	resp.Body.Close()

	var wrong [32]byte
	if _, err := (&http.Client{Transport: &http.Transport{TLSClientConfig: pin.Config(wrong)}}).Get(srv.URL); err == nil {
		t.Fatal("a different pin must be rejected")
	}
}

Real scenario: an IoT gateway talks to thousands of devices with self-signed certificates the company generated. Instead of InsecureSkipVerify: true it stores each device's SPKI hash at provisioning and verifies it with pin.Config; a swapped device fails closed.

Session resumption, tickets and 0-RTT Important ​

In plain words: After the first full handshake the server hands the client a "ticket", an encrypted note. Next time the client presents the ticket and the two sides skip the certificate exchange.

Common misunderstanding: "TLS 1.3 gives me 0-RTT, so my API is one round trip faster." Go's TLS server does not accept 0-RTT: it sends a ticket_age_add it never checks "because 0-RTT is not supported" and answers a client's early data with an alert (tls: client sent unexpected early data); the release notes for Go 1.21 say "0-RTT is still not supported in TLS". That is a safe default: RFC 8446 warns that "This data is not forward secret" and "There are no guarantees of non-replay between connections", and RFC 8470 defines Early-Data: 1 and 425 Too Early for applications that do accept it. quic-go's HTTP/3 server does enable 0-RTT at the QUIC layer (HTTP/3), so there you must treat early requests as replayable.

Definition: The server issues tickets by default; with nothing configured Go rotates the key itself: "automatically rotated every day and dropped after seven days". Config.SessionTicketsDisabled turns it off; SetSessionTicketKeys shares keys across replicas ("The first key will be used when creating new tickets, while all keys can be used for decrypting tickets", which is how you rotate; it is the documented exception to "do not modify a Config": "It is safe to call this function while the server is running", and it turns off the automatic rotation); Go 1.21 added WrapSession/UnwrapSession and SessionState for custom tickets. On the client, resumption needs ClientSessionCache (for example tls.NewLRUClientSessionCache); without it "session ticket support is also disabled". ConnectionState.DidResume reports the result. The openssl s_client output in the lab shows Post-Handshake New Session Ticket arrived after a TLS 1.3 handshake.

FactDetail
Server ticket key rotation (default)Every day; dropped after seven days
Ticket lifetime offeredAt most seven days (RFC 8446 limits it to 604,800 s)
Go 1.21 changeNew ticket on every resumption; tickets no longer carry a key identifier
Resumed connection and mTLSVerifyPeerCertificate not run; expiry is checked; use VerifyConnection
Multiple replicasSame SetSessionTicketKeys on all, or accept full handshakes
Security noteTicket keys decrypt recorded sessions' secrets: store and rotate like private keys
text
 loopback benchmark, Go 1.27.4, Apple M4 Pro, ECDSA P-256 certificate (real, from bench/)
 plain HTTP/1.1  keep-alive                  30,179 ns/op     62 allocs
 TLS 1.3 HTTP/1.1 keep-alive                 30,790 ns/op     62 allocs
 TLS 1.3 HTTP/2   keep-alive                 39,442 ns/op     63 allocs
 TLS 1.3 new connection, full handshake     467,804 ns/op    996 allocs
 TLS 1.3 new connection, resumed            421,979 ns/op   1089 allocs

Read the numbers carefully: a TLS handshake costs about 15 times a keep-alive request in CPU, which is the whole argument for connection reuse; on loopback resumption saves only about 10 percent because Go still performs a fresh ECDHE key exchange (psk_dhe_ke) and loopback has no round trip to save. On a real network resumption mainly saves the certificate chain bytes and signature verification, and every avoided handshake round trip is your RTT.

go
// Package resume makes repeat connections cheaper with session tickets.
package resume

import (
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"time"
)

// NewClient keeps an in-memory session cache. Without ClientSessionCache a Go
// client never resumes: it has nowhere to remember the ticket. DisableKeepAlives
// forces a new TCP+TLS connection per request so the effect is visible.
func NewClient(roots *x509.CertPool, serverName string, keepAlive bool) *http.Client {
	return &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			DisableKeepAlives: !keepAlive,
			TLSClientConfig: &tls.Config{
				RootCAs:            roots,
				ServerName:         serverName,
				ClientSessionCache: tls.NewLRUClientSessionCache(64),
			},
			ForceAttemptHTTP2: true,
		},
	}
}

// ShareTicketKeys gives several servers the same ticket keys, so a ticket
// issued by one replica is accepted by the others. The first key encrypts new
// tickets; the rest only decrypt, which is how you rotate. Treat the keys like
// private keys: anyone holding them can decrypt recorded session secrets.
func ShareTicketKeys(key [32]byte, previous [][32]byte, cfgs ...*tls.Config) {
	keys := append([][32]byte{key}, previous...)
	for _, c := range cfgs {
		c.SetSessionTicketKeys(keys)
	}
}
go
package resume_test

import (
	"crypto/tls"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pki"
	"academy/http2-https-tls-mtls/resume"
)

func resumed(t *testing.T, c *http.Client, url string) bool {
	t.Helper()
	resp, err := c.Get(url)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	io.Copy(io.Discard, resp.Body)
	return resp.TLS.DidResume
}

func newServer(t *testing.T, cfg *tls.Config) *httptest.Server {
	t.Helper()
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	srv.TLS = cfg
	srv.StartTLS()
	t.Cleanup(srv.Close)
	return srv
}

func TestSecondConnectionResumes(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, []byte{127, 0, 0, 1})
	srv := newServer(t, &tls.Config{Certificates: []tls.Certificate{cert}})
	c := resume.NewClient(ca.Pool(), "api.example.test", false)

	if resumed(t, c, srv.URL) {
		t.Fatal("the first connection cannot be a resumption")
	}
	if !resumed(t, c, srv.URL) {
		t.Fatal("the second connection should resume with the ticket from the first")
	}
}

func TestDisabledTicketsMeanFullHandshakeEveryTime(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, []byte{127, 0, 0, 1})
	srv := newServer(t, &tls.Config{Certificates: []tls.Certificate{cert}, SessionTicketsDisabled: true})
	c := resume.NewClient(ca.Pool(), "api.example.test", false)
	resumed(t, c, srv.URL)
	if resumed(t, c, srv.URL) {
		t.Fatal("SessionTicketsDisabled must prevent resumption")
	}
}

func TestSharedTicketKeysResumeAcrossReplicas(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, []byte{127, 0, 0, 1})
	a := &tls.Config{Certificates: []tls.Certificate{cert}}
	b := &tls.Config{Certificates: []tls.Certificate{cert}}
	var key [32]byte
	copy(key[:], "0123456789abcdef0123456789abcdef")
	resume.ShareTicketKeys(key, nil, a, b)
	srvA, srvB := newServer(t, a), newServer(t, b)

	// One ServerName for both replicas means one cache entry, like a load balancer VIP.
	c := resume.NewClient(ca.Pool(), "api.example.test", false)
	resumed(t, c, srvA.URL)
	if !resumed(t, c, srvB.URL) {
		t.Fatal("replica B should accept the ticket issued by replica A")
	}

	// A replica with its own random keys cannot read A's ticket.
	srvC := newServer(t, &tls.Config{Certificates: []tls.Certificate{cert}})
	if resumed(t, c, srvC.URL) {
		t.Fatal("replica C has different ticket keys and must fall back to a full handshake")
	}
}
go
package bench

import (
	"crypto/tls"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pki"
)

type fixture struct {
	plain *httptest.Server
	tls   *httptest.Server
	ca    *pki.Authority
}

func newFixture(b *testing.B) fixture {
	b.Helper()
	ca, err := pki.NewAuthority("bench ca")
	if err != nil {
		b.Fatal(err)
	}
	cert, err := ca.IssueServer(time.Hour, []string{"bench.example.test"}, []byte{127, 0, 0, 1})
	if err != nil {
		b.Fatal(err)
	}
	h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") })
	plain := httptest.NewServer(h)
	secure := httptest.NewUnstartedServer(h)
	secure.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
	secure.EnableHTTP2 = true
	secure.StartTLS()
	b.Cleanup(func() { plain.Close(); secure.Close() })
	return fixture{plain, secure, ca}
}

func (f fixture) tlsClient(h2, keepAlive, resume bool) *http.Client {
	cfg := &tls.Config{RootCAs: f.ca.Pool(), ServerName: "bench.example.test"}
	if resume {
		cfg.ClientSessionCache = tls.NewLRUClientSessionCache(8)
	}
	p := new(http.Protocols)
	p.SetHTTP1(!h2)
	p.SetHTTP2(h2)
	return &http.Client{Transport: &http.Transport{
		TLSClientConfig:   cfg,
		DisableKeepAlives: !keepAlive,
		Protocols:         p,
	}}
}

// hit sends one GET and reports whether its TLS handshake was a resumption.
func hit(b *testing.B, c *http.Client, url string) (resumed bool) {
	resp, err := c.Get(url)
	if err != nil {
		b.Fatal(err)
	}
	io.Copy(io.Discard, resp.Body)
	resp.Body.Close()
	return resp.TLS != nil && resp.TLS.DidResume
}

func run(b *testing.B, c *http.Client, url string, wantResumed bool) {
	hit(b, c, url) // warm up: first connection and (if enabled) first ticket
	if got := hit(b, c, url); got != wantResumed {
		b.Fatalf("DidResume = %v, want %v: the benchmark would measure the wrong thing", got, wantResumed)
	}
	for b.Loop() {
		hit(b, c, url)
	}
	c.CloseIdleConnections()
}

func BenchmarkPlainHTTP1KeepAlive(b *testing.B) {
	f := newFixture(b)
	run(b, &http.Client{Transport: &http.Transport{}}, f.plain.URL, false)
}

func BenchmarkTLS13HTTP1KeepAlive(b *testing.B) {
	f := newFixture(b)
	run(b, f.tlsClient(false, true, false), f.tls.URL, false)
}

func BenchmarkTLS13HTTP2KeepAlive(b *testing.B) {
	f := newFixture(b)
	run(b, f.tlsClient(true, true, false), f.tls.URL, false)
}

func BenchmarkTLS13NewConnFullHandshake(b *testing.B) {
	f := newFixture(b)
	run(b, f.tlsClient(false, false, false), f.tls.URL, false)
}

func BenchmarkTLS13NewConnResumed(b *testing.B) {
	f := newFixture(b)
	run(b, f.tlsClient(false, false, true), f.tls.URL, true)
}

Real scenario: an API behind a TCP load balancer runs eight replicas. Clients that reconnect land on a random replica; with independent random ticket keys only one in eight resumes. Sharing the keys from a secret store (rotated daily, old key kept for decryption) raises that to all, and the handshake CPU graph drops accordingly. The test TestSharedTicketKeysResumeAcrossReplicas is that scenario in miniature.

OCSP stapling and revocation Good to know ​

In plain words: Revocation answers "has this certificate been cancelled early?". OCSP stapling lets the server attach a fresh, CA-signed "still good" answer to the handshake so the browser need not ask the CA.

Common misunderstanding: "Go checks revocation for me." It does not: Certificate.Verify carries the warning "this function doesn't do any revocation checking" (the line is in the x509 source). If you need revocation you check a CRL (x509.ParseRevocationList, RevocationList) or an OCSP response yourself, typically in VerifyConnection.

Definition: Server side, tls.Certificate.OCSPStaple holds "an optional OCSP response which will be served to clients that request it"; you fetch and refresh it (golang.org/x/crypto/ocsp "parses OCSP responses as specified in RFC 2560"). Client side, ConnectionState.OCSPResponse is the stapled response, if any. Let's Encrypt retired OCSP: "On this date we will turn off our OCSP responders" (6 August 2025), moving revocation to CRLs, and OCSP Must-Staple requests stopped working in May 2025, so stapling for Let's Encrypt certificates is no longer available. Mozilla's guideline JSON still marks ocsp_staple true for CAs that offer it.

MechanismStatus for a Go service
OCSP staplingManual: set Certificate.OCSPStaple; not possible with Let's Encrypt any more
OCSP Must-Staple extensionDo not request it from Let's Encrypt (requests fail since May 2025)
CRLParse and consult yourself; browsers use CRLite and vendor lists
Short-lived certificatesReduce the need: Let's Encrypt offers six-day certificates
Internal mTLSShort-lived workload certificates (hours) beat revocation lists

Real scenario: an enterprise CA with an OCSP responder serves a Go reverse proxy; a sidecar goroutine refetches the OCSP response every 12 hours and updates the OCSPStaple field of the certificate behind GetCertificate, with the same atomic swap as rotation.

Encrypted Client Hello (Go 1.23 and 1.24) Good to know ​

In plain words: Even with TLS 1.3 the server name (SNI) in the ClientHello is readable on the wire, so an observer knows you are visiting clinic.example. ECH encrypts it.

Common misunderstanding: "ECH is on automatically in Go." It is not. A client must be given an ECHConfigList (published in a DNS HTTPS record), and a server must hold the matching keys.

Definition: Client side (Go 1.23): "The TLS client now supports the Encrypted Client Hello draft specification. This feature can be enabled by setting the Config.EncryptedClientHelloConfigList field." With the field set the handshake only succeeds if ECH is negotiated, a rejection returns *tls.ECHRejectionError (possibly with a new list), and MinVersion, if set, must be TLS 1.3. Server side (Go 1.24): "enabled by populating the Config.EncryptedClientHelloKeys field", each EncryptedClientHelloKey pairs a marshalled ECHConfig with its HPKE private key; Go 1.25 added GetEncryptedClientHelloKeys to load keys per handshake. The specification is a draft, and Go warns that "How this field is parsed may change in future Go versions".

SideFieldSince
ClientConfig.EncryptedClientHelloConfigListGo 1.23
ClientConfig.EncryptedClientHelloRejectionVerifywith client ECH (Go 1.23)
ServerConfig.EncryptedClientHelloKeysGo 1.24
ServerConfig.GetEncryptedClientHelloKeysGo 1.25
BothTLS 1.3 requiredn/a
go
// Package ech shows where Encrypted Client Hello plugs into crypto/tls.
// ECH hides the server name (SNI) inside an encrypted inner ClientHello.
// Client support arrived in Go 1.23, server support in Go 1.24, and Go 1.25
// added Config.GetEncryptedClientHelloKeys to load keys per handshake.
package ech

import (
	"crypto/tls"
	"crypto/x509"
)

// ClientConfig dials with ECH. configList is the serialized ECHConfigList a
// site publishes in its DNS HTTPS (type 65) record. With this field set the
// handshake only succeeds if ECH is negotiated, and MinVersion, if set, must
// be TLS 1.3.
func ClientConfig(configList []byte, roots *x509.CertPool, publicOrPrivateName string) *tls.Config {
	return &tls.Config{
		MinVersion:                     tls.VersionTLS13,
		RootCAs:                        roots,
		ServerName:                     publicOrPrivateName,
		EncryptedClientHelloConfigList: configList,
	}
}

// ServerConfig accepts ECH for the given keys. Each EncryptedClientHelloKey
// pairs a marshalled ECHConfig (what you publish in DNS) with its HPKE
// private key. Rotate by keeping the previous key in the slice until old
// clients have refreshed DNS.
func ServerConfig(cert tls.Certificate, keys []tls.EncryptedClientHelloKey) *tls.Config {
	return &tls.Config{
		Certificates:             []tls.Certificate{cert},
		MinVersion:               tls.VersionTLS13,
		EncryptedClientHelloKeys: keys,
	}
}
go
package ech_test

import (
	"crypto/tls"
	"net"
	"strings"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/ech"
	"academy/http2-https-tls-mtls/pki"
)

// Building a valid ECHConfig needs an HPKE key pair and the draft wire
// format, which is out of scope here, so these tests pin the wiring only.
func TestClientConfigRequiresTLS13(t *testing.T) {
	c := ech.ClientConfig([]byte{0x00}, nil, "api.example.test")
	if c.MinVersion != tls.VersionTLS13 || c.EncryptedClientHelloConfigList == nil {
		t.Fatalf("unexpected config: %+v", c)
	}
}

// A real TLS 1.3 listener proves the failure comes from the ECH path, not
// from a refused connection: the same server accepts a client without ECH.
func TestClientRejectsAMalformedConfigList(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13})
	if err != nil {
		t.Fatal(err)
	}
	defer ln.Close()
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				return
			}
			go func() { c.(*tls.Conn).Handshake(); c.Close() }()
		}
	}()
	addr := ln.Addr().String()

	plain := &tls.Config{RootCAs: ca.Pool(), ServerName: "api.example.test", MinVersion: tls.VersionTLS13}
	conn, err := tls.Dial("tcp", addr, plain)
	if err != nil {
		t.Fatalf("control without ECH must succeed, so a failure below is ECH-specific: %v", err)
	}
	conn.Close()

	_, err = tls.Dial("tcp", addr, ech.ClientConfig([]byte{0xde, 0xad}, ca.Pool(), "api.example.test"))
	if err == nil || !strings.Contains(err.Error(), "malformed ECHConfigList") {
		t.Fatalf("want the ECH error \"tls: malformed ECHConfigList\", got %v", err)
	}
}

func TestServerConfigCarriesTheKeys(t *testing.T) {
	keys := []tls.EncryptedClientHelloKey{{Config: []byte{1}, PrivateKey: []byte{2}, SendAsRetry: true}}
	c := ech.ServerConfig(tls.Certificate{}, keys)
	if len(c.EncryptedClientHelloKeys) != 1 || c.MinVersion != tls.VersionTLS13 {
		t.Fatalf("unexpected config: %+v", c)
	}
}

Real scenario: a privacy-sensitive service behind Cloudflare gets ECH from the CDN without code. Your own Go edge needs key generation, DNS publication and rotation; the snippet shows the wiring only, because building an ECHConfig needs HPKE tooling outside this chapter.

Debugging TLS: openssl s_client, curl -v, GODEBUG and key logs Must-know ​

In plain words: When "it does not connect" is all you know, ask the server what it presents and what it negotiates, from outside Go, then from inside.

Common misunderstanding: "The handler logs show nothing, so the client never reached me." Handshake failures are logged by net/http as http: TLS handshake error from ADDR: ... on the server's ErrorLog (stderr by default), and they happen before any handler runs, so access logs and middleware never see them. Raise visibility there first.

Definition and tools:

ToolCommandShows
openssl s_clientopenssl s_client -connect host:443 -servername host -alpn h2 -CAfile ca.crt </dev/nullChain, verification result, protocol, cipher, key-exchange group, ALPN, session ticket
openssl s_client (version probe)add -tls1_2 or -tls1_3Whether a version is accepted
openssl s_client (mTLS)add -cert client.crt -key client.keyWhether the server accepts your client certificate
openssl s_client (hostname)add -verify_hostname namehostname mismatch
curl -vcurl -v --http2 --cacert ca.crt https://host/ALPN: server accepted h2, TLS version and cipher, request and response headers
curl flags--http1.1, --http2, --http3, --tlsv1.3, --tls-max 1.2, --resolve host:443:IP, --cert, --keyForce a protocol, pin an IP, present a certificate
nmap --script ssl-enum-ciphers -p 443 hostthe Nmap NSE script ssl-enum-ciphersWhich cipher suites and versions the server accepts
Go: tlsinfo.Probe / Describethe snippet aboveSame facts, from code
Go: Config.KeyLogWriterwrite the NSS key log to a fileDecrypt a Wireshark capture
Go: GODEBUGsee belowRevert or tune a default
text
 real: openssl s_client against the lab server (OpenSSL 3.6.5)
 Negotiated TLS1.3 group: X25519MLKEM768        <- Go 1.24+ default hybrid key exchange
 Peer signing digest: SHA256, Peer signature type: ecdsa_secp256r1_sha256
 SSL handshake has read 1849 bytes and written 1613 bytes
 Verification: OK     ALPN protocol: h2     Cipher is TLS_AES_128_GCM_SHA256
 real: -verify_hostname wrong.example.test   -> Verification error: hostname mismatch
 real: -tls1_1 (client-side refusal in this OpenSSL build)  -> no protocols available

GODEBUG settings worth knowing, each documented in the release notes, with the version that introduced and (where it happened) removed them:

SettingEffectLifecycle
tlsmlkem=0Disable the default post-quantum hybrid key exchangeGo 1.24
tlssecpmlkem=0Disable the NIST-curve hybridsGo 1.26
tlskyber=0Same for the older Kyber draftGo 1.23, removed in 1.24
tlssha1=1Re-enable SHA-1 signatures in TLS 1.2Go 1.25
tlsmaxrsasize=4096Cap peer RSA key size (default 8192 bits)existing
tls10server, tlsrsakex, tls3des, tlsunsafeekm, x509keypairleafRestore pre-1.22/1.23 defaultsRemoved in Go 1.27
http2server=0Disable HTTP/2 on serversexisting
http2debug=1 or 2Verbose HTTP/2 frame logging (x/net)existing
x509ignoreCN=0Re-enable CN host matchingGo 1.15; long gone for practical purposes

Set them in the environment (GODEBUG=tlsmlkem=0 ./server) or with a //go:debug line in main; a go line in go.mod picks defaults for your language version.

KeyLogWriter is a field on tls.Config; point it at a file and load that file in Wireshark under Preferences, Protocols, TLS, "(Pre)-Master-Secret log filename". The test asserts lines such as CLIENT_HANDSHAKE_TRAFFIC_SECRET appear. "Use of KeyLogWriter compromises security and should only be used for debugging."

Real scenario: after raising MinVersion to TLS 1.3 a partner's integration fails with no handler log. journalctl shows http: TLS handshake error from 203.0.113.9:41231: tls: client offered only unsupported versions: [303 302 301]. The partner's client tops out at TLS 1.2; you choose between a dedicated TLS 1.2 listener and asking them to upgrade.

Server timeouts under load Must-know ​

In plain words: A TLS server spends CPU and memory on every connection before it ever sees a request. A client that connects and then sends nothing, or one byte a minute, holds a slot forever unless the server says "enough".

Common misunderstanding: "ListenAndServeTLS is production-ready." The package-level function builds a server with no timeouts. With ReadHeaderTimeout, ReadTimeout and IdleTimeout all zero, a Slowloris client keeps a connection open indefinitely and idle keep-alive connections are never reaped. The fields fall back to each other: a zero ReadHeaderTimeout uses ReadTimeout, and a zero IdleTimeout uses ReadTimeout too, so a server with only ReadTimeout: 30 * time.Second is bounded but crudely (one value for headers, body and idle). Set them explicitly. Without MaxHeaderBytes the default is DefaultMaxHeaderBytes, 1 MB.

Definition: The same http.Server fields also bound the TLS handshake: tlsHandshakeTimeout "returns the minimum of any positive ReadHeaderTimeout, ReadTimeout, or WriteTimeout", set as the read and write deadline of the connection while HandshakeContext runs. So a server with all three at zero has no handshake timeout at all, and a client that never completes the handshake pins a goroutine. For ReadTimeout: "most users will prefer to use ReadHeaderTimeout. It is valid to use them both."

FieldBoundsTypical API valueTrap
ReadHeaderTimeoutReading request headers (and the TLS handshake)5 sZero falls back to ReadTimeout; both zero means no Slowloris protection
ReadTimeoutWhole request including body30 sBreaks large uploads; use per-request deadlines instead
WriteTimeoutWriting the response30 sBreaks streaming and SSE; use http.ResponseController.SetWriteDeadline
IdleTimeoutKeep-alive wait (HTTP/2 idle connections too)1 to 2 minZero falls back to ReadTimeout; both zero means idle connections stay forever
MaxHeaderBytesHeader size64 KBDefault 1 MB per request
HTTP2.MaxConcurrentStreamsStreams per HTTP/2 connection100Unbounded work per connection if raised carelessly
http.Server.ShutdownGraceful stopn/aPair with GOAWAY for HTTP/2, see signals
text
 Slowloris against a TLS server with ReadHeaderTimeout = 150ms (test output, real)
 1  tls.Dial ok (handshake completes)
 2  client writes "GET / HTTP/1.1\r\nHost: ...\r\n"  and never the blank line
 3  server closes the connection after 150ms          (read error: EOF)
go
// Package timeouts holds the server limits that matter once the server is
// reachable by slow, hostile or simply unlucky clients.
package timeouts

import (
	"crypto/tls"
	"net/http"
	"time"
)

// Limits are the knobs, named after the http.Server fields they set.
type Limits struct {
	ReadHeaderTimeout time.Duration // also bounds the TLS handshake (min of Read*/Write* timeouts)
	ReadTimeout       time.Duration // whole request, body included
	WriteTimeout      time.Duration // from end of request header to end of response
	IdleTimeout       time.Duration // keep-alive wait; HTTP/2 uses it for idle connections
	MaxHeaderBytes    int
	MaxStreams        int // HTTP/2 concurrent streams per connection
}

// Default is a reasonable starting point for an API; streaming endpoints need
// http.ResponseController.SetWriteDeadline per request instead of one global WriteTimeout.
var Default = Limits{
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       30 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       2 * time.Minute,
	MaxHeaderBytes:    64 << 10,
	MaxStreams:        100,
}

// Apply builds the server.
func (l Limits) Apply(addr string, h http.Handler, cfg *tls.Config) *http.Server {
	return &http.Server{
		Addr:              addr,
		Handler:           h,
		TLSConfig:         cfg,
		ReadHeaderTimeout: l.ReadHeaderTimeout,
		ReadTimeout:       l.ReadTimeout,
		WriteTimeout:      l.WriteTimeout,
		IdleTimeout:       l.IdleTimeout,
		MaxHeaderBytes:    l.MaxHeaderBytes,
		HTTP2:             &http.HTTP2Config{MaxConcurrentStreams: l.MaxStreams},
	}
}
go
package timeouts_test

import (
	"crypto/tls"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/pki"
	"academy/http2-https-tls-mtls/timeouts"
)

func TestSlowHeaderIsCutOff(t *testing.T) {
	ca, _ := pki.NewAuthority("ca")
	cert, _ := ca.IssueServer(time.Hour, []string{"api.example.test"}, net.ParseIP("127.0.0.1"))
	l := timeouts.Default
	l.ReadHeaderTimeout = 150 * time.Millisecond

	srv := httptest.NewUnstartedServer(http.NotFoundHandler())
	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
	applied := l.Apply("", http.NotFoundHandler(), cfg)
	srv.Config = applied
	srv.TLS = cfg
	srv.StartTLS()
	defer srv.Close()

	conn, err := tls.Dial("tcp", srv.Listener.Addr().String(), &tls.Config{RootCAs: ca.Pool(), ServerName: "api.example.test", NextProtos: []string{"http/1.1"}})
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	// A request line and one header, but never the blank line that ends the header.
	io.WriteString(conn, "GET / HTTP/1.1\r\nHost: api.example.test\r\n")

	start := time.Now()
	conn.SetReadDeadline(time.Now().Add(3 * time.Second))
	_, err = conn.Read(make([]byte, 1))
	elapsed := time.Since(start)
	if err == nil {
		t.Fatal("server should have closed the connection or answered 408")
	}
	if elapsed > 2*time.Second {
		t.Fatalf("server waited %v; ReadHeaderTimeout did not apply", elapsed)
	}
	t.Logf("slow client dropped after %v (read error: %v)", elapsed.Round(10*time.Millisecond), err)
}

func TestApplySetsEveryLimit(t *testing.T) {
	s := timeouts.Default.Apply(":8443", http.NotFoundHandler(), nil)
	if s.ReadHeaderTimeout == 0 || s.ReadTimeout == 0 || s.WriteTimeout == 0 || s.IdleTimeout == 0 || s.MaxHeaderBytes == 0 {
		t.Fatalf("a limit is zero (unlimited): %+v", s)
	}
	if s.HTTP2.MaxConcurrentStreams != 100 {
		t.Fatalf("MaxConcurrentStreams = %d", s.HTTP2.MaxConcurrentStreams)
	}
}

Real scenario: a public endpoint is overwhelmed by 40,000 half-open TLS connections from a single botnet. With ReadHeaderTimeout: 5 * time.Second each one costs a goroutine for five seconds; a rate limit at the proxy and a per-IP connection cap finish the job (Rate limiting in Go).

Benchmarking with wrk and h2load Must-know ​

In plain words: Point a program that sends as many requests as it can at your server and measure how many per second it answers and how long each takes. Two numbers matter: throughput (requests per second) and latency (how long each request took, especially the slowest few percent).

Common misunderstanding: "My laptop says 80,000 req/s, so production does 80,000 req/s." That number is true for that payload, that hardware, loopback networking (no RTT), no TLS handshake cost if connections were reused, a warm cache, and a generator that was not itself the bottleneck. Change any one and it moves by multiples. A benchmark result without its settings is not a result.

wrk ("a modern HTTP benchmarking tool capable of generating significant load when run on a single multi-core CPU") is a multithreaded, event-driven HTTP/1.1 generator with optional LuaJIT scripting. Its README's example is wrk -t12 -c400 -d30s http://127.0.0.1:8080/index.html: "This runs a benchmark for 30 seconds, using 12 threads, and keeping 400 HTTP connections open."

wrk flagMeaning
-t, --threads"total number of threads to use"
-c, --connections"total number of HTTP connections to keep open with each thread handling N = connections/threads"
-d, --duration"duration of the test, e.g. 2s, 2m, 2h"
--latency"print detailed latency statistics" (the 50/75/90/99 percent table)
--timeout"record a timeout if a response is not received within this amount of time"
-H, --headerAdd a header to every request
-s, --scriptLuaJIT script for request generation, response processing and custom reports

The README's tips matter as much as the flags: "The machine running wrk must have a sufficient number of ephemeral ports available and closed sockets should be recycled quickly. To handle the initial connection burst the server's listen(2) backlog should be greater than the number of concurrent connections being tested."

h2load is nghttp2's load generator: "benchmarking tool for HTTP/2 server". It speaks h2 (TLS with ALPN), h2c, HTTP/1.1 (--h1) and HTTP/3 (--h3).

h2load flagMeaningDefault
-n, --requestsTotal requests across all clients1
-c, --clientsConcurrent clients (connections)1
-t, --threadsNative threads1
-m, --max-concurrent-streamsStreams in flight per connection ("HTTP pipelining" on HTTP/1.1)1
-D, --duration with --warm-up-timeTime-based run, with a warm-up excluded from the numbersoff
-r, --rate and --rate-periodOpen new connections at a fixed rate0
--rpsRequests per second per client (rate limit)off
--h1, --h3Force HTTP/1.1 or HTTP/3h2
-H, --headerAdd or override a headernone
--sniSend another name in SNIhost from URI
--connect-toConnect to another host and port than the URInone
--tls-session-fileRead and store a TLS session, so connections resumeoff
--ciphers, --tls13-ciphers, --groupsCipher lists and key-exchange groupsOpenSSL-style defaults
-w, -WStream and connection window bits30 (effectively no flow control)
--log-filePer-request start time, status, duration (TSV)off
--output-fileJSON including raw samplesoff

On flow control the manual is blunt: "h2load sets large flow control window by default, and effectively disables flow control to avoid under utilization of server performance. To set smaller flow control window, use -w and -W options. For example, use -w16 -W16 to set default window size described in HTTP/2 protocol specification." So a default h2load run does not exercise your server's window handling; set -w16 -W16 when that is what you want to test.

text
 illustrative output shapes (expected, not run: wrk and h2load are not installed on the build machine; the numbers are made up)
 wrk -t4 -c200 -d30s --latency https://localhost:8443/whoami
 Running 30s test @ https://localhost:8443/whoami
   4 threads and 200 connections
   Thread Stats   Avg      Stdev     Max   +/- Stdev
     Latency     1.9ms    1.1ms   40.2ms   91.20%
     Req/Sec    26.1k     2.4k    33.0k    70.40%
   Latency Distribution
      50%    1.7ms    75%    2.2ms    90%    2.9ms    99%    6.8ms
   3120000 requests in 30.00s, 560.4MB read
 Requests/sec: 104000.0      Transfer/sec: 18.7MB
 h2load -n 200000 -c 50 -m 10 -t 4 https://localhost:8443/whoami
 finished in 2.10s, 95238 req/s
 requests: 200000 total, 200000 started, 200000 done, 200000 succeeded, 0 failed, 0 errored, 0 timeout
 time for request:  min 0.4ms  max 38ms  mean 5.1ms  sd 2.3ms  +/- sd 88%     (plus median, p95, p99)
 time for connect:  min 3.2ms  max 11ms  mean 6.0ms
 time to 1st byte:  min 4.1ms  max 15ms  mean 7.5ms

The h2load manual defines the report: request is "the duration from sending the first byte of a request to receiving the last byte of the response"; connect is "the time taken to establish a connection, including TLS handshakes"; TTFB is the time to the first byte of application data; failed includes "requests that completed with a non-2xx/3xx status code", and errored is the network-level subset. Check these before you quote a req/s figure: a server returning 503 quickly looks wonderful.

How to read latency. Percentiles answer "what fraction of requests took at most this long". p50 is the typical request; p99 is the one in a hundred, and a user who makes 30 requests per page view sees the p99 on about a quarter of page views (1 - 0.99^30). The mean hides tails; the standard deviation assumes a bell curve that latency does not have. Report p50, p90, p99 and p99.9 together with the error count and the concurrency; these latency percentiles are the headline of any result.

NumberWhat it tells youWhat it hides
Requests/secThroughput at this concurrencyWhether latency was acceptable
Mean latencyAverage costEverything about the tail
p50Typical requestSlow outliers
p99, p99.9What your unluckiest users feelNeeds many samples: p99.9 from 1,000 requests is one sample
MaxThe worst single requestOne GC pause or one dropped SYN
Errors, timeouts, non-2xxWhether the run was validNothing; look first

Little's law ties them together: concurrency = throughput × latency. 200 connections that each wait 10 ms per request can complete at most 20,000 req/s, so raising -c raises throughput only until the server saturates; past that point throughput stays flat and latency grows (the "knee"). Find the knee, then run at 60 to 70 percent of it.

Benchmarking an HTTPS server: who generates load, who is measuredLoad generator hostwrk -t4 -c200 -d30s --latencyh2load -n100000 -c50 -m10hey / oha / vegeta attackthreads, connections,streams per connectionmust not be the bottleneckNetworkRTT adds to every handshakeloopback hides itsame region, same size VMGo server under testGOMAXPROCS (cgroup aware from Go 1.25)ReadHeaderTimeout, IdleTimeoutulimit -n, MaxConcurrentStreamspprof on 127.0.0.1 onlyWhat to read from the outputRequests/seconly meaningful with0 errors and a fixed payloadp50 / p90 / p99 / p99.9the tail is the userexperience, not the meanErrors, timeouts,non-2xx, resetscount before comparingCPU profilego tool pprofduring the runClosed loop (wrk, h2load, hey): each connection waits for its reply before sending again.When the server stalls, the generator stops sending, so queueing delay never reaches the percentiles.That is coordinated omission. Constant-rate tools (vegeta -rate, wrk2 -R, oha --latency-correction)are built to avoid it. h2load --rps only limits the rate; its latency starts at the first byte sent.Warm up first; compare TLS and plain runs with identical settings.

Connections and keep-alive decide what you are measuring. With keep-alive, -c 200 pays 200 TLS handshakes once and then measures request handling. Without it (Connection: close, hey -disable-keepalive, oha --disable-keepalive) every request pays TCP and TLS, which the loopback numbers above show is about 15 times as expensive in CPU; that is a legitimate test for a server that faces many short-lived clients, and a misleading one for an API behind a connection-pooling gateway. For HTTP/2 the unit is streams: h2load -c 10 -m 100 is 1,000 concurrent requests on ten connections, which is what a browser or gRPC client looks like, while wrk -c 1000 is 1,000 connections.

A minimal Go closed-loop generator (to read, not to replace the real tools) shows exactly what the percentile maths does, including the nearest-rank percentile and the coordinated-omission warning in its comment:

go
// Package loadgen is a minimal closed-loop load generator, small enough to
// read in one sitting. It exists to explain what wrk, hey and h2load report;
// use the real tools for real measurements.
package loadgen

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"slices"
	"sync"
	"time"
)

// Result summarises one run. Errors counts transport failures and responses
// outside 2xx/3xx; latencies and RPS cover successful requests only.
type Result struct {
	Requests, Errors    int
	Elapsed             time.Duration
	RPS                 float64
	P50, P90, P99, P999 time.Duration
	Min, Max            time.Duration
}

// Percentile returns the p-th percentile (0..100) of an ascending slice using
// the nearest-rank method: the smallest value with at least p percent of the
// samples at or below it.
func Percentile(sorted []time.Duration, p float64) time.Duration {
	if len(sorted) == 0 {
		return 0
	}
	rank := int(p/100*float64(len(sorted)) + 0.999999)
	rank = min(max(rank, 1), len(sorted))
	return sorted[rank-1]
}

// Run sends total GET requests with `concurrency` workers that each wait for
// a response before sending the next one (closed loop). A closed loop slows
// down when the server slows down and so under-reports queueing delay: this
// is the "coordinated omission" problem that wrk2 and vegeta's constant-rate
// attack mode avoid.
func Run(ctx context.Context, c *http.Client, url string, concurrency, total int) Result {
	jobs := make(chan struct{}, total)
	for range total {
		jobs <- struct{}{}
	}
	close(jobs)

	var (
		mu      sync.Mutex
		lat     = make([]time.Duration, 0, total)
		errs    int
		wg      sync.WaitGroup
		started = time.Now()
	)
	for range concurrency {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for range jobs {
				t0 := time.Now()
				err := get(ctx, c, url)
				d := time.Since(t0)
				mu.Lock()
				if err != nil {
					errs++
				} else {
					lat = append(lat, d)
				}
				mu.Unlock()
			}
		}()
	}
	wg.Wait()

	r := Result{Requests: total, Errors: errs, Elapsed: time.Since(started)}
	slices.Sort(lat)
	if len(lat) > 0 {
		r.Min, r.Max = lat[0], lat[len(lat)-1]
		r.P50, r.P90 = Percentile(lat, 50), Percentile(lat, 90)
		r.P99, r.P999 = Percentile(lat, 99), Percentile(lat, 99.9)
	}
	r.RPS = float64(total-errs) / r.Elapsed.Seconds()
	return r
}

func get(ctx context.Context, c *http.Client, url string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	resp, err := c.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if _, err = io.Copy(io.Discard, resp.Body); err != nil { // drain, or the connection cannot be reused
		return err
	}
	// Same convention as h2load: only 2xx and 3xx count as success. A server
	// answering 503 instantly must not look fast.
	if resp.StatusCode < 200 || resp.StatusCode >= 400 {
		return fmt.Errorf("status %d", resp.StatusCode)
	}
	return nil
}
go
package loadgen_test

import (
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
	"time"

	"academy/http2-https-tls-mtls/loadgen"
)

func TestPercentileNearestRank(t *testing.T) {
	var s []time.Duration
	for i := 1; i <= 100; i++ {
		s = append(s, time.Duration(i)*time.Millisecond)
	}
	for _, tc := range []struct {
		p    float64
		want time.Duration
	}{{50, 50 * time.Millisecond}, {90, 90 * time.Millisecond}, {99, 99 * time.Millisecond}, {100, 100 * time.Millisecond}, {0, time.Millisecond}} {
		if got := loadgen.Percentile(s, tc.p); got != tc.want {
			t.Errorf("p%v = %v, want %v", tc.p, got, tc.want)
		}
	}
	if loadgen.Percentile(nil, 99) != 0 {
		t.Error("empty input must give 0")
	}
}

func TestRunCountsAndOrdersPercentiles(t *testing.T) {
	var hits atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		if hits.Add(1)%50 == 0 {
			time.Sleep(20 * time.Millisecond) // a slow tail: 2 percent of requests
		}
	}))
	defer srv.Close()

	r := loadgen.Run(t.Context(), srv.Client(), srv.URL, 8, 200)
	if r.Requests != 200 || r.Errors != 0 || int(hits.Load()) != 200 {
		t.Fatalf("result %+v, server hits %d", r, hits.Load())
	}
	if !(r.Min <= r.P50 && r.P50 <= r.P90 && r.P90 <= r.P99 && r.P99 <= r.P999 && r.P999 <= r.Max) {
		t.Fatalf("percentiles out of order: %+v", r)
	}
	if r.P99 < 10*time.Millisecond {
		t.Fatalf("p99 %v should expose the slow tail (4 requests of 200 took 20ms)", r.P99)
	}
	if r.P50 > 10*time.Millisecond {
		t.Fatalf("p50 %v should stay fast", r.P50)
	}
}

func TestNon2xx3xxResponsesAreErrors(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusServiceUnavailable)
		w.Write([]byte("overloaded"))
	}))
	defer srv.Close()
	r := loadgen.Run(t.Context(), srv.Client(), srv.URL, 4, 40)
	if r.Errors != 40 || r.RPS != 0 {
		t.Fatalf("a 503 must count as a failed request (h2load: failed includes non-2xx/3xx): %+v", r)
	}
}

Real scenario: after moving a service from HTTP/1.1 to HTTP/2 behind the same load balancer the team measured with wrk and saw no gain, because wrk never spoke HTTP/2. h2load -c 20 -m 50 and a browser trace showed the gain: connection count fell from 2,000 to 20 and handshake CPU with it.

hey, oha, vegeta and the others: a comparison Important ​

In plain words: There are many load generators; they differ in whether they speak HTTP/2, whether they wait for a reply before sending the next request (closed loop) or send on a schedule (open loop), and how they report percentiles.

Common misunderstanding: "Open loop and closed loop give the same latency." They do not. In a closed loop each connection waits for its reply; when the server stalls the generator stops sending, so the stall appears as one slow request instead of the hundreds of requests that would have queued. The wrk2 README describes the model that wrk and "many current load generators" share: latency is computed from the first byte sent, so it "exhibits a strong Coordinated Omission effect, through which most of the high latency artifacts exhibited by the measured server will be ignored", and its fix is a constant-throughput mode (-R, "wrk modifed to produce a constant throughput load"); oha has --latency-correction ("Correct latency to avoid coordinated omission problem", only with -q); vegeta is built around a constant -rate.

ToolLanguageProtocolsModelKey flagsTLS / client certs
wrkCHTTP/1.1Closed-t -c -d --latency --timeout -shttps URLs
wrk2CHTTP/1.1Open, -R rate-t -c -d -R --latencyhttps URLs
h2loadC++h2, h2c, h1, h3Closed; --rps is a per-client rate limit (latency still measured from the first byte sent)-n -c -m -t -D -r --rps --h1 --h3--tls-session-file, --sni, --ciphers, --groups
heyGoHTTP/1.1, HTTP/2 (-h2)Closed; -q per worker-n -c -z -q -m -H -d -disable-keepalive-h2 for HTTP/2 endpoints
ohaRustHTTP/1.1, HTTP/2 (--http2, -p parallel streams)Closed; -q overall with --latency-correction-n -c -p -z -q --disable-keepalive--cacert, --cert, --insecure
vegetaGoHTTP/1.1, -http2, -h2cOpen, -rateattack -rate -duration -workers -max-workers -connections -keepalive -session-tickets-root-certs, -cert, -key, -insecure

Notes grounded in the READMEs: hey "supports HTTP2 endpoints" and its -q limit is per worker, while oha's -q "is set overall query per second instead of for each workers" (oha runs c * p concurrent workers on HTTP/2); vegeta reports can be text, json, hist[buckets] or hdrplot, and its README says -rate=0 used together with -max-workers models "a fixed set of concurrent users sending requests as fast as possible" (a closed loop); vegeta's -session-tickets and -keepalive flags control exactly the handshake behaviour this chapter is about.

Picking one.

You wantUse
The highest request rate one machine can generate against HTTP/1.1wrk
Honest tail latency at a chosen arrival ratevegeta attack -rate, wrk2 -R, oha -q ... --latency-correction (h2load --rps only limits the rate)
HTTP/2 or HTTP/3 behaviour, streams, TLS resumptionh2load
A quick look from a laptop, readable outputhey or oha
Realistic user flows (login, cart, checkout)A scripting tool such as k6 (not covered here) or a Go program
Repeatable CI regression budgetvegeta with a saved result file, compared run to run

Real scenario: the SLO says "p99 under 200 ms at 2,000 requests per second". The team runs echo "GET https://api.example.test/orders" | vegeta attack -rate=2000 -duration=60s -http2 | vegeta report -type=text from a second machine in the same region. A closed-loop run with 200 connections would have reported the same server as comfortably fast, because it slows its own offered load when the server slows down.

GOMAXPROCS and connections, and pprof while benchmarking Important ​

In plain words: A benchmark is also a test of the machine around the server: how many CPUs Go thinks it has, how many file descriptors it may open, whether the generator itself is starved.

Common misunderstanding: "More connections always means more throughput." Beyond the point where the server's CPUs are saturated, extra connections only add queueing, memory and context switches. Likewise "GOMAXPROCS equals the CPUs in my container": that is true only from Go 1.25, which made the default container-aware: "On Linux, the runtime considers the CPU bandwidth limit of the cgroup containing the process, if any" (Kubernetes CPU limits, not requests), and "the runtime periodically updates GOMAXPROCS". Before Go 1.25, a pod limited to 2 CPUs on a 64-core node ran with GOMAXPROCS=64, causing throttling and tail-latency spikes unless you used uber-go/automaxprocs ("Automatically set GOMAXPROCS to match Linux container CPU quota"; its README shows P99 rising when GOMAXPROCS exceeds the quota) or set the variable yourself. The automatic behaviour is disabled "if GOMAXPROCS is set manually via the GOMAXPROCS environment variable or a call to runtime.GOMAXPROCS" (and by GODEBUG containermaxprocs=0, updatemaxprocs=0).

ResourceSymptom when shortCheckFix
CPU on the serverThroughput flat, latency rising, top at 100%go tool pprof CPU profileFewer allocations, ECDSA certificate, keep-alive, more replicas
CPU on the generatorLatency noise, low rate on a fast servertop on the generator hostSeparate machine, more threads, wrk -t
GOMAXPROCS above the cgroup quota (before Go 1.25)Periodic latency spikes (CFS throttling)cpu.stat in the cgroup (nr_throttled)Go 1.25+, automaxprocs, or set the env var
File descriptorsaccept: too many open filesulimit -n, lsofGo raises the soft limit to the hard limit at start since Go 1.19; raise the hard limit
Ephemeral ports (generator)connect: cannot assign requested addressnet.ipv4.ip_local_port_range (kernel ip-sysctl docs)Reuse connections; more source IPs
Listen backlogConnection resets in the first secondnet.core.somaxconn ("Limit of socket listen() backlog"), ss -lntRaise net.core.somaxconn above -c
TLS handshake CPUHigh crypto/tls and crypto/ecdsa share in the profilepprof topResumption, ECDSA, avoid RSA-4096, terminate at a proxy
GC pressureruntime.gcBgMarkWorker in the profileGODEBUG=gctrace=1Reduce allocations; GOGC, GOMEMLIMIT

Profile while you benchmark. Expose net/http/pprof on a loopback-only port, run the load, and capture 30 seconds of CPU: go tool pprof -http=:0 http://127.0.0.1:6060/debug/pprof/profile?seconds=30. A handshake-heavy run is dominated by crypto/internal/... and crypto/ecdsa frames; a keep-alive run by net/http parsing, your handler, and the garbage collector. Never mount pprof on the public TLS listener, and remember that importing net/http/pprof registers its handlers on http.DefaultServeMux even if you never use it (the snippet's test documents the trap).

go
// Package pprofmux exposes net/http/pprof on its own mux and its own
// loopback listener, so profiling a benchmark never goes through the public
// TLS port. Caveat: importing net/http/pprof at all registers the same
// handlers on http.DefaultServeMux in its init function, so never serve
// DefaultServeMux on a public port in a binary that links this package.
package pprofmux

import (
	"net/http"
	"net/http/pprof"
)

// Handler returns the pprof endpoints on a private mux.
func Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index)
	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile) // ?seconds=30 CPU profile
	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
	return mux
}

// Serve runs it on 127.0.0.1 only:  go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
func Serve(addr string) *http.Server {
	if addr == "" {
		addr = "127.0.0.1:6060"
	}
	return &http.Server{Addr: addr, Handler: Handler()}
}
go
package pprofmux_test

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/http2-https-tls-mtls/pprofmux"
)

func TestIndexListsProfiles(t *testing.T) {
	srv := httptest.NewServer(pprofmux.Handler())
	defer srv.Close()
	resp, err := http.Get(srv.URL + "/debug/pprof/")
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != 200 || !strings.Contains(string(body), "goroutine") {
		t.Fatalf("status %d body %.80q", resp.StatusCode, body)
	}
}

// The import itself registers pprof on DefaultServeMux (see the package
// comment). This test documents the trap so nobody is surprised by it.
func TestImportAlsoRegistersOnDefaultServeMux(t *testing.T) {
	rec := httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(rec, httptest.NewRequest("GET", "/debug/pprof/", nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("status %d: pprof is not on DefaultServeMux any more; update the package comment", rec.Code)
	}
}

Real scenario: a service in a pod limited to 4 CPUs on a 96-core node shows p99 spikes every 100 ms under load (the CFS scheduling period). Upgrading from Go 1.24 to 1.25 with no code change removes the spikes, because GOMAXPROCS drops from 96 to 4 automatically.

Mechanics ​

The handshake, step by step Important ​

TLS 1.3 handshake: one round trip, then HTTP/2 on the same connectionClient (browser, curl)Go server (crypto/tls)1 ClientHello: SNI, ALPN [h2, http/1.1], key_share X25519MLKEM768 + X255192 ServerHello: TLS 1.3, chosen key_share (everything below is encrypted)3 EncryptedExtensions: ALPN = h2 (+ CertificateRequest if mTLS)4 Certificate, CertificateVerify, Finished5 [Certificate, CertificateVerify if mTLS], Finishedclient verifies the chain, the host name (SAN) and the signature6 HTTP/2 preface + SETTINGS + first request (application data)7 NewSessionTicket (after the handshake) + response1 RTTResumed connection: step 1 also carries a pre_shared_key (the ticket); the server skips Certificateand CertificateVerify, saving bytes and signature work. Go still does a fresh key exchange.0-RTT early data: a Go server never accepts it (a client's early_data gets an alert),so there is no replay window to design for. quic-go for HTTP/3 does support 0-RTT.

What crypto/tls does on the server for a TLS 1.3 connection, following readClientHello and serverHandshakeStateTLS13.handshake() in the Go 1.27 source: readClientHello first calls GetConfigForClient if set (it may swap the whole config) and only then picks the version (mutualVersion; since Go 1.25 the highest both support). Then processClientHello chooses the cipher suite (AES-GCM first only when the hardware and the client prefer it, otherwise ChaCha20-Poly1305 first: "preferenceList := defaultCipherSuitesTLS13" and a no-AES variant), the key exchange from CurvePreferences and the client's key_share (X25519MLKEM768 first when the client offers it), and the ALPN protocol (negotiateALPN). checkForResumption looks at a presented ticket. pickCertificate calls GetCertificate (or takes the Certificates entry compatible with the SNI and signature algorithms). sendServerParameters sends EncryptedExtensions, sendServerCertificate sends the optional CertificateRequest, Certificate and CertificateVerify, sendServerFinished sends Finished, and the flight is flushed. readClientCertificate verifies the client's certificate (ClientAuth, ClientCAs) and runs VerifyPeerCertificate then VerifyConnection; readClientFinished closes the handshake; sendSessionTickets issues NewSessionTicket messages. TLS 1.2 is the older two-round-trip flow with the same hooks, plus key exchange in ServerKeyExchange.

StepRound trips so farHook you control
TCP connect1net.Dialer, ConnContext, listener
ClientHello received1.5GetConfigForClient, ClientHelloInfo fields (ServerName, SupportedProtos, SupportedVersions, Extensions)
Certificate chosen1.5GetCertificate, Certificates
Client authenticated (mTLS)2ClientAuth, ClientCAs, VerifyPeerCertificate, VerifyConnection
First request byte accepted2 on a fresh connectionReadHeaderTimeout also covers the handshake
Resumed connectionsame count, no certificate workSessionTicketsDisabled, SetSessionTicketKeys, WrapSession

What net/http does with a TLS connection Important ​

Server.Serve accepts a connection from the TLS listener; the per-connection goroutine sets the handshake deadline (the minimum of ReadHeaderTimeout, ReadTimeout and WriteTimeout), calls HandshakeContext, and on failure logs http: TLS handshake error from ADDR: REASON and closes. If the first bytes were plain HTTP it writes HTTP/1.0 400 Bad Request with the body "Client sent an HTTP request to an HTTPS server." on the raw connection (and logs the same reason in lower case) instead of the raw reason tls: first record does not look like a TLS handshake. After a successful handshake it stores a copy of ConnectionState (this becomes r.TLS), reads NegotiatedProtocol, and for h2 hands the connection to the HTTP/2 server (via TLSNextProto), otherwise serves HTTP/1.1. Everything before that point is invisible to middleware: no access log line, no metrics, no request context.

Verbatim errors and alerts Must-know ​

Client-side errors (from crypto/x509 and crypto/tls):

TextTypeCauseFix
x509: certificate signed by unknown authorityx509.UnknownAuthorityErrorIssuer not in RootCAs or the system pool (macOS prints x509: “server” certificate is not trusted)Add the CA; serve the intermediate
x509: certificate is valid for a.example, not b.examplex509.HostnameErrorSAN does not include the nameReissue, or set ServerName
x509: certificate is valid for 2 names, but none matched b.examplex509.HostnameErrorSame, when there are many SANsSame
x509: cannot validate certificate for 10.0.0.5 because it doesn't contain any IP SANsx509.HostnameErrorDialled an IP, certificate has only DNS SANsAdd an IP SAN or dial the name
x509: certificate has expired or is not yet valid: ...x509.CertificateInvalidErrorClock skew or expiryRenew; check NTP
x509: certificate specifies an incompatible key usagex509.CertificateInvalidErrorMissing serverAuth or clientAuth EKUReissue with the right EKU
tls: failed to verify certificate: ...*tls.CertificateVerificationErrorWrapper; the cause is in .Errerrors.As and read Err
tls: first record does not look like a TLS handshaketls.RecordHeaderErrorSpoke TLS to a plain portFix scheme or port
http: server gave HTTP response to HTTPS clienthttp.ErrSchemeMismatch (Go 1.21)https:// to a plain portSame
remote error: tls: bad certificatealert 42The server rejected our client certificate, for example because its own VerifyConnection returned an error (the alert hides the reason)Check the server log
remote error: tls: certificate requiredalert 116mTLS server and we sent nonePresent a certificate
remote error: tls: unknown certificate authorityalert 48Server does not trust our client certificate's issuerFix ClientCAs
remote error: tls: expired certificatealert 45The peer's certificate or ours is expiredRenew
remote error: tls: protocol version not supportedalert 70No common version (MinVersion too high for the peer)Align versions
remote error: tls: no application protocolalert 120ALPN lists do not overlapAlign NextProtos

Server-side texts (the http: TLS handshake error from ... suffix):

TextMeaning
tls: client offered only unsupported versions: [303 302 301]The client's best version is below MinVersion (hex of 0x0303 and so on)
tls: no cipher suite supported by both client and server; client offered: [...]CipherSuites and the client's list do not overlap (TLS 1.2)
tls: client requested unsupported application protocols (["x"])ALPN mismatch
tls: client didn't provide a certificatemTLS required, client sent none
tls: client sent unexpected early dataA client tried 0-RTT; Go does not accept it
tls: no certificates configured / tls: neither Certificates, GetCertificate, nor GetConfigForClient set in ConfigThe server config has no certificate source
remote error: tls: bad certificateThe client rejected our certificate
EOF / connection reset by peerThe client gave up mid-handshake (often a health check or scanner)

How a certificate is verified Important ​

x509.Certificate.Verify(VerifyOptions) builds a path from the leaf, through the intermediates the peer sent plus Intermediates you add, to a root in Roots (nil means "the system roots or the platform verifier"). It checks each certificate's validity period at CurrentTime, that the chain's extended key usages include one of KeyUsages (server verification asks for serverAuth and mTLS server-side asks for clientAuth; an empty list means serverAuth), basic constraints (an intermediate must be a CA with room in its path length), name constraints, and, in the TLS client, the host name against the SAN with VerifyHostname. It does not check revocation: the source says "WARNING: this function doesn't do any revocation checking". On macOS and Windows the default verifier asks the operating system, which is why the "unknown authority" text differs between your laptop and a Linux container, and from Go 1.27 SystemCertPool also honours SSL_CERT_FILE and SSL_CERT_DIR on macOS and Windows (set, they make Go use its own verifier with roots from disk).

Solving the classic problems ​

ProblemSymptomSolutionCost or limit
Client does not trust the serverx509: certificate signed by unknown authorityAdd the CA to RootCAs; serve the full chainDistribute the CA
Name mismatchcertificate is valid for a, not bSAN with every name and IP you dial; set ServerNameReissue
Server log full of TLS handshake errorremote error: tls: bad certificate from clientsRead the client's error; usually trust or nameScanners add noise: filter the log
HTTP/2 silently offresp.Proto == "HTTP/1.1" against an h2 serverForceAttemptHTTP2: true on custom transports; "h2" in NextProtos when using ServeNone
Certificate expires in productionOutage at 00:00 UTCReloader plus alert at 14 days; autocertMonitoring
mTLS identity bypass on resumeAuthorisation skipped for returning clientsCheck in VerifyConnection, not VerifyPeerCertificateNone
Slowloris and idle socketsGoroutines and sockets pile upReadHeaderTimeout, IdleTimeout, MaxHeaderBytes, proxy limitsTune per endpoint
Handshake CPU dominatesHigh crypto/* in the profileKeep-alive, resumption, ECDSA, terminate at proxyOperational complexity
Benchmark liesGreat numbers, bad productionOpen-loop generator, separate machine, errors checked, warm-up, real networkMore setup
Long-lived connections ignore the new certificateOld chain after rotationPeriodic GOAWAY, max connection age, rolling restartReconnect storms: add jitter

Unknown CA, name mismatch, wrong scheme Must-know ​

Do not reach for InsecureSkipVerify. Print the real error, classify it with errors.As, and fix its cause:

go
resp, err := client.Get(url)
var cve *tls.CertificateVerificationError
var host x509.HostnameError
var unknown x509.UnknownAuthorityError
switch {
case errors.As(err, &host):
	log.Printf("name not in certificate: %v", host)          // fix SAN or ServerName
case errors.As(err, &unknown):
	log.Printf("CA not trusted: %v", unknown)                  // fix RootCAs or the chain
case errors.As(err, &cve):
	log.Printf("verification failed: %v", cve.Err)             // expired, EKU, constraints
case errors.Is(err, http.ErrSchemeMismatch):
	log.Printf("plain HTTP answered an https:// request")      // fix scheme or port
}
_ = resp

On macOS the platform verifier may return a different concrete type for an unknown CA, so the after test asserts only *tls.CertificateVerificationError; treat the wrapper as the stable contract.

Mutual TLS that actually authorises Must-know ​

Use RequireAndVerifyClientCert, a dedicated ClientCAs pool, short-lived client certificates, and a VerifyConnection allow list, as in mtls.ServerConfig. Rotate both server and client certificates (Rotation). If you also use a database that supports client certificates, check it the same way; for PostgreSQL the server's own view is queryable:

sql
-- PostgreSQL: which connections use TLS, with which version, and which client certificate?
SELECT a.usename, a.client_addr, s.ssl, s.version, s.cipher, s.client_dn, s.client_serial
FROM pg_stat_ssl s
JOIN pg_stat_activity a USING (pid)
WHERE a.backend_type = 'client backend';
text
 pg_hba.conf (PostgreSQL docs, section "SSL Client Certificates"): demand a verified certificate whose CN matches the user
 hostssl  all  all  10.0.0.0/8  scram-sha-256  clientcert=verify-full

Make benchmarks honest Must-know ​

  1. Run the generator on another machine in the same network as production clients, same instance class, never on the server.
  2. Warm up (h2load -D 60 --warm-up-time=10), then measure.
  3. Fix the payload and say whether TLS, keep-alive and HTTP/2 were on.
  4. Check errors, timeouts and non-2xx counts before reading anything else.
  5. Sweep concurrency (50, 100, 200, 400 connections) and plot throughput and p99; the knee is the capacity, not the peak.
  6. Use an open-loop tool for latency claims (tools).
  7. Repeat three times and report the spread; one run proves nothing.
  8. Profile during the run (tuning) and fix the top frame before buying hardware.

Choosing ​

SituationRecommendationExtra techniqueReason
Public website or API, one VMGo terminates TLS with autocert, MinVersion TLS 1.2, HSTSRedirect on :80, persistent DirCache, HostPolicyZero moving parts
Public API behind a cloud load balancerTerminate at the LB, h2c or HTTP to GoTrust X-Forwarded-* from the LB onlyThe platform renews certificates
Kubernetes, many servicesIngress terminates; mesh or Go mTLS insidecert-manager, Reloader, SPIFFE IDsZero trust between pods
Service to service, you own both endsmTLS, MinVersion TLS 1.3, RequireAndVerifyClientCertAllow list in VerifyConnection, hour-long certificatesStrong identity, small attack surface
Browser-facing, mobile users on bad networksHTTP/2 at the origin; HTTP/3 at a CDN or quic-go edgeAlt-Svc, UDP 443 openLoss tolerance
Local developmentmkcert or the in-code CARootCAs, never InsecureSkipVerifySame code path as production
Talking to a device with a self-signed certificatePin its keypin.ConfigAuthenticates without a CA
Legacy TLS 1.2-only partnerSeparate listener with MinVersion TLS 1.2Keep the main listener at TLS 1.3Contain the exception
Streaming or SSE endpointsPer-request ResponseController.SetWriteDeadlineNo global WriteTimeoutAvoid killing long responses
Capacity testh2load or vegeta, separate hostWarm-up, concurrency sweep, pprofDefensible numbers
"Is my TLS config good?"Mozilla intermediate or modern profilessl-config.mozilla.org, nmap ssl-enum-ciphers, openssl s_clientAn external yardstick

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Go binary on one host. The simplest correct setup is autocert on :443 with a DirCache on disk, a redirect plus HostPolicy on :80, HSTS on responses, the timeouts from timeouts.Default and a graceful Shutdown on SIGTERM. The database is on localhost or a private network; connect with TLS anyway if it is on another host (PostgreSQL's hostssl). Certificates live on one disk; the failure mode is the renewal job dying silently, so export NotAfter as a metric. HTTP/2 comes for free. A benchmark of this setup is h2load from a second small VM.

Modular monolith and multiple databases ​

Modules share a process, so no TLS between them; the TLS boundary is the process edge and each outbound dependency (PostgreSQL, Redis, an object store, a payment provider). Give each outbound client its own *http.Client or pool with its own RootCAs and ServerName, because a partner's private CA must not become trusted for everything. Per-client Transports also give you separate connection pools and ClientSessionCaches, so a slow partner cannot exhaust handshakes meant for the database. Keep one tls.Config factory with the policy (MinVersion, RootCAs from the platform bundle) and let modules add only ServerName and client certificates.

Microservices ​

Three choices: the mesh does mTLS (Istio or Linkerd, which document mutual TLS between workloads; Go code speaks plain HTTP or h2c to the sidecar), Go does mTLS itself (mtls.ServerConfig, SPIFFE IDs, a certificate source such as SPIRE or cert-manager), or the cluster network enforces it. A Go-native flow: the orders service dials https://payments.internal with a client certificate whose URI SAN is spiffe://example.test/ns/prod/sa/orders; payments verifies the chain against the platform CA, checks the allow list in VerifyConnection and logs the identity with each request (context carries it down the call chain). Certificates are hours long and rotate through a Reloader; HTTP/2 multiplexes the calls (and gRPC rides on top, see gRPC); deadlines propagate in the request, not in TLS. Handshakes happen once per connection, so keep pools warm and avoid DisableKeepAlives. The architecture view of the same topic is mTLS service security.

Distributed data: replicas, caches, sharded databases, multi-region ​

TLS terminates at every hop: client to edge, edge to service, service to cache and database, replica to replica. Each hop adds a handshake to a cold path, so connection pools and ClientSessionCache are not an optimisation but a latency budget item; across regions the handshake RTT is tens of milliseconds, so pooled connections and resumption matter far more than on loopback (the loopback table above hides this entirely). Ticket keys shared across replicas let a client reconnect to any of them with a resumed handshake. Replication streams (PostgreSQL streaming replication, Redis, Kafka) accept TLS and client certificates: use them, and use the same CA hierarchy and rotation approach as services so one expiry calendar covers everything. Anycast and multi-region ingress means the same certificate (or per-region ones) must be available everywhere: with autocert this requires a shared cache; with a CDN or global load balancer the provider handles it.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesTLS and HTTP/2 practice
1× (one instance)Correctnessautocert or a certificate file, timeouts, HSTS, redirect; h2load smoke test
10× (a few instances behind a load balancer)Certificates on several nodes; handshakes spreadTerminate at the LB or share a certificate source; shared ticket keys; per-instance GOMAXPROCS right-sized (Go 1.25+ container-aware)
100× (many services, regions, CDN)Identity, rotation and tail latency dominatemTLS with short-lived SPIFFE certificates, mesh or Go reloaders, HTTP/3 at the edge, connection pools sized with MaxConcurrentStreams, open-loop capacity tests, pprof in staging under load

Lab ​

All commands run from docs/snippets/go/http2-https-tls-mtls/go with export PATH=/opt/homebrew/bin:$PATH on macOS (adapt the path elsewhere).

1. Run the tests (real) ​

bash
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok    academy/http2-https-tls-mtls/acmecfg      1.526s
# ok    academy/http2-https-tls-mtls/after        1.558s
# ok    academy/http2-https-tls-mtls/before       1.539s
# ok    academy/http2-https-tls-mtls/bench        1.531s [no tests to run]
# ?     academy/http2-https-tls-mtls/demo         [no test files]
# ok    academy/http2-https-tls-mtls/ech          1.516s
# ok    academy/http2-https-tls-mtls/h2server     1.546s
# ok    academy/http2-https-tls-mtls/loadgen      1.562s
# ok    academy/http2-https-tls-mtls/mtls         1.460s
# ok    academy/http2-https-tls-mtls/pin          1.416s
# ok    academy/http2-https-tls-mtls/pki          1.380s
# ok    academy/http2-https-tls-mtls/pprofmux     1.402s
# ok    academy/http2-https-tls-mtls/redirect     1.488s
# ok    academy/http2-https-tls-mtls/resume       1.568s
# ok    academy/http2-https-tls-mtls/rotate       1.578s
# ok    academy/http2-https-tls-mtls/timeouts     1.667s
# ok    academy/http2-https-tls-mtls/tlsinfo      1.516s
# ok    academy/http2-https-tls-mtls/unencrypted  1.505s

2. HTTP/2 over TLS 1.3 with curl and openssl (real) ​

bash
go run ./demo -dir /tmp/tlslab &        # writes ca.crt, server.crt/key, client.crt/key, listens on 127.0.0.1:8443
sleep 2                                  # give it time to start
curl -s --http2   --cacert /tmp/tlslab/ca.crt https://localhost:8443/whoami
# {"proto":"HTTP/2.0","tls_version":"TLS 1.3","alpn":"h2","cipher":"TLS_CHACHA20_POLY1305_SHA256","sni":"localhost","resumed":false}
curl -s --http1.1 --cacert /tmp/tlslab/ca.crt https://localhost:8443/whoami
# {"proto":"HTTP/1.1","tls_version":"TLS 1.3","alpn":"http/1.1", ...}
curl -sv --http2 --cacert /tmp/tlslab/ca.crt https://localhost:8443/whoami 2>&1 | grep -E "ALPN|SSL connection"
# * ALPN: curl offers h2,http/1.1
# * SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256 / [blank] / UNDEF
# * ALPN: server accepted h2
/opt/homebrew/opt/openssl@3/bin/openssl s_client -connect 127.0.0.1:8443 -servername localhost \
  -CAfile /tmp/tlslab/ca.crt -alpn h2 </dev/null 2>&1 | grep -E "group|Verification|ALPN|Cipher is"
# Negotiated TLS1.3 group: X25519MLKEM768
# Verification: OK
# New, TLSv1.3, Cipher is TLS_AES_128_GCM_SHA256
# ALPN protocol: h2
pkill -f 'demo -dir /tmp/tlslab'           # stop this server: lab 3 uses its own directory and port

Notice that the two clients got different cipher suites from the same server: Go chooses by hardware and by what the client prefers.

3. mTLS: refuse, then admit (real) ​

bash
go run ./demo -dir /tmp/tlslab-mtls -mtls -addr 127.0.0.1:8444 &   # own directory and port: nothing from lab 2 is overwritten
sleep 2
curl -s --cacert /tmp/tlslab-mtls/ca.crt https://localhost:8444/identity ; echo "exit=$?"
# exit=56                                   (server log: tls: client didn't provide a certificate)
curl -s --cacert /tmp/tlslab-mtls/ca.crt --cert /tmp/tlslab-mtls/client.crt --key /tmp/tlslab-mtls/client.key https://localhost:8444/identity
# spiffe://example.test/ns/prod/sa/orders
pkill -f 'demo -dir /tmp/tlslab-mtls'

4. What TLS costs on loopback (real) ​

bash
go test -run xxx -bench . -benchmem -benchtime=2s ./bench
# cpu: Apple M4 Pro
# BenchmarkPlainHTTP1KeepAlive-12         74481    30179 ns/op     5125 B/op    62 allocs/op
# BenchmarkTLS13HTTP1KeepAlive-12         76189    30790 ns/op     5132 B/op    62 allocs/op
# BenchmarkTLS13HTTP2KeepAlive-12         60741    39442 ns/op     6795 B/op    63 allocs/op
# BenchmarkTLS13NewConnFullHandshake-12    5029   467804 ns/op   143549 B/op   996 allocs/op
# BenchmarkTLS13NewConnResumed-12          5710   421979 ns/op   158536 B/op  1089 allocs/op

Questions to answer from it: why is HTTP/2 slower than HTTP/1.1 on one sequential client (framing, HPACK and stream bookkeeping with no concurrency to exploit)? Why does resumption save so little here?

5. Load test the demo with wrk and h2load (expected, not run) ​

bash
go run ./demo -dir /tmp/tlslab &          # the plain (non-mTLS) server again, on 8443; if a tool rejects the demo CA, see its certificate options
sleep 2
wrk -t4 -c200 -d30s --latency https://localhost:8443/whoami
h2load -n 200000 -c 50 -m 10 -t 4 https://localhost:8443/whoami
h2load -n 20000 -c 100 -m 1 --h1 https://localhost:8443/whoami          # same server over HTTP/1.1
h2load -n 20000 -c 100 --tls-session-file=/tmp/h2.sess https://localhost:8443/whoami   # resumption
# expected: HTTP/2 with -m 10 shows far fewer connections and lower p99 than --h1 at the same total requests;
#           run it twice with the session file: "time for connect" drops on the second run
pkill -f 'demo -dir /tmp/tlslab'

6. Profile during the run (expected, not run) ​

bash
# in main: go http.ListenAndServe("127.0.0.1:6060", pprofmux.Handler())
go tool pprof -top -nodecount=15 'http://127.0.0.1:6060/debug/pprof/profile?seconds=30'
# expected with --h1 and no keep-alive: crypto/ecdsa, crypto/internal/... and syscall.Read near the top
# expected with keep-alive and HTTP/2: net/http (hpack, frame parsing), your handler, runtime GC

7. Slowloris and the handshake timeout (real) ​

bash
go test -count=1 -v -run TestSlowHeaderIsCutOff ./timeouts
#     timeouts_test.go:48: slow client dropped after 150ms (read error: EOF)
# --- PASS: TestSlowHeaderIsCutOff (0.16s)

For PHP/Laravel developers ​

PHP-FPM does not do TLS or HTTP/2 at all: Nginx or Apache terminates TLS and speaks HTTP/2 (an http2 setting in the Nginx server block, Protocols h2 http/1.1 in Apache's mod_http2 documentation), and FastCGI carries plain requests to PHP, so a Laravel developer has usually never configured a cipher suite, MinVersion, or a certificate reload. Certificates come from certbot or the host. Laravel's docs say the same thing from the application side: behind a TLS-terminating load balancer "your application sometimes does not generate HTTPS links", which you fix by trusting the proxy with the trustProxies middleware method in bootstrap/app.php (Go equivalent: read X-Forwarded-Proto only from the proxy's address, or use the PROXY protocol). Laravel Octane under FrankenPHP is the closest PHP analogue to a Go server that terminates TLS itself: its docs describe modifying the Sail command "to enable HTTPS, HTTP/2, and HTTP/3", with FrankenPHP configured through a Caddyfile (php artisan octane:start --server=frankenphp --caddyfile=...). For outgoing calls Laravel's Http facade wraps Guzzle, and withOptions passes Guzzle request options straight through, including verify (path to a CA bundle) and cert and ssl_key (client certificate), which is mTLS from PHP.

php
// Laravel: outgoing mTLS with a private CA (Guzzle options through withOptions).
$response = Http::withOptions([
    'verify'  => '/etc/ssl/internal-ca.pem',          // like RootCAs; never 'verify' => false
    'cert'    => '/etc/ssl/orders-client.crt',          // like Certificates[0].Certificate
    'ssl_key' => '/etc/ssl/orders-client.key',          // like the key in tls.Certificate
])->get('https://payments.internal/refunds');
Laravel / PHP worldGo
Nginx or Apache terminates TLS and HTTP/2http.Server + tls.Config; ALPN picks h2
certbot renews, nginx -s reloadautocert, or a Reloader with GetCertificate
ssl_protocols TLSv1.2 TLSv1.3;MinVersion: tls.VersionTLS12
ssl_verify_client on; ssl_client_certificate ca.pem;ClientAuth: RequireAndVerifyClientCert, ClientCAs
$_SERVER['SSL_CLIENT_S_DN'] in PHPr.TLS.VerifiedChains[0][0] (verified)
trustProxies for X-Forwarded-ProtoCheck the proxy address yourself
Http::withOptions(['verify' => false])InsecureSkipVerify: true (same sin)
ab, siege, k6wrk, h2load, vegeta, hey, oha
php-fpm per-request process, no handshake stateLong-lived process: pools, tickets, rotation are your job

Common misconceptions ​

BeliefReality
"HTTPS means the site is safe."It means encrypted transport to the named host; phishing sites have valid certificates.
"InsecureSkipVerify only silences an error."It disables authentication; any certificate from anyone is accepted.
"I need x/net/http2 for HTTP/2."net/http negotiates h2 automatically over TLS since Go 1.6.
"A custom TLSClientConfig keeps HTTP/2."It disables it unless ForceAttemptHTTP2 is true.
"h2c needs x/net/http2/h2c."Go 1.24 has Protocols.SetUnencryptedHTTP2; the package is deprecated.
"Go supports HTTP/3 in net/http."Only github.com/quic-go/quic-go/http3; the standard library has no public switch.
"TLS 1.3 gives me 0-RTT."Go's TLS server never accepts 0-RTT; quic-go's HTTP/3 server does.
"I should set CipherSuites to be secure."TLS 1.3 suites are not configurable, the order is ignored, and the default list is already conservative.
"Setting ClientAuth enables mTLS."Only RequireAndVerifyClientCert verifies and requires; also set ClientCAs.
"A valid client certificate means the caller is authorised."It proves who signed the identity; you still need an allow list.
"VerifyPeerCertificate always runs."Not on resumed connections; use VerifyConnection for must-run checks.
"The Common Name is the host name."Go ignores it since 1.15; names must be in the SAN.
"Go checks revocation."Certificate.Verify does none.
"A redirect to HTTPS is enough."The first request is still plain; add HSTS (and preload when ready).
"wrk benchmarks HTTP/2."wrk is HTTP/1.1; use h2load, oha, hey or vegeta -http2.
"Higher requests/sec means a faster server."Only with zero errors, a stated payload, and tail latency measured open-loop.
"More connections, more throughput."Past saturation it only adds queueing and memory.

Cheat sheet ​

TopicWhat to remember
Server in one linesrv.ListenAndServeTLS("", "") with TLSConfig set; HTTP/2 is automatic
Minimum configMinVersion: tls.VersionTLS12 (or 1.3 internally); leave CipherSuites and CurvePreferences nil
Client configRootCAs, ServerName, ForceAttemptHTTP2: true on a custom Transport
CertificatesSAN, not CN; fullchain.pem (leaf + intermediates); ECDSA P-256; Leaf set
Local devmkcert or an in-code CA; never InsecureSkipVerify
Public certificatesautocert with HostPolicy, DirCache; ports 80 and 443; 90-day certificates, renew at 60
HTTP/2 off switchesServer.Protocols, TLSNextProto, GODEBUG=http2server=0; custom client transports
h2cProtocols.SetUnencryptedHTTP2(true); client Transport.Protocols
HTTP/3quic-go/http3, Alt-Svc header; UDP 443
mTLS serverRequireAndVerifyClientCert + ClientCAs + VerifyConnection allow list
mTLS clientCertificates (or GetClientCertificate) + RootCAs + ServerName
IdentityURI SAN spiffe://..., exactly one; authorise in code
RotationGetCertificate + atomic.Pointer, reload only on successful parse
ResumptionClientSessionCache on the client; SetSessionTicketKeys across replicas; no 0-RTT in Go
Redirect and HSTS308 to a configured host; Strict-Transport-Security over TLS only
Debuggingopenssl s_client -alpn h2, curl -v --http2, KeyLogWriter, GODEBUG
TimeoutsReadHeaderTimeout (also the handshake), IdleTimeout, MaxHeaderBytes; no global WriteTimeout for streams
Load toolswrk (h1, closed), h2load (h2/h3), vegeta/wrk2 (open), hey/oha (quick)
Reading resultsErrors first, then p50/p90/p99/p99.9, then req/s; Little's law
RuntimeGo 1.25+ container-aware GOMAXPROCS; Go raises the fd soft limit since 1.19; pprof on loopback

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Your Go client works against the staging API but fails in production with x509: certificate signed by unknown authority. The quick fix on the team chat is InsecureSkipVerify: true. What do you do instead? Must-know ​

Answer

Answer: Find out which CA issued the production certificate and whether the server sends its intermediate. If the CA is private, put it in RootCAs; if the server omits the intermediate, fix the server to send the full chain. InsecureSkipVerify keeps the encryption but lets any party with any certificate impersonate the server (the source calls it "susceptible to machine-in-the-middle attacks"). If you must tolerate a self-signed device, pin its public key in VerifyConnection (see InsecureSkipVerify).

2 — Why does a custom http.Transport with a TLSClientConfig talk HTTP/1.1 to an HTTP/2 server, and how do you fix it? Must-know ​

Answer

Answer: http.Transport "conservatively disables HTTP/2" whenever TLSClientConfig, DialContext or similar fields are set. Set ForceAttemptHTTP2: true (what http.DefaultTransport does) so the client again offers h2 in ALPN, and check resp.Proto once. See HTTP/2 in Go.

3 — What exactly is ALPN, and how do you see which protocol a Go server negotiated? Must-know ​

Answer

Answer: Application-Layer Protocol Negotiation (RFC 7301) is a TLS extension in which the client lists protocols (h2, http/1.1) and the server picks one inside the handshake, at no extra round trip. In Go it is Config.NextProtos; the result is ConnectionState.NegotiatedProtocol (r.TLS.NegotiatedProtocol in a handler), and r.Proto shows HTTP/2.0 or HTTP/1.1. A client that sends no ALPN leaves it empty and gets HTTP/1.1.

4 — A server sets ClientAuth: tls.RequestClientCert and expects it to behave like mTLS. Why is that unsafe, and what should it use? Important ​

Answer

Answer: RequestClientCert asks for a certificate but does not require one and does not verify the chain, so an anonymous or forged client gets through unless your code checks. Use RequireAndVerifyClientCert with ClientCAs set to your own CA pool (a nil ClientCAs lets the verifier fall back to the system roots), then authorise the identity (for example a SPIFFE URI SAN) in VerifyConnection. See mTLS server side.

5 — Where do you put an identity allow list: VerifyPeerCertificate or VerifyConnection, and why? Important ​

Answer

Answer: In VerifyConnection. VerifyPeerCertificate is "not invoked on resumed connections", and since Go 1.21 servers skip client certificate verification on resumption (besides the expiry check), so a returning client would bypass the allow list. VerifyConnection "will run for all connections, including resumptions". The same warning applies to configs returned by GetConfigForClient, because tickets can be accepted across parent and child configs.

6 — How do you serve a renewed certificate without restarting, and what happens to connections that are already open? Must-know ​

Answer

Answer: Set Config.GetCertificate to a function that returns the current *tls.Certificate from an atomic.Pointer, and replace the pointer only after tls.LoadX509KeyPair succeeds (so a half-written file keeps the old certificate). The next handshake uses the new certificate; open connections keep the one they negotiated, so long-lived HTTP/2 or gRPC connections need GOAWAY, a maximum connection age or a rolling restart. See Rotation.

7 — Is 0-RTT available in Go's TLS server, and what is the risk where it is available? Important ​

Answer

Answer: No. Go's crypto/tls server does not accept early data and answers a client's early_data with an alert, so there is nothing to configure or replay-protect. Where 0-RTT exists (quic-go's HTTP/3, other servers), RFC 8446 warns that early data "is not forward secret" and has "no guarantees of non-replay", so only idempotent requests are safe; RFC 8470 defines Early-Data: 1 and 425 Too Early for rejecting the rest. See resumption.

8 — Your http.Server has no ReadTimeout, WriteTimeout or ReadHeaderTimeout. How does that affect TLS handshakes? Important ​

Answer

Answer: The handshake deadline is "the minimum of any positive ReadHeaderTimeout, ReadTimeout, or WriteTimeout". With all three zero there is no handshake timeout, so a client that connects and never finishes the handshake (or finishes it and never sends headers) holds a goroutine and a socket indefinitely. A nonzero ReadTimeout alone does bound it, because a zero ReadHeaderTimeout and a zero IdleTimeout fall back to ReadTimeout, but one value for everything is blunt. Set ReadHeaderTimeout (about 5 s) and IdleTimeout explicitly; per-request write deadlines via http.ResponseController handle streaming. See timeouts.

9 — You run wrk -t4 -c200 against an HTTP/2 API and compare with h2load -c 20 -m 10. What is each tool actually doing, and why are the numbers not comparable? Must-know ​

Answer

Answer: wrk is an HTTP/1.1 generator: 200 connections, one request in flight on each. h2load speaks HTTP/2: 20 connections with up to 10 concurrent streams each, so 200 requests in flight but ten times fewer handshakes, with header compression, and by default a huge flow-control window (-w, -W change that). They exercise different server paths (connection accept and TLS versus stream multiplexing), so compare like with like: h2load --h1 versus h2load on the same server, with the same payload and zero errors.

10 — What is coordinated omission, and which load tools avoid it? Important ​

Answer

Answer: A closed-loop generator sends the next request on a connection only after the previous reply arrives, so when the server stalls the generator stops offering load and the stall is recorded as one slow request instead of the many that would have queued. The percentiles look better than any real user would see. Constant-rate tools send on a schedule and are built to avoid this: vegeta attack -rate (its README says it avoids Coordinated Omission), wrk2 -R (constant throughput, corrected latency) and oha -q ... --latency-correction. h2load --rps is only a per-client rate limit: the manual defines request latency as from sending the first byte to receiving the last byte of the response, so it does not add scheduling delay and should not be treated as a correction. See tools.

11 — Can a Go program serve HTTP/3 with the standard library? Good to know ​

Answer

Answer: No. http.Protocols has an unexported HTTP/3 bit used only for internal tests, and ListenAndServeTLS with it returns "http: Server.Protocols contains HTTP3, but Server does not support HTTP/3". Use github.com/quic-go/quic-go/http3 (http3.Server, http3.ConfigureTLSConfig) over UDP, and advertise it with an Alt-Svc header from your HTTP/1.1 or HTTP/2 listener. See HTTP/3.

12 — Why did a Kubernetes pod with a 2-CPU limit on a 64-core node show latency spikes before Go 1.25, and what changed? Good to know ​

Answer

Answer: GOMAXPROCS defaulted to the number of logical CPUs of the node (64), so the runtime ran many threads that the cgroup CPU quota then throttled, producing periodic stalls. Go 1.25 made the default container-aware: "the runtime considers the CPU bandwidth limit of the cgroup" and updates it periodically, unless GOMAXPROCS is set by environment variable or runtime.GOMAXPROCS. On earlier versions use automaxprocs or set the variable from the limit. See tuning.

Glossary ​

TermMeaning
ACMEAutomatic Certificate Management Environment (RFC 8555): the protocol clients use to get certificates from a CA
AEADAuthenticated encryption with associated data (AES-GCM, ChaCha20-Poly1305): the only cipher kind in TLS 1.3
ALPNApplication-Layer Protocol Negotiation (RFC 7301): the TLS extension that picks h2 or http/1.1
Alt-SvcResponse header that advertises another endpoint or protocol (HTTP/3) for the same origin
autocertgolang.org/x/crypto/acme/autocert: Go's ACME client and certificate manager
CACertificate authority: signs certificates
Certificate chainLeaf, then intermediates; Go sends the chain you configured, and RFC 8446 lets the trust anchor be omitted
Cipher suiteThe set of algorithms for a TLS 1.2 connection; TLS 1.3 suites are fixed
ClientAuthServer policy for client certificates (NoClientCert to RequireAndVerifyClientCert)
ClientCAsPool of CAs a server trusts for client certificates
Closed loopA load generator that waits for a reply before sending the next request on a connection
Coordinated omissionUnder-reporting of latency because a closed-loop generator slows down with the server
CRLCertificate revocation list
Curve / groupKey-exchange group (X25519, P-256, X25519MLKEM768)
DidResumeConnectionState field: the handshake was a resumption
ECDHEEphemeral elliptic-curve Diffie-Hellman: forward-secret key exchange
ECHEncrypted Client Hello: hides the SNI inside the ClientHello
EKUExtended key usage in a certificate (serverAuth, clientAuth)
GetCertificatetls.Config callback that picks the server certificate per handshake
GetConfigForClienttls.Config callback that picks the whole config per ClientHello
GOAWAYHTTP/2 frame announcing that no new streams will be accepted
GODEBUGEnvironment variable (or //go:debug) that tunes or reverts runtime behaviour
h2 / h2cHTTP/2 over TLS / HTTP/2 over plain TCP
h2loadnghttp2's HTTP/2 (and HTTP/3) benchmarking tool
HPACKHTTP/2 header compression
HSTSHTTP Strict Transport Security (RFC 6797): browsers use HTTPS only
HTTP/3HTTP over QUIC; in Go via quic-go
InsecureSkipVerifytls.Config flag that disables chain and host name verification
KeyLogWritertls.Config field that writes session secrets for Wireshark
LeafThe end-entity certificate of a chain
MaxConcurrentStreamsHTTP/2 limit on simultaneous streams per connection
mkcertTool that creates a local CA and trusted development certificates
ML-KEMPost-quantum key encapsulation (FIPS 203); X25519MLKEM768 is the hybrid
mTLSMutual TLS: both sides present and verify certificates
OCSP staplingThe server attaches a CA-signed revocation status to the handshake
Open loopA load generator that sends on a schedule regardless of replies
PEMText encoding of certificates and keys (base64 between BEGIN and END lines)
PKIPublic key infrastructure: CAs, certificates, trust stores
Prior knowledgeStarting HTTP/2 without negotiation (h2c)
QUICUDP-based transport with TLS 1.3 built in
RootCAsPool of CAs a client trusts for server certificates
SANSubject Alternative Name: DNS names, IPs and URIs a certificate is valid for
Session ticketEncrypted resumption state the server gives the client
SNIServer Name Indication: the host name in the ClientHello
SPIFFE IDWorkload identity as a URI SAN, spiffe://trust-domain/path
TLS terminationEnding the TLS session at a proxy or load balancer
VerifyConnectiontls.Config hook run on every connection, including resumed ones
VerifyPeerCertificatetls.Config hook run after built-in verification, not on resumption
wrkHTTP/1.1 closed-loop benchmarking tool with Lua scripting
0-RTTSending application data in the first flight on resumption; not accepted by Go's TLS server

References ​

Built by Morteza Negahi