为Autocert (golang) 实现通配符证书功能
时间:2024-02-25
浏览:302
作者:佚名
golang学习网今天将给大家带来《为Autocert (golang) 实现通配符证书功能》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
问题内容
实现具有通配符证书支持的 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”支持
正确答案
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://go.dev/play/p/8gGIpnl1NLs 查看演示
终于介绍完啦!小伙伴们,这篇关于《为Autocert (golang) 实现通配符证书功能》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
