mkcert と golang の net/http を使い、ローカル環境に HTTPS サーバを立てる

mkcert をインストール(ビルド)する

https://github.com/FiloSottile/mkcert#linux

$ sudo apt install libnss3-tools
$ git clone https://github.com/FiloSottile/mkcert && cd mkcert
$ go build -ldflags "-X main.Version=$(git describe --tags)"

mkcert で証明書とキーを作成する

$ mkcert -install
The local CA is already installed in the system trust store! 👍
The local CA is already installed in the Firefox and/or Chrome/Chromium trust store! 👍

$ mkcert -key-file key.pem -cert-file cert.pem 127.0.0.1 ::1

Created a new certificate valid for the following names 📜
 - "127.0.0.1"
 - "::1"

The certificate is at "cert.pem" and the key at "key.pem" ✅

It will expire on 18 October 2023 🗓

$ ls *.pem
cert.pem  key.pem

HTTPS サーバのサンプルコード

作成した cert.pemkey.pem のパスを http.ListenAndServeTLS に渡します。

package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
    })
    if err := http.ListenAndServeTLS(":5000", "cert.pem", "key.pem", nil); err != nil {
        log.Fatal(err)
    }
}

動作確認

$ curl https://127.0.0.1:5000
Protocol: HTTP/2.0

参考にさせていただいたサイト