使用通配符证书支持实现https go服务器。
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
}无法知道如何将通配符模式添加到主机白名单。
需要支持"*.example.com“
发布于 2022-05-11 14:41:38
HostWhitelist不支持通配符,但是由于HostPolicy只是一个函数,所以可以使用正则表达式实现自己的HostPolicy:
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
}https://stackoverflow.com/questions/71741888
复制相似问题