'wildcard certificate support using Autocert (golang)

implementing a https go server with wildcard certificate support.

package main

import (
    "crypto/tls"
    "log"
    "net/http"
    "golang.org/x/crypto/acme/autocert"
)

func main() {
    certManager := autocert.Manager{
        Prompt:     autocert.AcceptTOS,
        HostPolicy: autocert.HostWhitelist("example.com"), //Your domain here
        Cache:      autocert.DirCache("certs"),            //Folder for storing certificates
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello world"))
    })

    server := &http.Server{
        Addr: ":https",
        TLSConfig: &tls.Config{
            GetCertificate: certManager.GetCertificate,
        },
    }

    go http.ListenAndServe(":http", certManager.HTTPHandler(nil))

    log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}

couldn't figure out how to add a wildcard pattern to the hostwhitelist.

need support for "*.example.com"



Solution 1:[1]

The HostWhitelist doesn't support wildcards, but because a HostPolicy is merely a function, you can implement your own HostPolicy, using e.g. a regular expression:

var (
    allowedHosts      = regexp.MustCompile(`^[^.]+\.example\.com$`)
    errPolicyMismatch = errors.New("the host did not match the allowed hosts")
)

func CustomHostPolicy(_ context.Context, host string) error {
    if matches := allowedHosts.MatchString(host); !matches {
        return errPolicyMismatch
    }
    return nil
}

See demo on https://go.dev/play/p/8gGIpnl1NLs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1