ZetCode

Go HTTPS and TLS

last modified November 19, 2026 Go 1.27

In this article we show how to serve and call HTTPS in Go. We create a test certificate, run an HTTPS server, make a client trust the certificate, examine verification errors, configure the TLS version and use client certificates for mutual TLS.

All examples in this article were run with Go 1.27.0, curl 7.81 and OpenSSL 3.0 on Linux. The servers listen on 127.0.0.1:8443. The dates and key material in the outputs differ on every run.

HTTPS and TLS

HTTPS is HTTP sent over a TLS (Transport Layer Security) connection. TLS encrypts the data, protects it against changes and lets the client check that it talks to the right server. The current version is TLS 1.3, defined in RFC 8446.

The server proves its identity with a certificate: a public key together with the names it is valid for, signed by a certificate authority (CA). The client accepts the certificate if it is signed by a CA it trusts, is valid at the current time and contains the host name the client connected to. Public websites get certificates from CAs such as Let's Encrypt, which every operating system trusts. For tests and internal services, we can create our own certificates.

In Go, crypto/tls implements the protocol, crypto/x509 handles certificates, and net/http uses both for HTTPS.

A certificate for testing

The Go distribution contains a small program that generates a self-signed certificate, that is, one signed by its own key. We create one for the loopback address and localhost, and inspect it with openssl.

The --host option sets the names and addresses the certificate is valid for, and --ecdsa-curve P256 creates a small and fast ECDSA key instead of the default RSA key. The program writes the certificate to cert.pem and the private key to key.pem; both are text files in the PEM format. The certificate is valid for one year. The names are stored in the Subject Alternative Name extension, which is what clients check; the subject, here the default organization Acme Co, is only informative.

$ go run $(go env GOROOT)/src/crypto/tls/generate_cert.go --host 127.0.0.1,localhost --ecdsa-curve P256
2026/11/19 16:02:51 wrote cert.pem
2026/11/19 16:02:51 wrote key.pem
$ openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltName
subject=O = Acme Co
issuer=O = Acme Co
notBefore=Nov 19 15:02:51 2026 GMT
notAfter=Nov 19 15:02:51 2027 GMT
X509v3 Subject Alternative Name: 
    DNS:localhost, IP Address:127.0.0.1

An HTTPS server

An HTTPS server differs from an HTTP server in one function call.

https_server.go
package main

import (
    "crypto/tls"
    "fmt"
    "log"
    "net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, "Hello over %s, %s\n",
        tls.VersionName(r.TLS.Version), tls.CipherSuiteName(r.TLS.CipherSuite))
}

func main() {

    http.HandleFunc("GET /", hello)

    log.Println("Listening on https://127.0.0.1:8443")
    log.Fatal(http.ListenAndServeTLS("127.0.0.1:8443", "cert.pem", "key.pem", nil))
}

The handler reports the TLS version and the cipher suite of the connection.

log.Fatal(http.ListenAndServeTLS("127.0.0.1:8443", "cert.pem", "key.pem", nil))

http.ListenAndServeTLS works like ListenAndServe, but it loads the certificate and the key and accepts only TLS connections.

tls.VersionName(r.TLS.Version), tls.CipherSuiteName(r.TLS.CipherSuite))

For HTTPS requests, r.TLS holds the state of the connection; for plain HTTP it is nil. VersionName and CipherSuiteName turn the numeric codes into names.

We test the server with curl. Without options, curl refuses the certificate, because no CA it trusts has signed it; the server logs a handshake error for that connection. With --cacert, curl trusts our certificate. Both 127.0.0.1 and localhost work, because the certificate contains both names.

$ curl https://127.0.0.1:8443/
curl: (60) SSL certificate problem: self-signed certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
$ curl --cacert cert.pem https://127.0.0.1:8443/
Hello over TLS 1.3, TLS_AES_128_GCM_SHA256
$ curl --cacert cert.pem https://localhost:8443/
Hello over TLS 1.3, TLS_AES_128_GCM_SHA256

Trusting a certificate in Go

A Go client verifies certificates against the CAs of the operating system. To trust our certificate, we give the client its own set of roots.

trust_client.go
package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
)

func main() {

    pem, err := os.ReadFile("cert.pem")
    if err != nil {
        log.Fatal(err)
    }

    roots := x509.NewCertPool()
    if !roots.AppendCertsFromPEM(pem) {
        log.Fatal("no certificate found in cert.pem")
    }

    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{RootCAs: roots},
        },
    }

    res, err := client.Get("https://127.0.0.1:8443/")
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()

    body, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    cert := res.TLS.PeerCertificates[0]
    fmt.Println("subject:     ", cert.Subject)
    fmt.Println("valid till:  ", cert.NotAfter.Format("2006-01-02"))
    fmt.Println("names:       ", cert.DNSNames, cert.IPAddresses)
    fmt.Println("key exchange:", res.TLS.CurveID)
    fmt.Print(string(body))
}

The client loads cert.pem as a trusted root and prints details of the connection.

roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(pem) {

A CertPool is a set of certificates. AppendCertsFromPEM adds all certificates found in PEM data and reports whether it found any.

TLSClientConfig: &tls.Config{RootCAs: roots},

The TLS settings of a client live in the transport. With RootCAs set, the client trusts only these roots, not the system ones; a client that should trust both can start from x509.SystemCertPool and add the certificate to it.

cert := res.TLS.PeerCertificates[0]

res.TLS describes the connection on the client side. PeerCertificates holds the chain sent by the server, starting with the server's own certificate. CurveID names the key exchange: Go 1.24 and later use X25519MLKEM768, which combines classic X25519 with a post-quantum algorithm.

$ go run trust_client.go
subject:      O=Acme Co
valid till:   2027-11-19
names:        [localhost] [127.0.0.1]
key exchange: X25519MLKEM768
Hello over TLS 1.3, TLS_AES_128_GCM_SHA256

Verification errors

When verification fails, the request returns an error that wraps the reason. The program tries three clients against the same server.

verify_errors.go
package main

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

func check(name string, client *http.Client) {

    _, err := client.Get("https://127.0.0.1:8443/")

    var unknown x509.UnknownAuthorityError
    var hostErr x509.HostnameError

    switch {
    case err == nil:
        fmt.Printf("%s: ok\n", name)
    case errors.As(err, &unknown):
        fmt.Printf("%s: unknown authority, issuer %s\n", name, unknown.Cert.Issuer)
    case errors.As(err, &hostErr):
        fmt.Printf("%s: certificate is not valid for %s\n", name, hostErr.Host)
    default:
        fmt.Printf("%s: %v\n", name, err)
    }
}

func withConfig(cfg *tls.Config) *http.Client {
    return &http.Client{Transport: &http.Transport{TLSClientConfig: cfg}}
}

func main() {

    pem, err := os.ReadFile("cert.pem")
    if err != nil {
        log.Fatal(err)
    }

    roots := x509.NewCertPool()
    if !roots.AppendCertsFromPEM(pem) {
        log.Fatal("no certificate found in cert.pem")
    }

    check("default client", http.DefaultClient)
    check("own roots", withConfig(&tls.Config{RootCAs: roots}))
    check("other name", withConfig(&tls.Config{RootCAs: roots, ServerName: "api.example.com"}))
}

The check function sends a request and reports why it failed.

case errors.As(err, &unknown):

An x509.UnknownAuthorityError means that the chain does not lead to a trusted root. The default client fails this way, because the certificate is not signed by any CA of the system.

check("other name", withConfig(&tls.Config{RootCAs: roots, ServerName: "api.example.com"}))

ServerName sets the name the client expects in the certificate; by default it is the host of the URL. With a name the certificate does not contain, verification fails with an x509.HostnameError. A certificate that has expired or is not yet valid gives an x509.CertificateInvalidError.

The InsecureSkipVerify option of tls.Config turns all these checks off. A connection that accepts any certificate can be intercepted by anyone on the way, so the option does not belong in production code; trust the certificate instead, as above.

$ go run verify_errors.go
default client: unknown authority, issuer O=Acme Co
own roots: ok
other name: certificate is not valid for api.example.com

Configuring the server

For more control, we create an http.Server with a tls.Config. This server accepts only TLS 1.3.

tls_config.go
package main

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

func hello(w http.ResponseWriter, r *http.Request) {

    w.Header().Set("Strict-Transport-Security", "max-age=31536000")
    fmt.Fprintf(w, "Hello over %s\n", tls.VersionName(r.TLS.Version))
}

func main() {

    mux := http.NewServeMux()
    mux.HandleFunc("GET /", hello)

    srv := &http.Server{
        Addr:    "127.0.0.1:8443",
        Handler: mux,
        TLSConfig: &tls.Config{
            MinVersion: tls.VersionTLS13,
        },
        ReadHeaderTimeout: 5 * time.Second,
        IdleTimeout:       time.Minute,
    }

    log.Println("Listening on https://127.0.0.1:8443")
    log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
}

The server also sets timeouts and an HSTS header.

TLSConfig: &tls.Config{
    MinVersion: tls.VersionTLS13,
},

Go accepts TLS 1.2 and 1.3 by default. Setting MinVersion to TLS 1.3 rejects older clients. Go chooses secure cipher suites itself, so they rarely need to be configured.

w.Header().Set("Strict-Transport-Security", "max-age=31536000")

The Strict-Transport-Security header tells browsers to use only HTTPS for this host for the next year.

The first curl command shows the response headers. The response came over HTTP/2: a Go server negotiates HTTP/2 automatically on TLS connections. The second command limits curl to TLS 1.2 and the server refuses the handshake.

$ curl -i --cacert cert.pem https://127.0.0.1:8443/
HTTP/2 200 
strict-transport-security: max-age=31536000
content-type: text/plain; charset=utf-8
content-length: 19
date: Thu, 19 Nov 2026 15:03:24 GMT

Hello over TLS 1.3
$ curl --cacert cert.pem --tls-max 1.2 https://127.0.0.1:8443/
curl: (35) error:0A00042E:SSL routines::tlsv1 alert protocol version

A client certificate

In mutual TLS, the client also proves its identity with a certificate. This is common between internal services. The generate_cert.go program creates certificates for servers only, so we write our own generator with crypto/x509.

client_cert.go
package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "log"
    "os"
    "time"
)

func writePEM(name, kind string, data []byte, mode os.FileMode) {

    block := pem.EncodeToMemory(&pem.Block{Type: kind, Bytes: data})
    if err := os.WriteFile(name, block, mode); err != nil {
        log.Fatal(err)
    }
    log.Println("wrote", name)
}

func main() {

    key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        log.Fatal(err)
    }

    template := &x509.Certificate{
        Subject:     pkix.Name{CommonName: "reporting-service"},
        NotBefore:   time.Now(),
        NotAfter:    time.Now().Add(90 * 24 * time.Hour),
        KeyUsage:    x509.KeyUsageDigitalSignature,
        ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
    }

    der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
    if err != nil {
        log.Fatal(err)
    }

    keyDER, err := x509.MarshalPKCS8PrivateKey(key)
    if err != nil {
        log.Fatal(err)
    }

    writePEM("client.pem", "CERTIFICATE", der, 0o644)
    writePEM("client-key.pem", "PRIVATE KEY", keyDER, 0o600)
}

The program creates a key, a self-signed certificate for a service called reporting-service, and writes both as PEM files.

key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

The private key is an ECDSA key on the P-256 curve.

ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},

The template describes the certificate. The common name identifies the client, and the extended key usage allows the certificate to be used for client authentication only. A server rejects client certificates without this usage. With no SerialNumber, Go generates a random one.

der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)

The second template argument is the issuer. Passing the certificate itself and its own key makes it self-signed. A real CA would pass its certificate and key here.

writePEM("client-key.pem", "PRIVATE KEY", keyDER, 0o600)

The private key is readable by its owner only.

$ go run client_cert.go
2026/11/19 16:04:02 wrote client.pem
2026/11/19 16:04:02 wrote client-key.pem
$ openssl x509 -in client.pem -noout -subject -ext extendedKeyUsage
subject=CN = reporting-service
X509v3 Extended Key Usage: 
    TLS Web Client Authentication
$ stat -c '%A %s %n' client.pem client-key.pem
-rw-r--r-- 542 client.pem
-rw------- 241 client-key.pem

Mutual TLS

The server now asks every client for a certificate and accepts only those it trusts.

mtls_server.go
package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "log"
    "net/http"
    "os"
)

func hello(w http.ResponseWriter, r *http.Request) {

    client := r.TLS.PeerCertificates[0]
    fmt.Fprintf(w, "Hello, %s\n", client.Subject.CommonName)
}

func main() {

    pem, err := os.ReadFile("client.pem")
    if err != nil {
        log.Fatal(err)
    }

    clientCAs := x509.NewCertPool()
    if !clientCAs.AppendCertsFromPEM(pem) {
        log.Fatal("no certificate found in client.pem")
    }

    mux := http.NewServeMux()
    mux.HandleFunc("GET /", hello)

    srv := &http.Server{
        Addr:    "127.0.0.1:8443",
        Handler: mux,
        TLSConfig: &tls.Config{
            MinVersion: tls.VersionTLS13,
            ClientCAs:  clientCAs,
            ClientAuth: tls.RequireAndVerifyClientCert,
        },
    }

    log.Println("Listening on https://127.0.0.1:8443")
    log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
}

The server loads client.pem as the set of trusted client certificates and greets the client by name.

ClientCAs:  clientCAs,
ClientAuth: tls.RequireAndVerifyClientCert,

ClientAuth makes a certificate mandatory and verifies it against ClientCAs. With a real CA, the pool holds the CA certificate, and any client certificate it signs is accepted.

client := r.TLS.PeerCertificates[0]

In the handler, the verified client certificate identifies the caller, so the server can authorize requests without passwords or tokens.

mtls_client.go
package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
)

func main() {

    cert, err := tls.LoadX509KeyPair("client.pem", "client-key.pem")
    if err != nil {
        log.Fatal(err)
    }

    pem, err := os.ReadFile("cert.pem")
    if err != nil {
        log.Fatal(err)
    }

    roots := x509.NewCertPool()
    if !roots.AppendCertsFromPEM(pem) {
        log.Fatal("no certificate found in cert.pem")
    }

    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                RootCAs:      roots,
                Certificates: []tls.Certificate{cert},
            },
        },
    }

    res, err := client.Get("https://127.0.0.1:8443/")
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()

    body, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Print(string(body))
}

The client presents its certificate and trusts the server's certificate.

cert, err := tls.LoadX509KeyPair("client.pem", "client-key.pem")

tls.LoadX509KeyPair loads a certificate with its private key into a tls.Certificate, which is put into Certificates.

The Go client and curl with --cert and --key get the greeting. Without a client certificate, the server aborts the connection; with TLS 1.3, curl sees this only when it starts writing the request, and its error message varies between runs.

$ go run mtls_client.go
Hello, reporting-service
$ curl --cacert cert.pem https://127.0.0.1:8443/
curl: (16) OpenSSL SSL_write: Broken pipe, errno 32
$ curl --cacert cert.pem --cert client.pem --key client-key.pem https://127.0.0.1:8443/
Hello, reporting-service

Source

Go crypto/tls package - reference
Go crypto/x509 package - reference
RFC 8446 - The Transport Layer Security (TLS) Protocol Version 1.3

In this article we have worked with HTTPS and TLS in Go: a test certificate, an HTTPS server, trusted roots, verification errors, server configuration, a client certificate created with crypto/x509 and mutual TLS. For public servers, the golang.org/x/crypto/acme/autocert package obtains certificates from Let's Encrypt automatically. The httptest article tests code against a TLS server, and the HTTP server and HTTP client articles cover net/http.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.