Create an HTTPS server
suggest changeGenerate a certificate
An HTTPS server needs a certificate and private key. For local development, generate a self-signed pair with openssl:
openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout key.pem -out cert.pem -subj "/CN=example.com" -days 3650
The parameters are:
reqUse the certificate request toolx509Creates a self-signed certificatenewkey rsa:4096Creates a new key and certificate by using the RSA algorithms with4096bit key lengthsha256Forces the SHA256 hashing algorithms which major browsers consider as secure (at the year 2017)nodesleaves the private key unencrypted. Without it, the server asks for the password each time it starts.keyoutnames the file that receives the keyoutnames the file that receives the certificatesubjsets the domain name this certificate is valid fordayssets how many days the certificate is valid.3650is about 10 years.
A self-signed certificate is fine for internal projects, debugging, and tests. Browsers will warn that it is not trusted. To avoid that, the certificate must be signed by a certification authority. Let’s Encrypt is one free option: https://letsencrypt.org
The necessary Go code
Pass the resulting cert.pem certificate and key.pem private key to the
server. Browsers will warn about this self-signed certificate; use a certificate
issued by a trusted authority in production.
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
})
log.Fatal(http.ListenAndServeTLS(":443","cert.pem","key.pem", nil))
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents