How to Use HTTPS/TLS in Go

Enable HTTPS in Go by loading certificate and key files into a tls.Config and passing it to your HTTP server.

Use the crypto/tls package to create a secure listener or client by loading your certificate and key files.

package main

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

func main() {
	cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
	if err != nil {
		panic(err)
	}
	tlsConfig := &tls.Config{Certificates: []tls.Certificate{cert}}
	server := &http.Server{
		Addr:      ":443",
		TLSConfig: tlsConfig,
	}
	server.ListenAndServeTLS("", "")
}