Create an HTTPS server

suggest change

Generate 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:

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))
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents