GolangWebDev
GolangWebDev
915 0 0

Zero-config tool to make locally trusted

mkcert is a simple tool for making locally-trusted development certificates. It requires no configuration.

$ mkcert -install 
The local CA is now installed in the system trust store! ⚡️
Warning: "certutil" is not available, so the CA can't be automatically installed in Firefox! ⚠️
Install "certutil" with "brew install nss" and re-run "mkcert -install" 
$ mkcert 127.0.0.1
Note: the local CA is not installed in the Firefox trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️

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

The certificate is at "./127.0.0.1.pem" and the key at "./127.0.0.1-key.pem" ✅

It will expire on 3 April 2025 

Add certFile and keyFile to web server:

package main

import (
	"flag"
	"fmt"
	"github.com/klauspost/compress/gzhttp"
	"net"
	"net/http"
	"strings"
)

func main() {
	certFile := flag.String("c", "localhost.pem", "full path of cert File")
	keyFile := flag.String("k", "localhost-key.pem", "full path of key File")

	flag.Parse()

	//certFile, keyFile := "localhost.pem", "localhost-key.pem"
	s := &http.Server{
		Addr: ":https",
		Handler: gzhttp.GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
			fmt.Fprintf(w, strings.Repeat("Hello ssl! ", 1024))
		})),
	}
	go http.ListenAndServe(":http", http.HandlerFunc(handleHTTPRedirect))
	_ = s.ListenAndServeTLS(*certFile, *keyFile)
}

func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" && r.Method != "HEAD" {
		http.Error(w, "Use HTTPS", http.StatusBadRequest)
		return
	}
	target := "https://" + stripPort(r.Host) + r.URL.RequestURI()
	http.Redirect(w, r, target, http.StatusFound)
}

func stripPort(hostport string) string {
	host, _, err := net.SplitHostPort(hostport)
	if err != nil {
		return hostport
	}
	return net.JoinHostPort(host, "443")
}

Read more https://github.com/FiloSottile/mkcert

0

See Also


Discussion

Login Topics